id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_webmaster.55477 | I would like to set up search queries in Google Analytics to have stats of site searches, however it doesn't seem to show me any stats. This is what I have entered so far:On my site, searching (or getting search results) can be done in a couple ways - simple and rewritten. Here are examples of that:http://example.com/?search=mobile+phonehttp://example.com/search/mobile%20phone/date/1.htmlWhat do I need to enter into the fields to have my searches tracked correctly in Google Analytics? | How to track site searches in Google Analytics? | google analytics;site search | It seems that Google Analytics only supports query string parameters for these fields. So, you should simply enter the value search (without an equals sign). It does not support regular expressions, or any other form of URL.Personally, I would argue against using pretty URLs (e.g. /search/mobile%20phone/date/1.html) for search queries. But, if you do want to use them, you can override the URL in the Javascript code:ga('send', 'pageview', '/?search=mobile+phone');(Source).You could of course place regular expressions here, and rewrite accordingly, but I will leave the implementation to you. |
_codereview.144760 | I have 3 ToolBars that I use across my whole application The first one is just a ToolBar with a close button.The second one is a ToolBar with a close and delete icon.The third one is a ToolBar with a close and home icon.Here is my case, I use this ToolBar in many places, and I dont want to use Fragment for some reasons so I am forced to use Activity.For usability, I created methods to handle their functions, but I am sure I can do something to make this easier as I repeat this code in each activity.toolbar_layout.xml<?xml version=1.0 encoding=utf-8?><android.support.v7.widget.Toolbar xmlns:android=http://schemas.android.com/apk/res/android xmlns:app=http://schemas.android.com/apk/res-auto android:layout_width=match_parent android:layout_height=wrap_content android:minHeight=?attr/actionBarSize android:background=@color/app_bg > <RelativeLayout android:layout_width=match_parent android:layout_height=wrap_content> <ImageView android:id=@+id/CloseImageView android:layout_width=wrap_content android:layout_height=wrap_content app:srcCompat=@drawable/ic_chevron_left_white_48dp /> <TextView android:id=@+id/toolbarTitle android:layout_width=wrap_content android:layout_height=wrap_content android:text=ToolBar Title android:gravity=center android:layout_centerVertical=true android:layout_centerHorizontal=true android:textSize=18sp android:textColor=@color/white /> </RelativeLayout></android.support.v7.widget.Toolbar>toolbar_layout_delete_icon.xml<?xml version=1.0 encoding=utf-8?><android.support.v7.widget.Toolbar xmlns:android=http://schemas.android.com/apk/res/android xmlns:app=http://schemas.android.com/apk/res-auto xmlns:tools=http://schemas.android.com/tools android:layout_width=match_parent android:layout_height=wrap_content android:minHeight=?attr/actionBarSize android:background=@color/app_bg > <android.support.constraint.ConstraintLayout android:layout_width=match_parent android:layout_height=wrap_content> <ImageView android:id=@+id/CloseImageView android:layout_width=wrap_content android:layout_height=wrap_content app:srcCompat=@drawable/ic_chevron_left_white_48dp tools:layout_constraintBottom_creator=1 app:layout_constraintBottom_toBottomOf=parent tools:layout_constraintLeft_creator=1 app:layout_constraintLeft_toLeftOf=parent app:layout_constraintTop_toTopOf=parent /> <TextView android:id=@+id/toolbarTitle android:layout_width=wrap_content android:layout_height=wrap_content android:text=ToolBar Title android:gravity=center android:textSize=18sp android:textColor=@color/white tools:layout_constraintBottom_creator=1 android:layout_marginStart=84dp app:layout_constraintBottom_toBottomOf=parent tools:layout_constraintLeft_creator=1 android:layout_marginBottom=16dp app:layout_constraintLeft_toRightOf=@+id/CloseImageView android:layout_marginLeft=84dp app:layout_constraintHorizontal_bias=0.54 /> <ImageView android:id=@+id/DeleteImageView android:layout_width=wrap_content android:layout_height=wrap_content app:srcCompat=@drawable/ic_delete_icon_36dp tools:ignore=MissingConstraints app:layout_constraintTop_toTopOf=parent app:layout_constraintRight_toRightOf=parent app:layout_constraintBottom_toBottomOf=parent android:layout_marginEnd=16dp android:layout_marginRight=16dp /> </android.support.constraint.ConstraintLayout></android.support.v7.widget.Toolbar>toolbar_layout_home_icon.xml<?xml version=1.0 encoding=utf-8?><android.support.v7.widget.Toolbar xmlns:android=http://schemas.android.com/apk/res/android xmlns:app=http://schemas.android.com/apk/res-auto android:layout_width=match_parent android:layout_height=wrap_content android:minHeight=?attr/actionBarSize android:background=@color/app_bg > <RelativeLayout android:layout_width=match_parent android:layout_height=wrap_content> <ImageView android:id=@+id/CloseImageView android:layout_width=wrap_content android:layout_height=wrap_content app:srcCompat=@drawable/ic_chevron_left_white_48dp /> <TextView android:id=@+id/toolbarTitle android:layout_width=wrap_content android:layout_height=wrap_content android:text=ToolBar Title android:gravity=center android:layout_centerVertical=true android:layout_centerHorizontal=true android:textSize=18sp android:textColor=@color/white /> <ImageView android:layout_width=wrap_content android:layout_height=wrap_content app:srcCompat=@drawable/ic_home_white_36dp android:layout_centerVertical=true android:layout_alignParentRight=true android:layout_alignParentEnd=true android:layout_marginRight=15dp android:layout_marginEnd=15dp android:id=@+id/HomeImageView /> </RelativeLayout></android.support.v7.widget.Toolbar>java method that handles the ToolBar :private void setupToolbar() { Toolbar mytoolbar = (Toolbar) findViewById(R.id.mytoolbar); TextView toolbarTitle = (TextView) mytoolbar.findViewById(R.id.toolbarTitle); toolbarTitle.setText(getResources().getString(R.string.submit_claim)); ImageView closeButton = (ImageView) mytoolbar.findViewById(R.id.CloseImageView); closeButton.setOnClickListener(v -> finish()); ImageView HomeButton = (ImageView) mytoolbar.findViewById(R.id.HomeImageView); HomeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent(PolicyAndContactDetailActivity.this , MainActivity.class); mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(mIntent); finish(); } }); }I need to minimize my code as much as possible, and any help with @+id names will be appreciated. | Android - Share ToolBar across whole application | java;android | null |
_unix.196615 | Running Mint 17.1 with Cinammon 2.4.8 and I have two 2560 * 1440 monitors, both placed in the display settings as next to each other, not mirrored.The mouse cursor moves as normal between the two monitors, except for about 16 pixels from the top and the bottom of the right hand side of the left monitor. Then the cursor just won't move any further right until I move it more than 16 pixels away from the top or bottom of the screen.This is about the height of a panel or title bar, so my first thought was to close all applications and try it with an empty desktop. Still happens. Same with moving the taskbar panel from the bottom.I also tried swapping the displays around but it still happens. Even setting the displays offset so that for example, the cursor coming from halfway down the left screen goes to the top of the right screen or vice versa has no effect; the cursor still gets stuck at the top and bottom 16 pixels of the left screen.Output of xdpyinfo:name of display: :0version number: 11.0vendor string: The X.Org Foundationvendor release number: 11501000X.Org version: 1.15.1maximum request size: 16777212 bytesmotion buffer size: 256bitmap unit, bit order, padding: 32, LSBFirst, 32image byte order: LSBFirstnumber of supported pixmap formats: 7supported pixmap formats: depth 1, bits_per_pixel 1, scanline_pad 32 depth 4, bits_per_pixel 8, scanline_pad 32 depth 8, bits_per_pixel 8, scanline_pad 32 depth 15, bits_per_pixel 16, scanline_pad 32 depth 16, bits_per_pixel 16, scanline_pad 32 depth 24, bits_per_pixel 32, scanline_pad 32 depth 32, bits_per_pixel 32, scanline_pad 32keycode range: minimum 8, maximum 255focus: window 0x3804196, revert to Parentnumber of extensions: 29 BIG-REQUESTS Composite DAMAGE DOUBLE-BUFFER DPMS DRI2 DRI3 GLX Generic Event Extension MIT-SCREEN-SAVER MIT-SHM Present RANDR RECORD RENDER SECURITY SGI-GLX SHAPE SYNC X-Resource XC-MISC XFIXES XFree86-DGA XFree86-VidModeExtension XINERAMA XInputExtension XKEYBOARD XTEST XVideodefault screen number: 0number of screens: 1screen #0: dimensions: 5120x1440 pixels (1355x381 millimeters) resolution: 96x96 dots per inch depths (7): 24, 1, 4, 8, 15, 16, 32 root window id: 0x9f depth of root window: 24 planes number of colormaps: minimum 1, maximum 1 default colormap: 0x22 default number of colormap cells: 256 preallocated pixels: black 0, white 16777215 options: backing-store WHEN MAPPED, save-unders NO largest cursor: 64x64 current input event mask: 0xfac033 KeyPressMask KeyReleaseMask EnterWindowMask LeaveWindowMask KeymapStateMask ExposureMask StructureNotifyMask SubstructureNotifyMask SubstructureRedirectMask FocusChangeMask PropertyChangeMask ColormapChangeMask number of visuals: 20 default visual id: 0x20 visual: visual id: 0x20 class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x21 class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x8d class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x8e class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x8f class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x90 class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x91 class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x92 class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x93 class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x94 class: TrueColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x95 class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x96 class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x97 class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x98 class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x99 class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x9a class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x9b class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x9c class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x9d class: DirectColor depth: 24 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits visual: visual id: 0x60 class: TrueColor depth: 32 planes available colormap entries: 256 per subfield red, green, blue masks: 0xff0000, 0xff00, 0xff significant bits in color specification: 8 bits | Dual Monitors on Cinnamon 2.4.8 - cursor gets stuck on bottom and top right of left screen | linux mint;mouse;cinnamon;dual monitor | null |
_scicomp.18669 | I don't understand the concept with local and global vec's in petsc when it come to DMDAVecGetArray and VecGetValues. I'm creating some DMDA Vec in parallel which works well. Now I want to access certain non local values of my Vec without receiving the whole global array (will not fit into my main memory) on each processor.Is there something I'm getting wrong? In the documentation of VecGetValues it is written Gets values from certain locations of a vector. Currently can only get values on the same processor. thx | Get a single value from a global Vec in petsc | c++;petsc;vector | null |
_unix.140630 | Is there a way to make &>/dev/null the default behavior in a sh/bash script? I' rather not have to appended this to every command within the console, not an *.sh script.I'm looking to make a global setting...or at least a custom alias of some sort, but one that makes any command and every command, auto-append &>/dev/null to the end.Any ideas? | How do I enable &>/dev/null by default for all sh/bash commands? | bash;stderr;null | null |
_cs.63904 | I have multiples arrays. I'd like to enumerate all sets containing exactly one item from each array in a (pseudo-)random order, without explicitly building the array of all sets. Any solution, even with poor pseudo-randomization, is welcome.EDIT: Example for clarity:Say I have arrays A = { a1, a2 }, B = { b1, b2 }, C = { c1 }I want to enumerate all the sets containing exactly one ax, bx and cx{ a1, b1, c1 }, { a1, b2, c1 }, { a2, b1, c1 }, { a2, b2, c1 }I want to enumerate them in a random order. The nave solution would be to enumerate them in an array, then shuffle this array. But the solution is huge and I don't want to store it explicitely in memory. | Enumerating sets in a random order | algorithms;sets;randomness;enumeration | Suppose that you have arrays $A_1,\ldots,A_d$ of sizes $n_1,\ldots,n_d$. The total number of tuples is thus $n_1 \times \cdots \times n_d$. Given a number in the range $1,\ldots,n_1 \times \cdots \times n_d$, you can decipher it into a tuple (I leave this part to you). It now remains to compute a pseudorandom permutation of the numbers $1,\ldots,n_1 \times \cdots \times n_d$, another task I leave to you. |
_unix.181522 | In my repos I'm implementing a new interesting strategy to preserve some versioned files from merges, that makes use of custom merge drivers and .gitattributes. Please take a look:http://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#Merge-StrategiesI noticed though, that if I apply it to files already tracked in repo/branches, it doesn't work. To make it work, I have to either define the paths in .gitattributes before adding the files to the repo/branch, or delete the files and add them again.Not a big problem, but I'm quite curious of the reason of this behavior. Does anyone know? | Why is .gitattributes applied only to files added to repo after defining it? | git;merge | null |
_codereview.141402 | I got an idea to make a Roman/Arabic number converter, and I would like to hear your thoughts, where I could improve it, if there are Python specific things that I missed, so on and so forth.# Decodes roman numeralsdef get_arabic_numbers(t): # Hold the numbers in the list l = list() # The format format = 0 # Convert from roman numeral to arabic number for i in range(0, len(t)): if t[i] == 'I': l.append(int(1)) elif t[i] == 'V': l.append(int(5)) elif t[i] == 'X': l.append(int(10)) elif t[i] == 'L': l.append(int(50)) elif t[i] == 'C': l.append(int(100)) elif t[i] == 'D': l.append(int(500)) elif t[i] == 'M': l.append(int(1000)) # Calculate the format as follows: i = 0 while i < len(l) - 1: # If the next numeral is greater than the current one, add the next one minus the current one = format = format + next_numeral - current_numeral if l[i] < l[i+1]: format = format + l[i+1] - l[i]; i = i + 2 # Else add it normally else: format = format + l[i] i = i + 1 # Fix in case the last two numerals are equal if i == len(l): if l[i-2] == l[i-1]: format = format + l[i-1] else: format = format + l[i] # Return the format return format# Encode an arabic digit to a roman numeraldef encode(l, c, one, five, nine): # The format to be returned format = # Special case 5.1: 5 has its own numeral 'V' # Special case 5.2: 50 has its own numeral 'A' # Special case 5.3: 500 has its own numeral 'D' if l[c] == 5: format = format + five elif l[c] < 5: for i in range(0, l[c]): format = format + one elif l[c] > 5: # Special case 9.1: 9 depends on 10, so it's 'IX' # Special case 9.2: 90 depends on 1000, so it's 'XC' # Special case 9.3: 900 depends on 1000, so it's 'CM' if l[c] == 9: format = format + nine else: format = format + five for i in range(6, l[c] + 1): format = format + one return format# Encodes arabic numbersdef get_roman_numerals(t): # The arabic number to be converted t = int(t) # The list contains the number's digits l = list() # int is not iterable, so I wrote this to get the digits while t >= 1: l.append(int(t % 10)) t = t / 10 # They are in the wrong order, so the list has to be reversed l.reverse() # The format format = # Current position in the number c = 0 # If the number is at least 1000 if len(l) >= 4: num = 0 # All the digits after 1000 i = int(len(l) - 1) while i > 3: num = num + 1 i = i - 1 # A list containing these digits li = list() for i in range(0, num + 1): li.append(l[i]) # Converts the list to an int n = map(str, li) n = ''.join(n) n = int(n) # Add an 'M' for every 1000 for i in range(0, n): format = format + 'M' c = num + 1 # If the number is also least 100 if len(l) >= 3: format = format + encode(l, c, 'C', 'D', CM) c = c + 1 # If the number is at least 10 if len(l) >= 3: format = format + encode(l, c, 'X', 'L', XC) c = c + 1 # If the number is at least 100 but smaller than 1000 if len(l) > 2: format = format + encode(l, c, 'I', 'V', IX) # If the number is at least 10 but smaller than 100 if len(l) == 2: format = format + encode(l, c, 'X', 'L', XC) c = c + 1 format = format + encode(l, c, 'I', 'V', IX) # If the number is at least 1 but smaller than 10 if len(l) == 1: format = format + encode(l, c, 'I', 'V', IX) return format | Converting from Roman numerals to Arabic numbers | python;beginner;roman numerals | ImpressionsThat's a very long solution. The comments were generally helpful, but the code itself could have been easier to understand if it were shorter and more expressive.The variable names were generally not helpful: l, i, t, c, li were all cryptic.get_arabic_numbers(t) is not really named appropriately:get implies retrieving something that already exists. This is more of a calculation.Why is numbers plural?Why is the parameter named t what does it stand for?Strictly speaking, the result is an int. It's not Arabic, nor is it even in base ten. It's just an abstract integer, which is conventionally rendered for you as base-ten Arabic digits when str() is called on it (whether explicitly or implicitly). (And by Arabic, we mean 0123456789, not .)Based on these concerns, I'd call it decode_roman_numeral(roman). It happens to be what you wrote as the comment! Similarly, I'd call the inverse function encode_roman_numeral(num).Arabic Roman# The formatformat = 0That's not what I would call a format I would call it a result.# Hold the numbers in the listl = list()# Convert from roman numeral to arabic numberfor i in range(0, len(t)): if t[i] == 'I': l.append(int(1)) elif t[i] == 'V': l.append(int(5)) elif t[i] == 'X': l.append(int(10)) elif t[i] == 'L': l.append(int(50)) elif t[i] == 'C': l.append(int(100)) elif t[i] == 'D': l.append(int(500)) elif t[i] == 'M': l.append(int(1000))As I mentioned before, l is a cryptic name. There is no need to convert 1 to int(1). Lookups are typically done in Python using a dictionary. Also, whenever you populate a list by creating an empty list and appending to it repeatedly, that is a good candidate for a list comprehension:trans = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}values = [trans[r] for r in roman]# Calculate the format as follows:i = 0while i < len(l) - 1: # If the next numeral is greater than the current one, add the next one minus the current one = format = format + next_numeral - current_numeral if l[i] < l[i+1]: format = format + l[i+1] - l[i]; i = i + 2 # Else add it normally else: format = format + l[i] i = i + 1Do you really need a case that advances i by two? How about this instead:result = 0for i in range(0, len(l) - 1): if l[i] < l[i+1]: result -= l[i] else: result += l[i]As I mentioned before, the code could be more expressive. This loop is summing values in a list, so we should use the sum() built-in function to say what we mean.result = sum( val if val >= next_val else -val for val, next_val in zip(values[:-1], values[1:]))All together, then, I'd condense your function down to this:def decode_roman_numeral(roman): Calculate the numeric value of a Roman numeral (in capital letters) trans = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} values = [trans[r] for r in roman] return sum( val if val >= next_val else -val for val, next_val in zip(values[:-1], values[1:]) ) + values[-1]Arabic RomanThe encode() function encodes a single Arabic digit, so encode_digit() would be a better name. There is no point in passing l and c separately, since you only ever care about l[c]. Instead of looping to append characters to format, use the * operator to construct a repeated string.I would write this helper function using a single expression with four cases:def encode_digit(digit, one, five, nine): return ( nine if digit == 9 else five + one * (digit - 5) if digit >= 5 else one + five if digit == 4 else one * digit )The get_roman_numerals() function is rather convoluted. I had a hard time following the code, so I went by your comments instead. In the end, I figured out that it was essentially doing this:def encode_roman_numeral(num): num = int(num) return ( 'M' * (num // 1000) + encode_digit((num // 100) % 10, 'C', 'D', 'CM') + encode_digit((num // 10) % 10, 'X', 'L', 'XC') + encode_digit( num % 10, 'I', 'V', 'IX') ) |
_codereview.154676 | I have a Data First Migration and have been struggling a little with storing an enum value as a string.(Im aware that enums should be stored as ints but, personally I have never liked this, yes enums are hard and fast values but I have always percived them to vary a little bit as the code evolves, i am therefore worried about the integrity of using an int value as new values are added.) However in my example I need to store the value as a string anyway so that other systems will be able to understand it.So the database has the following generated propertypublic string billing_location { get; set; }The View Modelpublic string billing_location { get; set; }public MobiusBillingLocation BillingLocation{ get { MobiusBillingLocation mbl; if (Enum.TryParse(billing_location, true, out mbl)) { return (MobiusBillingLocation) Enum.Parse(typeof(MobiusBillingLocation), billing_location, true); } return MobiusBillingLocation.None; } //This also needs setting in the controller code set { billing_location = value == MobiusBillingLocation.None ? null : value.ToString(); }}public enum MobiusBillingLocation { None, UK, US, SGSingapore }The code has been designed so that it will be happy with null values and translates None as null and back again.My questions are, does this approach seem reasonable?Any ideas / suggestions for improvments?Would you use this approach for enums on a code first model for example?UPDATEI will add that, in this database, due to it being legacy and unnormalized (thats another topic) and has systems on it that i can't touch I cant be adding extra lookup tables at this time, the data in it however needs to have meaning to a user, ie integer values won't work as they don't pass meaning.I am however also interested in some side discussion about use of enums. | Storing Enum values as Strings in DB | c#;strings;entity framework;enum | null |
_codereview.69687 | I am working on a library in which I need to make synchronous and asynchronous methods in my client library.My library does this:The customer will use our library and they will call it by passing user_id. We will then construct a URL by using that userId and make an HTTP client call to that URL. We will then get a JSON string back after hitting the URL. And after we get the response back as a JSON string, then we will send that JSON String back to our customer as it is.Now I need to have synchronous and asynchronous methods. Some customer will call the executeSynchronous method to get the same feature and some customer will call our executeAsynchronous method and with the executeAsynchronous method, they will call future.get in there code itself.Interface:public interface Client { // for synchronous public String executeSynchronous(final String userId); // for asynchronous public Future<String> executeAsynchronous(final String userId);}And then I have SmartClient which implements the Client interface:public class SmartClient implements Client { private RestTemplate restTemplate = new RestTemplate(); private ExecutorService service = Executors.newFixedThreadPool(5); // for synchronous call @Override public String executeSynchronous(String userId) { String response = null; try { Future<String> handle = executeAsynchronous(userId); response = handle.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { e.printStackTrace(); } return response; } //for asynchronous call @Override public Future<String> executeAsynchronous(String userId) { Future<String> future = null; try { Task task = new Task(userId, restTemplate); future = executor.submit(task); } catch (Exception ex) { e.printStackTrace(); } return future; }}This simple class will perform the actual task:class Task implements Callable<String> { private final String userId; private RestTemplate restTemplate; public Task(String userId, RestTemplate restTemplate) { this.userId = userId; this.restTemplate = restTemplate; } public String call() throws Exception { String url = createURL(userId); // make a HTTP call to the URL String jsonResponse = restTemplate.exchange(url, HttpMethod.GET, null, String.class); return jsonResponse; } // create a URL private String createURL(String userId) { String generateURL = somecode; return generateURL; }}Is this the correct and efficient way of solving this problem? Can we generalize my interface?How about the exception handling?I need to have both synchronous and asynchronous methods so that the customer can call any method they like to call. Some customers might call the asynchronous method and then they will do future.get in their own library. Some can call the synchronous method, which internally can call the asynchronous method and do a future.get on it to return the response. | Synchronous and asynchronous methods in a client library | java;performance;asynchronous | public String executeSynchronous(final String userId);Drop this final as it helps nobody.How about the exception handling?Exception handling is always a pain, especially with checked exceptions. Usually, the best way is the simplest one, i.e., do nothing. Declare the exception to be thrown and let it blow. Someone up the stack will take care of it (it may be you) in a place where this makes sense.e.printStackTrace();This is rather wrong. You should log the message, printing to stderr may be redirected to somewhere where nobody sees it. What's worse, your method returns null and the caller has no way to find out what went wrong. Even worse, the caller does not expect null and will get an NPE one day (usually, when it creates the biggest damage).@Overridepublic String executeSynchronous(String userId) { String response = null; try { Future<String> handle = executeAsynchronous(userId); response = handle.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { e.printStackTrace(); } return response;}You're actually using two threads (the current one and one in the executor) where just one is needed. It should go the other way round: Let executeSynchronous do the work and submit a Callable calling it when asynchronous execution is needed.Is this the correct and efficient way of doing this problem?I guess, it's correct, but concerning efficiency it's no good to block two threads instead of one (and there's also the small overhead of executor, which is useless in the synchronous case).... Can we generalize interface?Maybe... I guess you want many such methods... and an interface containing both versions would be twice as big; no good idea. There'scom.google.common.util.concurrent.Futures.immediateFuture(@Nullable V value)in Guava, which could help. Instead of two methods, use two implementations of a single interface (synchronous and asynchronous).public interface Client { public Future<String> executeAsynchronous(String userId);}The synchronous implementation does the real job normally, but returns an immediateFuture instead of the value itself.The asynchronous implementation calls the synchronous one using the executor. In case of 10+ methods I'd consider using a dynamic proxy.Alternatively, you could add an argumentenum Synchronicity {SYNCHRONOUS, ASYNCHRONOUS}(don't use a boolean as its meaning is not obvious) to all the interface methods. |
_cs.73910 | Suppose you have some programming language with manual memory management. What features does this language need to have in order to be able to implement precise garbage collection as a library, and not as a fundamental language construct?By a precise GC I mean one where only pointers to the heap are traversed to ascertain which variables are or are not live.Some additional considerations:C and C++ have the Boehm garbage collector, but I don't count this since it's not a precise GC. The Boehm collector assumes that anything on the stack that could be a pointer, based purely on memory alignment requirements, is a pointer. For example, any integer k such that (k % 4) == 0 looks at a bit level like a pointer, since pointers must be 4-byte aligned.magpie transforms existing C code to use a precise garbage collector. The generated C code has a lot of stubs for garbage collection, i.e. stuff for registering any stack pointers into the heap with the collector. I don't count this because no one could ever be expected to write code that way; it's more of a compilation target for other languages.I imagine that such a language would need to have:Macros or some form of metaprogramming, for encapsulating all of the extra code needed to do things like register GC roots.Some reflective mechanism that allows you to inspect structs or unions; you need to determine which members are pointers.Some reflective mechanism that allows you to examine the stack frame layout. This sounds a lot harder than 2.I hope this isn't too vague or opinion-based but I've been wondering about it for a while. | What would a language look like in which precise GC was implementable as a library? | memory management;language design;garbage collection | null |
_unix.190232 | I am using Kali GNU/Linux 1.1.0, I want to change default kali theme to some other theme,I searched different different post most of them are using gnome-tweak tool,I tried sudo apt-get update and then sudo apt-get install gnome-tweak toolI got following message Package gnome-tweak tool is not avilable,but is referred to by another package.This may mean that the package is missing, has been obsoleted, oris only available from another sourceE: Package 'gnome-tweak-tool' has no installation candidatePlease suggest some option,Thanks in advance! | gnome-tweak tool not found | gnome;package management;kali linux | null |
_cstheory.906 | Sometimes, when using Google search, you don't immediately get quality results to your query. It is seems that PageRank algorithm gets distracted by widely used keywords that have different meanings and uses. Therefore, you need to spend extra time and possibly use different keywords to refine the search context.Is there a good reference that addresses the PageRank algorithm's shortcomings? Is there a contextual search algorithm? | Reference for the shortcomings of Google's PageRank algorithm? | ds.algorithms;reference request | to answer your specific question, there are many papers that discuss PageRank mathematically, such as:Deeper Inside PageRank, (A. N. Langville and C.D. Meyer), Internet Mathematics (1), 335400 (2004)and in each one you might find discussion of computational and operational issues (computing it faster, using memory more efficiently), but I don't know of any that stand out as addressing shortcomings of -results- specifically.to answer what you're getting at (why does google not give me what I want without trying?)google search does not equal PageRank (though PR is a major part of it)PageRank itself doesn't address lexical ambiguityGoogle's additions try to address multiple meanings of words (different meanings under different contexts), and synonyms (other strings that mean the same thing); they're not perfect, but more and more they are being addressed. |
_webapps.78099 | How can I create a new map (with my personal POIs) using Google Maps from a PC browser and use Street View options to see details?I am not able to create a map, give a name and add new points.I need to use it from a smartphone but I prefer to create it by PC because of the screen dimensions. | How to create a personal map with Google Maps and navigate with Street View? | google maps | To create a new map is it necassary to login with your personal google account and BEFORE any search you can see the menu where you can find your maps and create new ones |
_softwareengineering.328514 | Is there a preferred practice around initialising variables which are first defined within a branch of code, or is this purely subjective / personal preference?i.e. there are multiple ways this can be done; the most obvious of which are below:#option 1[string]$path = ''if ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { $path = ${env:ProgramFiles(x86)}} else { $path = $env:ProgramFiles}Get-ChildItem $path #option 2[string]$path = $env:ProgramFilesif ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { $path = ${env:ProgramFiles(x86)}}Get-ChildItem $path #option 3if ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { [string]$path = ${env:ProgramFiles(x86)}} else { [string]$path = $env:ProgramFiles}Get-ChildItem $path In most programming languages you'd go with option 1; i.e. have the variable declared and defaulted at the top, then assign it in a later branch. You may select option 2 instead if the cost of fetching the value is insignificant (e.g. in the above we're just pulling back an environment variable, so it's a low cost operation; but if we were pulling back a value from an external resource / using an expensive query or operation we may prefer option 1 to option 2). Equally some people may prefer option 1 to option 2 because it better illustrates the conditions under which each value should be used.Option 3 is only permissible in languages which don't require variable declaration; so is allowed in PowerShell / is the lowest cost solution (i.e. minimum number of assignments).NB: I realize that the [string] qualifier is superfluous / that PowerShell will automatically determine this; this is just something I include to help illustrate the idea of variable declaration (i.e. first assignment).I feel an aversion to option 3, probably because of my background in other languages; so don't know if others would have the same aversion, or if most people just think this is the right thing to do in this language.Are there any guidelines on this sort of thing (i.e. when there are no considerable performance considerations or additional factors to better inform the decision)? | Correct way to initialize variables in PowerShell | powershell | This is very much opinionated, and every professional programmer should have no problems to read and understand each of the variants. However, here is a version which avoids the superfluous repetition of the $path variable, thus being more DRY than any of your 3 alternatives:[string]$path = if ($ENV:PROCESSOR_ARCHITECTURE -like '*64') { ${env:ProgramFiles(x86) } else { $env:ProgramFiles }To make this a little bit more readable, I would probably introduce an explaining variable for the expression $ENV:PROCESSOR_ARCHITECTURE -like '*64' (but this is something I would do for any of the four variants, and so orthogonal to your question). i.e.[bool]$isX64Processor = $ENV:PROCESSOR_ARCHITECTURE -like '*64'[string]$path = if ($isX64Processor) { ${env:ProgramFiles(x86) } else { $env:ProgramFiles } |
_codereview.129115 | Recently I used this pattern to create a list of properties, each property having a varying number of arguments. The properties list can be made at compile time, it does not need to change at runtime.I tried to code this in a way such that it was easy for me to edit to add in additional properties (i.e., easy to add in a Video Card with arguments Brand, and Cost). This would be part of an application, e.g., this could be implemented by having a property editor dialog which showed the property name, and 3 text boxes with labels showing the names of the properties they are editing. The constructor for clsProperty has a lot of exceptions it can throw, it's probably not necessary since this can only be changed at compile time, but I put them in for completeness and to demonstrate what could go wrong if there was a typo in the code that made the properties list; let me know if you think there is a better way to do error handling in this case. It would be nice to have at least some sort of warning if the parameters aren't right but I'm not sure if exceptions are the right thing to use here.I think I saw that a list of Object is usually frowned upon, let me know if this is a valid time to use that, or if there is an alternative in this case.Any general suggestions to improve readability would be helpful too.For the sake of this example assume that everything in clsProperty is for display purposes only, no code will be doing something like if(Property.Name == ...)using System;using System.Collections.Generic;namespace csParseTest{ internal class clsProperty { // is it worth making these fields into properties of clsProperty? internal readonly string Name; internal readonly List<string> ArgNames = new List<string>(); internal readonly List<Type> ArgTypes = new List<Type>(); internal readonly List<Object> ArgDefaults = new List<Object>(); private List<Object> ArgValues = new List<Object>(); internal clsProperty(string iName, List<string> iArgNames, List<Type> iArgTypes, List<Object> iArgDefaults) { if (string.IsNullOrWhiteSpace(iName)) { throw new ArgumentException(Property must have a valid name.); } this.Name = iName; bool tParameterLengthsOK = ( (iArgNames.Count == iArgTypes.Count) && (iArgTypes.Count == iArgDefaults.Count) ); if (!tParameterLengthsOK) { throw new ArgumentException(Each argument must have a name, type, and default value.); } for (int tArgumentIndex = 0; (tArgumentIndex < iArgNames.Count); tArgumentIndex++) { string tArgName = iArgNames[tArgumentIndex]; Type tArgType = iArgTypes[tArgumentIndex]; object tDefaultValue = iArgDefaults[tArgumentIndex]; if(tDefaultValue == null) { throw new ArgumentException(Argument + tArgumentIndex + : no default value.); } if (String.IsNullOrWhiteSpace(tArgName)) { throw new ArgumentException(Argument + tArgumentIndex + : name must not be blank.); } if (!IsValidArgType(tArgType)) { throw new ArgumentException(Argument + tArgumentIndex + : type + tArgType.ToString() + is not supported.); } this.ArgNames.Add(tArgName); this.ArgTypes.Add(tArgType); this.ArgDefaults.Add(tDefaultValue); this.ArgValues.Add(tDefaultValue); } } internal void SetArgument(int iArgIndex, string iValueString) { if ((iArgIndex < 0) || (iArgIndex > (ArgValues.Count - 1))) { throw new IndexOutOfRangeException(Argument index + iArgIndex + is invalid, arguments list has + ArgValues.Count + items.); } Object tValue = null; Type tArgType = this.ArgTypes[iArgIndex]; if (TryParseArgValue(iValueString, tArgType, out tValue)) { this.ArgValues[iArgIndex] = tValue; } else { throw new ArgumentException(Could not parse string + iValueString + as argument type + tArgType.ToString()); } } // for the sake of this example assume that properties can only be one of these types. internal static bool IsValidArgType(Type iType) { return ( (iType == typeof(System.String)) || (iType == typeof(System.Int32)) || (iType == typeof(System.Int64)) || (iType == typeof(System.Single)) || (iType == typeof(System.Double)) ); } private static bool TryParseArgValue(string iValueString, Type iParseAsType, out object qValue) { qValue = null; if (iParseAsType == typeof(System.String)) { qValue = iValueString; return true; } else if (iParseAsType == typeof(System.Int32)) { int tParsedInt; if (int.TryParse(iValueString, out tParsedInt)) { qValue = tParsedInt; return true; } else { return false; } } else if (iParseAsType == typeof(System.Int64)) { long tParsedLong; if (long.TryParse(iValueString, out tParsedLong)) { qValue = tParsedLong; return true; } else { return false; } } else if (iParseAsType == typeof(System.Single)) { float tParsedFloat; if (float.TryParse(iValueString, out tParsedFloat)) { qValue = tParsedFloat; return true; } else { return false; } } else if (iParseAsType == typeof(System.Double)) { double tParsedDouble; if (double.TryParse(iValueString, out tParsedDouble)) { qValue = tParsedDouble; return true; } else { return false; } } else { // I considered throwing an exception here return false; } } }; class Program { // for the sake of this example assume that this properties list does not need to be changed at runtime. private static readonly List<clsProperty> AllProperties = new List<clsProperty> { new clsProperty(Optical Drive, new List<string> {Brand, Speed, Format}, new List<Type> {typeof(System.String), typeof(System.Single), typeof(System.String)}, new List<Object> {Asus, 220.3, BD-ROM}), // or with named parameters... new clsProperty(iName:Hard Drive, iArgNames:new List<string> {Type, Price}, iArgTypes: new List<Type> {typeof(System.String), typeof(System.Double)}, iArgDefaults: new List<Object> {Solid State Drive, 123.4}) }; // test code static void Main(string[] args) { // e.g., user edits values using text boxes (or a data grid maybe), // then hits OK or apply AllProperties[0].SetArgument(0, Lite-On); AllProperties[0].SetArgument(1, 100.9); AllProperties[0].SetArgument(2, DVD-ROM); //Properties[0].SetArgument(1, ShouldFail); return; } }}EDIT: This would be using Winforms for the GUI | User editable properties with varying number of arguments | c#;winforms | Is it about web or windows UI? WPF or WinForms: you could just use PropertyGrid - it is the same component you have in Visual Studio to edit properties. To define properties at runtime if happens to be needed - see TypeDescriptor. |
_webmaster.65721 | I'm currently browsing through a local transparent proxy. I'm receiving 404 responses from a couple of web hosts, although the proxy works perfectly with everything else; I was wondering whether it could be the websites recognizing and blocking the proxy user.Is this a possibility or is there something wrong with the proxy? | Is it possible for a website to determine whether the user is browsing through a transparent proxy? | 404;proxy | null |
_unix.164387 | Right now I could only see the applications (frequent and all) and files in the home folder. But I can't see a file which is present in a folder in home directory. For example I can't see the files in Downloads folder in home directory but can see the folder Downloads and files present in home directory while searching in the Debian activity overview search bar (latest GNOME version). Also I am using Linux Mint 16 but the desktop environment I'm using is GNOME with mutter as window manager. | See files other than home folder files in activity overview seach bar in debian | debian;gnome | null |
_webmaster.67890 | I am using MaxCDN for my website, and to prevent hotlinking, I only allow my website's pictures to be displayed on whitelisted HTTP referrers, through MaxCDN's security settings.However, even though I have added every kind of Google domain I could find, my post's pictures won't show up in new Google+ Posts.These are the domains I have whitelisted so far:*.googleusercontent.com*.google.com*.googleapis.com*.gstatic.com*.googlegroups.com*.ggpht.comWhich server am I missing? | Which domain do I need to whitelist as an HTTP referrer for Google+? | google plus | null |
_cogsci.9015 | I read the whole Wikipedia article. But I still have doubts. Is art therapy effective? If so, in which ways has it been studied? | Is art therapy really effective? | social psychology;reference request;clinical psychology | null |
_codereview.101840 | I want to know about best practice for this SplashScreen class:public class SplashScreen extends Activity { // time out to splash screen private static int SPLASH_TIME_OUT = 2000; private Runnable mjumpRunnable; private Handler mHandler; //image view to validae logo ImageView validatelogo; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splashscreen); validatelogo = (ImageView) findViewById(R.id.imgvalidatelogo); validatelogo.setVisibility(View.VISIBLE); final Animation fadeouteffect = AnimationUtils.loadAnimation(this , R.anim.fadein); validatelogo.setAnimation(fadeouteffect); mjumpRunnable = new Runnable() { @Override public void run() { jump(); } }; mHandler = new Handler(); mHandler.postDelayed(mjumpRunnable , SPLASH_TIME_OUT); } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ jump(); } return super.onTouchEvent(event); } void jump(){ if(isFinishing()) return; startActivity(new Intent(this , LoginActivity.class)); finish(); }} | SplashScreen class | java;android | So you want to follow good practices. There are quite a few things to pick on here.Limit access as much as possibleTry to make member fields private first, and relax access as needed.For example, why isn't this variable private?ImageView validatelogo;Aim for immutabilityImmutable things are easy to work with:as they never change,there is no window of vulnerability,you can trust immutable things from the time they are constructed forever.Even if true immutability is not achievable,it's good to take steps in that direction.A good first step is to try to make member fields final.For example, these variables could easily be final:private static int SPLASH_TIME_OUT = 2000;private Handler mHandler;Limit scope as much as possibleBy limiting the scope where a variable is visible,you make the variable easier to understand,and reduce the probability of accidental modifications.For example, these member variables are only used inside one method, onCreate,so they should be declared there (converting to local variables from members): private Runnable mjumpRunnable; private Handler mHandler; ImageView validatelogo;NamingmjumpRunnable doesn't conform to Android naming conventions,it should be mJumpRunnable (with capitalized J).LayoutThere are many pointless blank lines,especially at the end of onCreate.FormattingThere are multiple formatting issues here: void jump(){ if(isFinishing()) return; startActivity(new Intent(this , LoginActivity.class)); finish(); }That is:Inconsistent indentationIt's recommended to use braces always, even with single-statement ifThere should be a space between ){ in jump(){There shouldn't be a space before the comma in this , |
_unix.203704 | Somewhere along the way I've fallen into the habit of hitting tab twice after using a wildcard in commands like mv or rm, which by default causes bash to show the list of files that would match the wildcard expansion. For example: {~/bin}-> ls p*<TAB> pnuke pscp pssh prsync pslurp pssh-askpass However, when using the bash_completion package in Debian Jessie, this behavior has changed, and the default behavior when completing a filename is to replace any wildcards with the first (and only the first) file that matches the expansion. With bash_completion installed, if I use the same example as above, my command line changes to look like this after hitting tab: {~/bin}-> ls pnukeOf all the possible actions bash could have taken in this situation, this seems like the least useful. Is there a way to get back the default readline file completion behavior, while still getting all the other goodies that bash_completion provides when completing something that is not a file name? Or if not the default behavior, can I at least make it do something helpful? (Even doing nothing at all would be more helpful behavior than this.) | Context-sensitive bash completion changes wildcard behavior | bash;autocomplete | null |
_unix.90260 | I'm administrating a system where users authenticate via NIS and things went wrong when a user tried to use yppasswd to change her password. She got the error:yppasswd: yppasswdd not running on NIS master host (localhost).Based on suggestions elsewhere around the Web, I tried setting an entry in /etc/hosts with the client's IP (as opposed to 127.0.0.1) pointing to the client's host name. This didn't work.My /etc/yp.conf says ypserver <my_server_IP>.strace output shows that yppasswd consults /etc/hosts and /etc/nsswitch.conf before deciding on 127.0.0.1 for the server.What am I missing?Client is running Debian 7.0 (Wheezy) and server is running Debian 6.0.1 (Squeeze)NoteI'm aware that NIS is nearing total obsolescence and very vulnerable. A migration to LDAP is on my agenda, but I need a solution for this in the interim.Additional DetailsFiles on the client:/etc/hosts127.0.0.1 localhost<IP in current DHCP lease> host_name.domain host_name<server_ip> server_name server_name.domain/etc/nsswitch.confpasswd: files nis compatgroup: files nis compatshadow: files nis compathosts: files mdns4_minimal [NOTFOUND=return] dns mdns4networks: filesprotocols: db filesservices: db filesethers: db filesrpc: db filesnetgroup: nis | NIS users can't use yppasswd on client machines | debian;nis | null |
_codereview.32756 | I made a method that finds synonyms to words using thesaurus.com and I'm looking for comments and feedback to it. In what ways can I improve it, both when it comes to speed, security, reliability (regardless of how reliable it is to rely on a third-party website for look-ups), etc. /// <summary> /// This method relies heavily on thesaurus.com for synonym lookups. It is not completely reliable, but is deemed reliable enough in instances where you dont have your own thesaurus /// </summary> public static string[] GetSynonyms(string word) { string url = string.Format(http://thesaurus.com/search?q={0}, word); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { List<string> synonyms = new List<string>(); StringBuilder data = new StringBuilder(); string line; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { //we know that the synonyms is in the upper-part of the html stream so we do not want to read the entire stream. while((line = reader.ReadLine()) != null) { var index = line.IndexOf(<span class=\text\>); if(index > 0) { index = index + <span class=\text\>.Length; synonyms.Add(line.Substring(index).Replace(</span>, )); } //break when we come to the Antonyms section of the page if (line.Contains(container-info antonyms)) { break; } } } return synonyms.ToArray<string>(); } else { return null; } }Edit: As an example, it now takes about 3.5 seconds to find the synonyms for the word old. | Parse and extract synonym data from a website | c#;parsing | You're doing things the hard way. By that I mean, why build a web crawler for this? Is it a requirement that you only use thesaurus.com? There are several quality thesaurus services out there with APIs that you could utilize.I've never used any of them, but a quick web search and a bit of sifting results and these ones appear to be at the head of the thesaurus API ballgame.Altervista Thesaurus: Thesaurus is a web service providing search capability for synonyms in different languages.The synonyms are retrieved from the thesauri dictionaries of OpenOffice according to the relevant licenses.Big Huge Thesaurus: This site sports a very simple API for retrieving the synonyms for any word. You can access the API by making a GET request...I also found another Stack Exchange post on the topic, which lists some more options:https://webapps.stackexchange.com/questions/9156/database-of-english-synonymsIf thesaurus.com is absolutely a requirement, then you're doing the best you can. You have to send the request, crawl the page, extract the information you want, and format it into something you can use. thesaurus.com does have an API, but from how they describe it, its difficult to get them to give you access. You can read more about that here:thesaurus.com API |
_softwareengineering.37973 | My team and I develop software that our customers will use to interact with their customers. Additionally, we also eat our own dogfood and use the software ourselves to interact with our customers.Therefore, it can sometimes be difficult to explain use cases and scenarios, as our employees can be operators, our customers can be operators, and our customers' customers can be visitors.However, our customers can also be visitors interacting with our operator employees, our customers' customers can be visitors interacting with our customer or our employee.Here is a model where:A is an employeeB is a customerC is our customers' customerX interacts with YOperator --> Visitor A --> B A --> C B --> CBecause sometimes our customers can play different roles, it's sometimes necessary to refer to the specific role, Operator or Visitor, instead of Employee and Customer.It's also a mouthful to say customer's customer all the time.I was wondering how other development shops handle these semantic details when writing their use cases and scenarios. Are there any one-word, generic terms that can apply to any product that involves a third-level actor?Other than using the specific roles, Operator and Visitor, what words could be used to identify a customer of a customer? The word would need to be short enough as to be adopted within an organization. If longer than a couple syllables, it's shortened form must still differentiate it from the other actors. | What do you call a customer's customer in a specification document, use case, or scenario? | communication;naming;specifications | to explain use cases and scenariosThat's the key: use the terminology of the domain, i.e. the names of the roles. Who can play the roles is not important. Make sure that the roles are well-defined (for each scenario).It is entirely possible for me to visit my own website and purchase my own products. It's silly, but it's possible [but I've done it to test the e-commerce software!]. That fact that I am the provider, host, author, webmaster, copywriter, programmer, client, customer, visitor, purchaser, guest, owner, and employee all at the same time does not alter the terminology of the use-case: customer buys product from owner via web form |
_scicomp.8139 | I have recently started using Lapack++ which I found convenient for my programming purpose, in general. Now, I need to solve a matrix using QR algorithm. I've searched the user manualand I found a LaGenQRFactComplex Class for the purpose. But it need a complex matrix type as input parameter (as per my understanding).Is there any other way for me to use the same for solving a real valued matrix?? | Lapack++ for QR algorithm | linear algebra;linear solver;c++;lapack;numerical analysis | null |
_softwareengineering.108258 | A computer science degree (like any undergraduate degree) does not prepare you to be productive immediately. And my sense is that employers are less and less willing to provide that initial training. (Or at least if you DO have those core skills*, you have a broader selection of first jobs to choose from).What skills should a senior focus on to make him/her self more employable?And how might you get those skills?*EDIT: I'm not talking about experience/mastery of technology. I'm talking about core skills like Source Control (not mastery of a particular SC, but just being able to use one an understanding the concepts) and Unit Testing (having written Unit Tests using at least some famework), etc. | What core skills does a new Computer Science Graduate need to be employable? | employment | null |
_softwareengineering.234159 | I'm currently reading about database schemas about how the three-level ANSI-SPARC architecture works and i'm a bit confused about a concept it's talking about. My question is what would happen if an application was modified so it could store data for a column not defined in the logical schema? The book i'm reading talks about: ... the addition or removal of new entities, attributes or relationships should be possible without having to change existing external schemas or having to rewrite application programs. - Database Systems: A practical Approach to Design, Implementation and Management. Page: 40 (Part: 2.1.5)How does the logical schema handle input (columns) from applications for which it is not defined in the logical schema?ANSI-SPARC architecture: http://en.wikipedia.org/wiki/ANSI-SPARC_Architecture | Database Schema Data Independence | database design;schema | For those who don't have that reference handy, the Wikipedia article on ANSI-SPARC provides a decent overview.How does the logical schema handle input (columns) from applications for which it is not defined in the logical schema?The short answer is that the logical schema can't handle (store) input if it doesn't have columns defined for it.The long answer is that I think the problem is that you've got the frame of reference backwards. The internal or logical schema needs to have a representation for all of the data that all of the applications (external schemas) may present. But the external schemas don't need to know of all of the potentialities that are possible within the logical schema.What that quote is focusing on is adding a new, external view onto the existing database. That will likely require the logical schema to be extended to handle the new bits of data that the new view will require. But the changes required for this new external view will have zero bearing upon the existing external views and their perception of what the database schema looks like.To use a concrete example...Say I have an application that tracks ticket sales. I have all sorts of wonderful schemas built around pricing, history, seating, sellers, and buyers. So my ticket sales app has a view of what it perceives the database schema to be.Later on, I'm talking with another business partner and realize that with a little modification to the database and a new external view, I can easily track auction results. The premise of that quote is that I should be able to make changes to the logical schema (my database) to support my new auction results application without having to make any changes to my ticket sales tracking application. |
_softwareengineering.313021 | I am working as SAP developer, where in many cases you have traditional requirements to applications (reports):Read in some data from the database or a fileDo some magic with that data, e.g. do various calculationsWrite out the results into the database or a file againThis is the typical use case for many SAP programs, as it has been for about 30 years now in that area. However, in recent years even SAP becomes more and more modern, with web-based (HTML5) interfaces, Java support, mobile apps, and last but not least a reasonable OO version of the main programming language, ABAP.Coming from the Java world for me it's obvious to prefer ABAP OO over plain procedural ABAP in many cases. However, as often in the SAP world, there are many older co-workers that are used to that old precdural programming style, they have never learned any OO programming. So my boss asked me to explain OO in general to them, and in which cases it makes sense to use it rather than the old style.So I did this, organised a workshop, and explained all that. However, even though it seems most of these collegues have understood what OO means in general, what classes and objects are, inheritance, the whole thing, they still just don't use it. For them it seems convenient to stick what they are used to to, as this is what they have used since dozens of years.Now I don't want to convince them to use ABAP OO in any case, as in SAP sometimes it does make sense to use traditional procedural approaches. However, as with modern SAP application OO does make sense in many cases, I would like to make my co-workers life easier by convincing (not forcing) them to use OO in these cases.Can you recommend any arguments why in general OO does make sense in some - practical! - cases, even if you are used to procedural programming since 20+ years? | How to convince old co-workers of the merits of OO for certain applications | object oriented;procedural;sap;abap | I think your question goes beyond some magical explanation as to why OO is better. In fact, that question has already been asked on this site.You made a management mistake. You can't take a complex subject, do some minimal training with not follow-up or management buy-in and think you're going to get people to change the way they do things when there is no immediate incentive.Are there going to be code reviews that have management support to start providing negative consequences for not complying? At what point will it be unacceptable to check in code that is not done in OOP when appropriate?Will additional training be offered? Will more time be offered to complete some tasks? One benefit of OOP is to help maintain complex code. It will take longer to write. Who is willing to slow the current development in hopes of limiting technical debt?I like learning new things, but they take time and don't immediately show up in production code for my job. There are occasions when I can step back and evaluate what I'm doing and architect a better solution. Sometimes, there's someone constantly looking over your shoulder to put out a fire and the latest and greatest new shiny stuff has to sit in the box.Don't give up! Focus on some early adopters. Find a new piece of code to write and team-up with everyone and see if you can design it differently. Don't worry if it never gets into production, they're learning.Eventually, they will be forced to revisit code that was designed with more OOP principles and they may finally see how much easier it is to work with, debug and expand. It will take time and time is very valuable. |
_cs.41176 | The cycle detection problem for a directed graph has well-known polynomial time solutions, graph traversal algorithms such as Dijkstra algorithm can be used to find whether or not a cycle exists in a graph.The difficulty however comes when we are required to find in polynomial time whether 2 vertex disjoint cycles exist in an arbitrary graph. Is there such a polynomial time algorithm which finds whether 2 vertex disjoint cycles exist in an arbitrary graph?By vertex disjoint cycles, I mean cycles which do not share a common vertex. | Polynomial time algorithm for finding two or more vertex-disjoint cycles | algorithms;graphs;polynomial time | null |
_scicomp.26636 | Kahan summation applies to summation problems, but not to three-term recurrence relations. However, a three-term recurrence shares many of the features of a summation-albeit with a rescaling step at each iteration. Hence there seems to be hope for a Kahan summation for three-term recurrences. Has this idea been worked out in the literature or is the idea flawed in some way? | Kahan Summation for Three-Term Recurrences | reference request;stability;floating point | null |
_codereview.56014 | We have a base interface: public interface IMessage { //Some properties }then we have derived messages that implement this interface such as: public class AlarmEventMessage: IMessage { //Some properties }Now, these messages get routed to a message handler that receives them.So we have multiple overloads for this Handle(IMessage message) to handle the specific derived messages. public class MessageHandler { public bool Handle(IMessage message) { if (message is AlarmEventMessage) { return Handle(message as AlarmEventMessage); } // some more message routing here } public bool Handle(AlarmEventMessage message) { // Some business logic here } //Handle more messages here }I believe it violates the Single-Responsibility Principle. This class constantly keeps changing because of new messages being added and also the business logic that relates with this new message.Are there any other SOLID principles it violates? Does it look like an Anti-Pattern? | Multiple overloads for message handling | c# | You are correct when you say that the MessageHandler class violates the Single Responsibility Principle. What you're looking for here is generics. First of all, you need to define a contract for messages and their respective handlers. This can be done with the following:public interface IMessage{ // properties}public interface IMessageHandler<in TMessage> where TMessage : IMessage{ bool Handle(TMessage message);}So with the AlarmEventMessage, you can do this:public class AlarmEventMessage : IMessage{ // properties}public class AlarmEventMessageHandler : IMessageHandler<AlarmEventMessage>{ public bool Handle(AlarmEventMessage message) { // stuff }}This design allows you to do some cool stuff with decorator chains, dispatching, registration by convention (if you're using an IoC container that supports it), among other things. For more information, check out the following two articles (they demonstrate how to implement the command/query pattern, but the design is identical):Meanwhile... on the command side of my architectureMeanwhile... on the query side of my architecture |
_unix.329127 | I'm wondering if is correct to find with half days like this-mtime +2.5 -delete for 2 and a half daysLE: there are any dangers in using this? | Is correct to find with half days -mtime +2.5 -delete? | find | null |
_softwareengineering.202691 | Ive got a 2 database tables in parent/child relationship as one-many.Ive got three classes representing the data in these two tables:Parent Class{ Public int ID {get; set;} .. other properties}Child Class{ Public int ID {get;set;} Public int ParentID {get; set;} .. other properties}TogetherClass{ Public Parent Parent; Public List<Child> ChildList;}Lastly Ive got a client and server application Im in control of both ends so can make changes to both programs as I need to. Client makes a request for ParentID and receives a Together Class for the matching parent, and all of the child records.The client app may make changes to the children add new children, remove or modify existing ones. Client app then sends the Together Class back to the server app.Server app needs to update the parent and child records in the database.In addition I would like to be able to log the changes Im doing this by having 2 separate tables one for Parent, one for child; each containing the same columns as the original plus date time modified, by whom and a list of the changes. Im unsure as to the best approach to detect the changes in records new records, records to be deleted, records with no fields changed, records with some fields changed.I figure I need to read the parent & children records and compare those to the ones in the Together Class. Strategy A:If Together classs child record has an ID of say 0, that indicates a new record; insert.Any deleted child records are no longer in the Together Class; see if any of the comparison child records are not found in the Together class and delete if not found (Compare using ID).Check each child record for changes and if changed log.Strategy B:Make a new Updated TogetherClassUpdatedClass{ Public Parent Parent {get; set} Public List<Child> ListNewChild {get;set;} Public List<Child> DeletedChild {get;set;} Public List<Child> ExistingChild {get;set;} // used for no changes and modified rows}And then process as per the list. The reason why Im asking for ideas is that both of these solutions dont seem optimal to me and I suspect this problem has been solved already some kind of design pattern ?I am aware of one potential problem in this general approach that where Client App A requests a record; App B requests same record; A then saves changes; B then saves changes which may overwrite changes A made. This is a separate locking issue which Ill raise a separate question for if Ive got trouble implementing. The actual implementation is c#, SQL Server and WCF between client and server - sharing a library containing the class implementations.Apologies if this is a duplicate post I tried searching various terms without finding a match though.Update based on comments from svick and TimG:To track change would the base class be something like:public class ChangedRowBase { public enum StatusState { New, Unchanged, Updated, Deleted }; protected StatusState _Status; public StatusState Status { get { return _Status; } } public void SetUnchanged() { _Status = StatusState.Unchanged; } public void SetDeleted() { _Status = StatusState.Deleted; }}Then my Child class would have something like: public int SomeDumbProperty { get; set { base.Status = StatusState.Updated; // Missing line here to set the property itself } } private int _SomeIntelligentProperty; public int SomeIntelligentProperty { get { return _SomeIntelligentProperty; } set { if (value != _SomeIntelligentProperty) { _SomeIntelligentProperty = value; base.Status = StatusState.Updated; } } }The idea being that the intelligent one detects if there has indeed been a change; otherwise using the dumb one the client app would need to either detect change and only update if there has been a change, or use the setter anyway flagging a change which actually didn't occur.I also know that my dumbproperty doesn't work (or compile) right now. If I want code in the getter or setter, does this mean I need to define a separate private variable myself ? I know the short hand {get; set;} does this behind the scenes. | Design pattern for logging changes in parent/child objects saved to database | c#;design patterns;database;logging | Here are common design patterns to handle these scenarios. Set up a base class. Child and parent will inherit from base. Base class should do the following:Have a .Status property (read-only) that tracks if an object is {unchanged, new, updated, deleted} The status is set during {constructor, .delete() method, each Property's setter}. You will need a factory method to generate an object instance with a status of unchanged or a method to mark itself as unchanged.btw. This approach makes an object more atomic because it is self-contained and it keeps track of its own changes. This is also an example of why people use Properties (getters/setters) instead of public vars. A commonly used pseudo locking mechanism is to use a combination of .LastModifiedDateTime (read only) and .LastModifier (read-only) columns on each DB table (non code-table/static-table). These are also set in the constructor/factory method. On Update/Save, compare the current LastModifiedDateTime & LastModifier to the DB. If they don't match then reject this change.#1 is similar to the way many ORMs maintain state (handle changes). #2 is often referred-to as a soft locking mechanism. |
_softwareengineering.339449 | Suppose you set up a Redis cluster with one master and two slaves. Two clients are connected to each of the slaves. Both clients make conflicting changes at the same time:What happens if these changes are replicated to Master at around the same time? Are they just applied to Master in the order they are received, then replicated back down?What if transactions are used? Is the result eventually consistent, i.e. does Master resolve the conflict by applying the transactions in some order, then replicate the resolution down?I don't expect perfect consistency from a distributed cache, but I do want to understand the fine points so that I use caching well. The application I'm working on uses the distributed cache for coordination among worker threads/processes. For example, when one worker processes an item, it puts a key in the cache with an expiration of 1 minute telling other workers not to process the same item. It's acceptable if two or three workers end up processing the same item, but this mechanism prevents infinite reprocessing. | How does Redis (or any typical distributed cache) handle replication conflicts? | caching;redis;distributed system | null |
_codereview.104019 | Suppose I have a class of complex numbers called Complex and I wish to implement a class of generic matrices with transpose operation.doubles and ints don't require special care, but you have to calculate the conjugate of complex numbers to transpose. Therefore, I implemented a specialized transpose().template <class T> Matrix<T> Matrix<T>::transpose() const{ Matrix<T> matrix(_cols, _rows); unsigned int i, j; for (i = 0; i < _rows ; ++i) { for (j = 0; j < _cols; ++j) { matrix(j, i) = (*this)(i, j); } } return matrix;}template <> Matrix<Complex> Matrix<Complex>::transpose() const{ Matrix<Complex> matrix(_cols, _rows); unsigned int i, j; for (i = 0; i < _rows ; ++i) { for (j = 0; j < _cols; ++j) { matrix(j, i) = (*this)(i, j).conj(); } } return matrix;}As you can see, there's a severe code repetition. Is there any way I can deal with it (like using helper methods)?References from Wikipedia:TransposeConjugate transpose | Specialized template methods with complex numbers class | c++;template | null |
_softwareengineering.349040 | I have to do a program to school in Assembler but we did just a few basic things. Is it possible to write code in Java and convert it to Assembler? | Convert program in Java to Assembler? | java;assembly | null |
_softwareengineering.226149 | I am implementing an ecommerce database. This is slightly different than most as the 'products' that are for sale are for services provided. For example a user (vendor) of the system may define a service to 'wash your car'.Table: Services--------------------------------------------------| ID (pk) | Title | Description |-------------------------------------------------- 1 Home Services wash your carI have omitted a number of columns, but should still be able to make my point.A client can then purchase the Home Services. So I have an orders table with a FK to the the Services table. Standard ecommerce stuff.The issue I have is what happens if the vendor decides to slightly update the description or even the title? This may have the affect of changing the entire service. For a normal commerce site, you'd add a discrete product. If this product changed, you would create a new product and discontinue the old one. With the packages, we need to allow updates as the description is the product and the sales pitch (maybe thats my problem though - maybe separate the two?) so I have to allow changes.For example they could change the description to 'wash your car and clean your house'.The obvious issue with this is that existing orders will still reference the same PK on the services table but the service is now different.I'm wondering what the best solution is to allow changes to be added, but maintain the correct data for existing orders. One solution I thought of is to not update the row, but add a new one and a version numberTable: Services------------------------------------------------------------------------------| ID (pk) | Title | Description | Version |------------------------------------------------------------------------------ 1 Home Services wash your car 1 2 Home Services wash your car and clear your house 2We can now access the correct information for previous orders, and existing customers can purchase the new home services option.This feels like a sensible way to do it, but want to see if anyone knew of any other solutions?One other solution is to allow updates on the services table, but then for each order, save the description and title (similar to how sometimes in commerce schemas the final price is saved directly to the order). Issue I have with this is a lot of duplicate data being saved. | Tracking correct order details in commerce database when modifying 'products' | database;database design;database development;relational database;schema | What you want to do is freeze the information at the time of an order.When a client makes an order you just make a copy of the description, price, product etc. in the order record.For instance, the price of a product can change a lot. You don't want a new product record for every price change. So you freeze the price in the order record.Once an order is made, a lot of the information references to the order and not to the products anymore. Things like price, description, vendor, vat, but also shipping adress get stored with the order.It now has become historical data.That way, even when things change, like price, decription or adress you can always see what the actual order was.A change of shipping adress for a client for instance, doesn't change where an order was shipped originally.See it as a contract: you take your product catalog, get the product details and client details and put them in the contract, the actual product and the name and adress of the client.You don't put in the contract: client 12345 has ordered 3 of product 7 on page 25 of the catalogue version B from may 2013 with 10% sunday sales discount. |
_unix.77518 | I try to remove string from .bash_profile. String is added when my shell script run:My string at bash_profile as follows:# for Myapllicationexport MYAPP_HOME=/opt/myappI want to remove the strings from .bash_profile when myapp is removed via rpm. How to remove any string from a file via shell script? (or possible alternative method) | How to remove any string from a file via shell scripts? | linux;shell script;bash script | You can remove a string from a text file with sed(others tools exist).For example:sed -i -e '/myapp/d' .bash_profileremoves from .bash_profileevery line containing the string myapp. |
_codereview.65284 | I have a requirement of a templated clone() method which Base classes can implement through an ICloneable interface and all the derived classes will automatically get a pure virtual clone<T>() method to override. I know this is confusing, so below is my code which probably explains it better.// ICloneable interfacetemplate <class T>class ICloneable{public: // smart pointer based polymorphic clone method // of template parameter T virtual std::unique_ptr<T> clone() const = 0;};// Any class deriving from ICar would need to // implement std::unique_ptr<ICar> clone()// and std::string name()class ICar : public ICloneable<ICar>{public: virtual std::string name() = 0; virtual ~ICar() {}};// Derived car object implementing ICar interfaceclass NamedCar : public ICar{private: std::string _name;public: NamedCar() {_name = This car does not have a name;} NamedCar(std::string name) { _name = name; } virtual ~NamedCar() {} // override virtual std::string name() { return _name; } // override virtual std::unique_ptr<ICar> clone() const { return std::unique_ptr<ICar>(new NamedCar(*this)); }};class MercCar : public ICar{public: MercCar() {} virtual ~MercCar() {} // override virtual std::string name() { return Merc; } // override virtual std::unique_ptr<ICar> clone() const { return std::unique_ptr<ICar>(new MercCar(*this)); }};// Any class deriving from IBicycle would need to // implement std::unique_ptr<IBicycle> clone()// and void describe()class IBicycle : public ICloneable<IBicycle>{public: virtual ~IBicycle() {} virtual void describe() = 0;};class MyBicycle : public IBicycle{public: MyBicycle() {} virtual void describe() { std::cout << This is my bicycle << std::endl; } virtual std::unique_ptr<IBicycle> clone() const { return std::unique_ptr<IBicycle>(new MyBicycle(*this)); } virtual ~MyBicycle() {} };template <typename T>class MyGarage{private: T _data; std::unique_ptr<ICar> _car_ptr; std::unique_ptr<IBicycle> _bicycle_ptr;public: MyGarage(T& data, const std::unique_ptr<ICar>& cp, std::unique_ptr<IBicycle>& bp) : _data(data) { _car_ptr = cp->clone(); _bicycle_ptr = bp->clone(); } MyGarage(const MyGarage& source) : data(source._data) { _car_ptr = source._car_ptr->clone(); _bicycle_ptr = source._bicycle_ptr->clone(); } MyGarage& operator=(const MyGarage& source) { if (this != &source) { _data = source.data; _car_ptr = source._car_ptr->clone(); _bicycle_ptr = source._bicycle_ptr->clone(); } return *this; } std::unique_ptr<ICar> car_ptr() { return _car_ptr->clone(); } std::unique_ptr<IBicycle> bicycle_ptr() { return _bicycle_ptr->clone(); } void car_ptr(const std::unique_ptr<ICar>& cp) { _car_ptr = cp->clone(); } void bicycle_ptr(const std::unique_ptr<IBicycle> bp) { _bicycle_ptr = bp->clone(); } T data() { return _data; } void data(const T& data) { _data = data; }};int main(){ // Check whether the clone method works for IBicycle and ICar std::unique_ptr<IBicycle> p_bike; MyBicycle mybike; p_bike = mybike.clone(); p_bike->describe(); std::unique_ptr<ICar> p_car; NamedCar n_car(Ford); NamedCar kia_car(Kia); MercCar my_car; p_car = n_car.clone(); std::cout << p_car->name() << std::endl; p_car = kia_car.clone(); std::cout << p_car->name() << std::endl; p_car = my_car.clone(); std::cout << p_car->name() << std::endl; p_car = n_car.clone(); std::cout << p_car->name() << std::endl; NamedCar unnamed_car; p_car = unnamed_car.clone(); std::cout << p_car->name() << std::endl; int x = 123; // Check the functionality of MyGarage class MyGarage<int> garage(x, p_car, p_bike); std::cout << garage.car_ptr()->name() << std::endl; garage.bicycle_ptr()->describe(); garage.car_ptr(n_car.clone()); std::cout << garage.car_ptr()->name() << std::endl; garage.car_ptr(my_car.clone()); std::cout << garage.car_ptr()->name() << std::endl; int newx = x + 982; std::cout << garage.data() << std::endl; garage.data(newx); std::cout << garage.data() << std::endl;}The output is:This is my bicycleFordKiaMercFordThis car does not have a nameThis car does not have a nameThis is my bicycleFordMerc1231105which I expected.However, I wanted somebody's feedback on this i.e. whether this is a good design for such a problem, especially the MyGarage class - where I have to expose a setter for the internal unique_ptr, which I am not sure is a good idea. Also, is there a possibility of this design unknowingly leaking memory? | Polymorphic template cloning class | c++;design patterns;interface;pointers | null |
_webmaster.104929 | I have a website http://requestly.in which is currently hosted on GitHub. I have added a CNAME entryName: requestly.inValue: requestly.github.ioThis works perfectly fine. Now, I am trying to setup email service by Zoho. I need to add couple of MX records. According to Zoho documentation, I have to add the following entries:Host Name Address Priority@ mx.zoho.com 10@ mx2.zoho.com 20When I am trying to add any of the above entries, I am getting into an error situation saying CNAME entry already exists with same name. Please check for conflicts.Here are couple of screenshots for reference:List of CNAME entriesError Screenshot when trying to add MX Record | How to add MX record when CName exists (BigRock)? | cname;mx | null |
_unix.321252 | For testing reasons I would like to block specific packets depending on their options or type.For example in a DHCP DORA transaction I would like to block DHCP ACK packets only.Is it possible to do this using iptables ? If not , what are the possibilities ? | DROP a packet depending on it's options or type | linux;networking;iptables | You could use the u32 module. (See the manpage for iptables-extensions). It's not too user-friendly but should be usable.DHCP is a bit difficult to parse also because parts of the data, including the DHCP message type are in the options, which can be in arbitrary order. Though the message type option is likely to be the first one. The DHCP options start at offset 236 in the UDP packet, and the IP and UDP headers are 20+8 bytes long. So we are interested in the bytes starting at offset 264. The first four bytes should be the magic identifier, and the next three can be checked for the message type option. The type code is 0x35, the length is always 0x01 and for DHCPACK the value is 0x05. (The DHCP packet format is described e.g. on tcpipguide.com) So the expression for u32 could be:--u32 '268 >> 8 = 0x350105'Which simply means to read 4 bytes at offset 268 (as big-endian number), shift them 8 bits to the right (to keep the first three bytes), and compare that to the expected value.We could check the magic number too:--u32 '264 = 0x63825363 && 268 >> 8 = 0x350105'Checking that we actually have a UDP packet going to correct port is easier to do with regular iptables rules, so we'd use something like the following to match the expected DHCP packets.iptables -A foo -m udp --dport bootpc -m u32 --u32 '264 = 0x63825363 && 268 >> 8 = 0x350105'Though, as said, the DHCP options could be in any order, so this isn't a robust method, especially if someone actively tries to work around it. But perhaps for testing it could do. Also, I assumed the IP header doesn't contain any options. |
_webmaster.102221 | I need to fire 301 redirectionfrom example.com... to example.comand example.com////// to example.comHere is my code: RewriteCond %{THE_REQUEST} \ /([^\?\ .]*)\.(?:\?|\ |$)RewriteRule ^ /%1 [L,R=301]It does not work.And here is my .htaccess file:RewriteEngine onRewriteCond %{HTTP_HOST} ^www.example\.com$ [NC]RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]RewriteCond %{THE_REQUEST} ^.*/index\.phpRewriteRule ^(.*)index.php$ /$1 [R=301,L]RewriteCond %{THE_REQUEST} \ /([^\?\ .]*)\.(?:\?|\ |$)RewriteRule ^ /%1 [L,R=301] | Redirect URL with multiple trailing dots and trailing slashes using .htaccess | htaccess;redirects;trailing slash | null |
_cseducators.2710 | As an tutor for introductory CS classes, I often come across students that have a very rigid understanding of a programming language up to what they have been taught so far. This most often manifests itself when they ask the question I can do that? I thought that.... I've most often seen this when showing students that branching and looping statements can be nested. It has even occurred when dealing with parenthesis and order of operations in mathematical expressions. As a concrete example, in Python many containers allow access via brackets:# dictionariesfoo = dict()foo[a] = 10foo[a]# dequesbar = deque('asdf')bar[0]# and many more...These students usually repeatedly struggle with this every time a new construct is introduced, as they fail to see how certain concepts from one part of the language extend to the other parts. In this case, it is that brackets are used for accessing elements.In short, how can I influence the student's thinking process from This language only allows me to do this into Can this language do this?, and help them expand upon what they have already seen and understood? | How can I help students develop intuition about a programming language? | undergraduate;syntax | I think this is a structure of knowledge problem. I suspect the disconnect is that you have organized your knowledge in a way your students haven't. You understand that strings, lists, dicts, and deques are all something called containers. You also understand that all containers can be accessed with []. Therefore, it's straightforward to consider that [] could be applied to any new container you come across.But do your students understand this organization of types in terms of containers? I bet they don't yet. They are still thinking about each type as an individual entity, disconnected from others.Experts' knowledge is organized much more effectively than novices' that's what it means to be an expert. (Cite: Relevant section from How People Learn, summary from Cal State Northridge)On the other hand, novices' understanding is tightly tied to shallow features like syntax. It will take a while for them to see the deeper organizational features. You can help your students become more like experts by explicitly helping them organize their knowledge. If it's not overwhelming for the students, teach them what a container is and what all containers have in common. More generally, connect concepts together to help support students' development of those expert-level connections. Good luck! |
_hardwarecs.7168 | I need an Android phone for long bicycle trips.Requirements in order of importance:Long battery lifetime (at least 12 hours with frequent GPS & camera usage, the longer the better)Small enough to fit in trousers pocketRather good GPSRather robust, as it might fall a few timesRather good camera (mostly daytime landscapes)Price: Hopefully less than 500 EURAble to make calls | Pocket-sized Android phone with big battery and good camera | android;smartphones | null |
_cs.9088 | I cannot imagine how cohomology is related to graph theory, actually I read solid definition from wiki, and to be honest, I cannot understand it. e.g I know what is homotopy (in simple term), group of functions such that I can continuously convert each of them to another one, and I think this is useful for understanding homology, but, is there similar visualization method for cohomology? (I'm not looking for exact definition, I want to imagine it, actually this is in graph theoretic concept). for more information see introduction of this paper. I want to understand it in this paper, how is useful? how to imagine it? P.S1: my field is not related to group theory, and as in introduction author wrote, this paper doesn't need deep group theoretic definition! and I don't want to be deep in group theory. Just looking for simple way to understand them.P.S2: I think I can imagine what is free group (which is in introduction of paper), at least by Calay graph seems to be easy to imagine it. P.S3: I also asked this in math.stackexchange but I think this is something between two field and may I get some mathematical answer there and some others here (from CS point of view) to understand it well. | Visualized definition of cohomology | graph theory;group theory | null |
_webmaster.58146 | I have very basic programming skills or other computer skills.I wanted to download whole web content including pdf text files from a website, by going through each pdf and downloading them individually is taking my time. what is this webcrawler and can i use it to download all of this files? again very limited or no knowledge about these. Can you let me know how to proceed? Will very much appreciate | Downloading pdf files | web crawlers | null |
_hardwarecs.2181 | I have a Harmony 650 Universal Remote, which I love! I use it to control a wide range of devices, among them playing and pausing media on on my Mac. (technically a Hackintosh, but that isn't directly relevant).The Harmony 650 cannot interface over Bluetooth--only IR. For a while now, I've been using the Logitech Harmony Adapter for PlayStation 3 alongside RemoteBuddy in order to get my remote to be recognized by my computer. One of the things I like about this adapter is its sensitivity--it's able to pick up an IR signal no matter which direction my remote is pointed. Annoyingly, however, the harmony adapter takes around seven seconds to wake up after it hasn't been used for a few minutes.I would like to replace this adapter with a non-Bluetooth, USB IR adapter. However, USB IR adapters seem to be very difficult to find nowadays. Where can I find a USB IR adapter that:Will work with my Mac (preferably via Remote Buddy's Candelair driver)Will have similarly great sensitivity to my Harmony PS3 adapterCosts less than $25 ($10 or less is preferable, but $25 is my limit) | USB IR Receiver for Mac | remote control | null |
_cs.75081 | This is a problem that I think is a reduction from the halting problem. I have on two separate practice exams statements that,Given a Turing machine T and a string w, to determine whether T will halt when started on input w.andGiven a Turing machine T and a string w, to determine whether T will halt when started on a blank tape.The answer key states that these problems are both partially decidable, which is astonishing to me given that they are reductions from the halting problem, which is undecidable.If there was a Turing maching M, that would halt if it's input was another Turing machine T that also halted on an arbitrary string, would that not violate the halting problem? Why are the two above statements considered to be partially decidable? | Is it possible to partially decide when will halt given any arbitrary input? | turing machines;halting problem | null |
_unix.40126 | I have a system with Solaris 10. One of the internal disks is broken:c0t0d0s2 auto:sliced rootdisk1_1 rootdg online c0t0d0s2 -c0t1d0s2 auto - - error c0t1d0s2 -c1t0d0s2 auto:sliced rootmirror1_1 rootdg online c1t0d0s2c1t1d0s2 auto:sliced rootmirror2_1 rootdg online c1t1d0s2 -When I run the format command, it becomes hung, because of the c0t1d0s2 disk. Is there a way to completly remove it from the system so that format can work again? | Solaris disk failed, how to remove it? | solaris;hard disk | This is from my emergency response notes. I neglected to mention the Solaris version and no longer have a recent Solaris box to check this on, so check the manpages and give it a try if it seems appropriate.First things first, you must umount any volumes on that disk, disable swap on it, and in every other say stop using it (e.g. if you're using Solaris software RAID). If you're using Veritas, check out rkosegi's answer.Then, find out what cfgadm calls the disk:cfgadm -alThe left column is the disk designation. Yes, I know, yet another format. At least this one includes the short block device name so it's not too difficult to find. Anyway, once you know it, say something like this: (based on your question, but do check first):cfgadm -c unconfigure c0::dsk/c0t1d0You can say cfgadm -al again to make sure the disk has been unconfigured. At this point, if your machine has hot-swappable disks, the disk will have been tri-stated, powered off, and controllers, backplanes etc. will be aware that you're about to remove it. If the disk has a ready to remove light, it'll illuminate.Once you're done replacing it:cfgadm -c configure c0::dsk/c0t1d0Once the disk is configured again, you can proceed with the rebuild. Good luck! |
_codereview.5178 | Due to software constraints, I cannot use the standard libraries, math.h, algorithm, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.I need to duplicate the Matlab any function in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size. Is it possible to write just one any function without using templates? How can I improve performance?I am striving for const correctness, performance/efficiency, and avoiding implicit type casting. bool any(bool* array, const int N){ // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true bool val; val = array[0] == true; int i = 0; while (val == false && i < N){ val = array[i++] == true; } return val;}bool any(bool** array, const int nRow, const int nCol){ // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true bool val; val = array[0][0] == true; int i = 0; while (i < nRow && val == false){ int j = 0; while (j < nCol && val == false){ val = array[i][j++] == true; } i++; } return val;} | Matlab any function in C / C++ | c++;c;algorithm;reinventing the wheel | I would suggest having the 2D implementation call the 1D implementation, rather than duplicating the any logic in both implementations, e.g.bool any(bool** array, const int nRow, const int nCol){ // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true bool val = false; for (int i = 0; i < nRow && val == false; ++i) { val = any(array[i], nCol); // call 1D version of any ) return val;} |
_webapps.1062 | Gmail's maximum attachment size is 25 MB. How to send files bigger than that? | How to send big files via email? | gmail;email;file exchange | Upload it to a website and send them a link. For example:Dropbox (in a public or shared folder)Google DriveNearlyFreeSpeech (paid)Amazon S3 (paid)If you upload it to a public service (e.g. a Dropbox public folder) and it's important that it's kept confidential, encrypt it with 7-Zip. |
_unix.192839 | I have a linux board with two ethernet interfaces as mentioned below.eth0 connected to another linux machine (ad-hoc)eth0 on board 191.168.1.2 connected to Linux machine 192.168.1.3eth1 on board 10.222.190.25 connected to router 10.222.190.1 I want to enable the ping from linux machine (192.168.1.3) towards router 10.222.190.1. Basically I want the traffic to be passed through the board and then towards router.I believe by setting the correct ipables and NAT rules we should be able to achieve this.Can someone guide me here to achieve it? | How to enable ping between machines connected in two interfaces? | iptables;nat;ethernet | null |
_webmaster.83822 | I'm trying to figure what is the correct use of rel=canonical in case of archive pages (be it date, author, category etc). Basically, I want them indexed but nofollowed noindexed but followed, as they serve mostly for sorting content and are not directly relevant in searches.However, I'm not sure what to do about the rel=canonical tag. Should it...Strictly be set to point at the taxonomy url?Point to the homepage (on the grounds that the index page is just a custom sort of the frontpage)?Be left blank? | rel=canonical for archive pages | seo;nofollow;noindex;rel canonical | null |
_softwareengineering.161336 | I'm using this as part of a game, but it's not really a game development question, so I'm putting it on this more general Stack Exchange.The goal is to generate random outputs for a fixed integer input, but (and this is the clincher) to generate the same random output every time the same random input is put in.The idea here is that the function will generate the world the same way every time, so we don't need to store anything; the function itself is the storage. Unfortunately access speed is a little slow, because the only way I can find to generate random numbers is to create a new Random() object with a seed based on the input, which is surprisingly slow.Is there a better way? I'm not worried about crypto-safe generation; in fact I'm just going to pick a random seed in advance and expose it quite publicly.The current code looks like this:private const int seed;public MapCell GetMapCell(int x, int y){ Random ran = new Random(seed + (x ^ y)); return new MapCell(ran.NextInt(0, 4));}Where the MapCell is one of four types (in fact it's more complicated than this, but not a whole lot). The point is that this could be called for any parameters, at any time, in no particular order, but it needs to return the same answer every time, if x and y are the same every time. That's why I can't fix a certain Random object and use it repeatedly.I also don't want to store anything, because I want to keep the RAM usage quite low, but allow the player to wander freely to the edges of Int.MaxValue | How to generate random numbers without making new Random objects? | c#;random | Sign is on a good track, but his algorithm is wrong. It is not much random. It is actually pretty hard to create random like this. I was playing around with this and everything I tried created obvious patterns when printed in 2D. In the end I manged to create an algorithm that doesn't create any eye-visible patterns. I looked for inspiration in existing random algorithms.public static uint bitRotate(uint x){ const int bits = 16; return (x << bits) | (x >> (32 - bits));}public static uint getXYNoise(int x, int y){ UInt32 num = seed; for (uint i = 0; i < 16; i++) { num = num * 541 + (uint)x; num = bitRotate(num); num = num * 809 + (uint)y; num = bitRotate(num); num = num * 673 + (uint)i; num = bitRotate(num); } return num % 4;}When this algorithm is used to render a 4-shades of gray image, it creates this:For comparison, the Random algorithm creates this pattern:And Sign's algorithm too has patterns: |
_unix.87992 | I switched to Arch Linux from Debian/Crunchbang and noticed much higher temperature.It's almost the same configuration: openbox, etc and Arch runs with 57-70 C but Debian works with 43C - 50CI really like Arch, but I can't fix it, my touchpad gets really hot.It's something with software, because wheezy was cold enough for comfortable work. | Arch CPU temperature much higher than on Debian | debian;arch linux;temperature | null |
_cs.52668 | Consider the following dynamic card game with a regular deck of 26 red cards and 26 black cards. A dealer draws the unturned cards one by one, and we can ask him to stop at any time. For every red card drawn, we get 1 dollar and lose 1 dollar for every black card drawn. The problem consists in finding an algorithm which returns the expected value of the game. If we denote by $b$ and $r$, respectively, the number of black and red cards left in the deck at any time, the expected value of the game $E(b,r)$ satisfies:$$E(b,r)=\max\left\{b-r,\frac{b}{b+r}\,E(b-1,r)+\frac{r}{b+r}\,E(b,r-1)\right\}\,,$$with boundary conditions $E(0,r)=0$ and $E(b,0)=b$. The expected value of the game is therefore given by $E(26,26)$.My question is, if we implement the recursive algorithm associated with the above formula, how can we determine its complexity? Using the trivial cases of $E(1,1)$ and $E(2,2)$, it would appear that we are dealing with exponential complexity, but is there a way to prove this properly, and if so, what is the number of necessary operations to compute $E(n,n)$ for an arbitrarily large integer $n$? Any ideas or references to literature would be greatly appreciated. | Complexity of dynamic card game algorithm | algorithms;algorithm analysis;runtime analysis;probability theory;recursion | As pointed out in the comments, your recurrence is wrong (though equivalent for $b=r$; it's a recurrence for $E(b,r)+b-r$). Also, you can solve this efficiently using memoization or its more principled cousin, dynamic programming. The dynamic programming solution calculates iteratively $E(i,j)$ for $i+j=0,1,\ldots,52$.Finally, to answer your question, if you implement you original solution, you get a running time satisfying the recurrence$$T(b,r) = C + T(b-1,r) + T(b,r-1),$$with initial conditions $T(b,0) = O(1)$, $T(0,r) = O(1)$. If $T'(b,r) = T(b,r)-C$ then$$T'(b,r) = T'(b-1,r) + T'(b,r-1),$$a recurrence solved by $\alpha \binom{b+r}{r}$. Taking the initial conditions into account, we get that$$T(b,r) = \Theta\left(\binom{b+r}{r}\right).$$In particular,$$T(n,n) = \Theta\left(\binom{2n}{n}\right) = \Theta\left(\frac{4^n}{\sqrt{n}}\right).$$(This assumes all arithmetic is $O(1)$. The running time is actually somewhat larger since the relevant numbers grow fast, but this is a (multiplicative) lower-order factor.) |
_unix.371565 | How you would configure a Unix Web server to automatically start on reboot?Webserver- apache Web serveros-centosUsing Wget command I have downloaded the apache Web server. For example In Windows, for the same situation I would install the apache tomcat with windows service. And in services I mark the run config as automatically. So that for if main windows server gets reboot. The apache tomcat will automatically gets up and run. I need to achieve this in redhat and centos with apache webserver | configure Unix apache Web server to automatically start on reboot? | centos;rhel;apache httpd;startup | I don't really understand your question since it is written quite poorly but I'll try to help.Run the following code to enable the httpd service to run on startupsudo systemctl enable httpdRun the following code to start the httpd service this time since it hasn't been probably activated yetsudo systemctl start httpd |
_softwareengineering.253752 | Consider I am going to write a simple file based logger AppLogger to be used in my apps, ideally it should be a singleton so I can call it viapublic class AppLogger { public static String file = ..; public void logToFile() { // Write to file } public static log(String s) { AppLogger.getInstance().logToFile(s); }}And to use itAppLogger::log(This is a log statement);The problem is, what is the best time I should provide the value of file since it is a just a singleton? Or how to refactor the above code (or skip using singleton) so I can customize the log file path? (Assume I don't need to write to multiple at the same time)p.s. I know I can use library e.g. log4j, but consider it is just a design question, how to refactor the code above? | How to change the state of a singleton in runtime | java;design patterns;object oriented;object oriented design;singleton | null |
_cs.21455 | Based on the Wikipedia implementation of insertion sort:Given an input array $A$:for i 1 to length(A) j i while j > 0 and A[j-1] > A[j] swap A[j] and A[j-1] j j - 1is there a way to quantify how many swaps are needed to sort the input list? It's $O(n^2)$, but I want a more precise bound. A perfectly sorted array clearly needs no swaps (so insertion sort is $\Omega(n)$), while a completely reversed array requires something on the order of $n^2$ swaps, but how do we quantify the number of swaps? | How can I quantify the number of swaps required for insertion sort? | algorithms;sorting | It is a classic exercise to relate the running time of insertion sort to the number of inversions in the input. An inversion is a pair of indices $i < j$ such that $A[i] > A[j]$. The number of comparisons made by insertion sort when there are $I$ inversions is always between $I$ and $I+n-1$. |
_unix.41221 | Is there a way to specify multiple variables (not just integers) in for loops in bash? I may have 2 files containing arbitrary text that i would need to work with.What i functionally need is something like this:for i in $(cat file1) and j in $(cat file2); do command $i $j; doneAny ideas? | Multivariable For Loops | bash;command substitution;for | First, Don't read lines with for, as there are several unavoidable issues with reading lines via word-splitting.Assuming files of equal length, or if you want to only loop until the shorter of two files are read, a simple solution is possible.while read -r x && read -r y <&3; do ...done <file1 3<file2Putting together a more general solution is hard because of when read returns false and several other reasons. This example can read an arbitrary number of streams and return after either the shortest or longest input.#!/usr/bin/env bash# Open the given files and assign the resulting FDs to arrName.# openFDs arrname file1 [file2 ...]openFDs() { local x y i arr=$1 [[ -v $arr ]] || return 1 shift for x; do { exec {y}<$x; } 2>/dev/null || return 1 printf -v ${arr}[i++] %d $y done}# closeFDs FD1 [FD2 ...]closeFDs() { local x for x; do exec {x}<&- done}# Read one line from each of the given FDs and assign the output to arrName.# If the first argument is -l, returns false only when all FDs reach EOF.# readN [ -l ] arrName FD1 [FD2 ...]readN() { if [[ $1 == -l ]]; then local longest shift else local longest= fi local i x y status arr=$1 [[ -v $arr ]] || return 1 shift for x; do if IFS= read -ru $x ${arr}[i] || { unset -v ${arr}[i]; [[ ${longest+_} ]] && return 1; }; then status=0 fi ((i++)) done return ${status:-1}}# readLines file1 [file2 ...]readLines() { local -a fds lines trap 'closeFDs ${fds[@]}' RETURN openFDs fds $@ || return 1 while readN -l lines ${fds[@]}; do printf '%-1s ' ${lines[@]} echo done}{ readLines /dev/fd/{3..6} || { echo 'error occured' >&2; exit 1; }} <<<$'a\nb\nc\nd' 3<&0 <<<$'1\n2\n3\n4\n5' 4<&0 <<<$'x\ny\nz' 5<&0 <<<$'7\n8\n9\n10\n11\n12' 6<&0# vim: set fenc=utf-8 ff=unix ts=4 sts=4 sw=4 ft=sh nowrap et:So depending upon whether readN gets -l, the output is eithera 1 x 7b 2 y 8c 3 z 9d 4 105 1112ora 1 x 7b 2 y 8c 3 z 9Having to read multiple streams in a loop without saving everything into multiple arrays isn't all that common. If you just want to read arrays you should have a look at mapfile. |
_softwareengineering.333237 | We are using Firebase which is probably similar to MongoDB in that it stores arbitrary JSON structures. We are also using Node.js and so the library in question could in theory be used both backend and frontend.So yes we have a models library which has code to create a model and run special validation methods including setters which will validate upon setting model data. After validation, we have objects which we can put in the DB. Firebase also has validation which we will use (and perhaps in the end it will be the only validation we need?).It would be extremely useful to use this validation library everywhere, including the front-end. The problem is that our DB schemas are in the code that needs to be sent to the front-end for the library to work.How bad of an idea is it to send the schemas to the front-end?I believe we are mostly interested in protecting our proprietary information, and given that, I don't think plain code will do.We could send JSON data representing the schemas to the front-end along with the code and then dynamically set the schemas, that adds a layer of obfuscation to my knowledge, but seems complicated.Anyone have experience with this type of problem?Seems like there would be a lot of value added to having the same JS library front-end and back-end. | Putting NoSQL DB schemas on front-end, safely | javascript;node.js;validation;nosql;front end | null |
_webmaster.60595 | I ran into the following issue:On a website I want to prevent unauthorized access to a set of .xml files - the user has to authenticate first. Now it would be possible for an authenticated user to type the URL of the file I don't want them to see. To prevent this, I created a simple php script that checks user authentication, then serves up the XML (with appropriate Content-type header).At the same time, I put the following in the .htaccess file in the directory with .xml (and other) files:<Files ~ (.xml)>Order allow,denyDeny from allAllow from xx.yy.zz.tt (IP address of server)</Files>This did the trick - .xml files were not longer directly accessible, even for an authenticated user. But here is the thing I don't understand:If I leave out the 'Allow from' line, the php script still manages to access the .xml files. It seems that the .htaccess is completely ignored when it comes to php.So my question is two fold:Is this expected behavior?If so, then what method would one use to prevent a php script from accessing a particular file (or group of files)?There is clearly a fundamental issue around .htaccess that I completely failed to grasp. Thanks for your insights. | Why does .htaccess not prevent a php script from accessing a file | php;htaccess | PHP doesn't work with the file over HTTP but directly on the filesystem, unless you access the file over HTTP using cUrl or file_get_contents('http://.../file.xml').If you want to prevent the files from being accessed without the user being authenticated first, place the files outside the public directory and serve them from there./files//public_html/index.phpNow, for the files...if ($user->isAuthenticated()) { // set proper file header // print out the file content from /files/}Documentation might help you get a grasp on what I have in mind... http://cn2.php.net/manual/en/function.readfile.php#48683This way you'll prevent anonymous users from accessing the files as those are not stored in a publicly accessible directory. |
_unix.317182 | I have a simple whiptail menu. Below are the details:whiptail --title Menu example --menu Choose an option 20 78 16 \<-- Back Return to the main menu. \Add User Add a user to the system. \Modify User Modify an existing user. \List Users List all users on the system. \Add Group Add a user group to the system. \Modify Group Modify a group and its list of members. \List Groups List all groups on the system.When I execute this, It works fine. But the only problem I have is I need to use the Keyboard in order to choose a particular option. I need this to respond to my mouse. | Is it possible to use the mouse in whiptail? If yes, then how can we do that | mouse;input;dialog;whiptail | null |
_unix.375590 | On my Mac terminal when I put sudo apt-get install ssh, its answer password. I dont have it. How can I find it please | sudo apt-get install ssh | ssh;apt;password | null |
_unix.217365 | There is no fonts directory in /usr/share at all on my system. How can I go about installing Microsoft True Type fonts in Centos 7? I only need Arial and Georgia. | How to install Microsoft True Type fonts for Centos 7? | fonts | Try install one of these using rpm (I'm not sure which is better): http://www.my-guides.net/en/images/stories/fedora12/msttcore-fonts-2.0-3.noarch.rpmhttp://nchc.dl.sourceforge.net/project/mscorefonts2/rpms/msttcore-fonts-installer-2.6-1.noarch.rpmhttp://li.nux.ro/download/nux/dextop/el7/x86_64/webcore-fonts-3.0-1.noarch.rpmBTW, if your problem is not compatible issue, please use free/libre fonts. There are many beautiful ones, such as DejaVu, Droid and URW. |
_webmaster.16383 | I have urls like the following:http://example.com/item/1http://example.com/item/1341http://example.com/item/33324I want to set up a funnel in Google Analytics and I understand that I can use a regular expression.What would i enter to match all the above URLs i.e /item/#{id}? | Google Analytics - Goals setup regular expression match | google analytics;url | null |
_unix.110584 | I have a log file trace.log which prints the time stamp, thread name and Transaction method and transaction ID as below.2014-01-23 15:50:41,724 [catalina-exec-35] INFO TRANSACTION getConnection REQUEST, ID=1308::2014-01-23 15:50:41,725 [catalina-exec-33] INFO TRANSACTION getConnection REQUEST, ID=1304::2014-01-23 15:50:41,727 [catalina-exec-10] INFO TRANSACTION getConnection REQUEST, ID=1298::2014-01-23 15:50:41,727 [catalina-exec-24] INFO TRANSACTION getConnection REQUEST, ID=1307::2014-01-23 15:50:41,727 [catalina-exec-12] INFO TRANSACTION getConnection DONE, ID=1305::2014-01-23 15:50:41,733 [catalina-exec-10] INFO TRANSACTION getConnection DONE, ID=1298::2014-01-23 15:50:41,734 [catalina-exec-26] INFO TRANSACTION getConnection REQUEST, ID=1313::2014-01-23 15:50:41,734 [catalina-exec-26] INFO TRANSACTION getConnection DONE, ID=1313::2014-01-23 15:50:41,738 [catalina-exec-39] INFO TRANSACTION getConnection REQUEST, ID=1311::2014-01-23 15:50:41,733 [catalina-exec-35] INFO TRANSACTION getConnection DONE, ID=1308::2014-01-23 15:50:41,738 [catalina-exec-27] INFO TRANSACTION getConnection REQUEST, ID=1309::2014-01-23 15:50:41,737 [catalina-exec-22] INFO TRANSACTION getConnection REQUEST, ID=1310::2014-01-23 15:50:41,743 [catalina-exec-30] INFO TRANSACTION getConnection REQUEST, ID=1315::2014-01-23 15:50:41,744 [catalina-exec-39] INFO TRANSACTION getConnection DONE, ID=1311::2014-01-23 15:50:41,747 [catalina-exec-2] INFO TRANSACTION getConnection REQUEST, ID=1318::I want to grep and print the time stamp of the getConnection REQUEST and getConnection DONE for a particular ID in a single line into a file.I have a written a shell script that printing the time stamp in multiple lines as below.Here is my shell scriptfor i in {1..800}do echo Welcome $i times echo ID=$i, getConnection >> time.log grep ID=$i: trace.log | grep getConnection | cut -d'[' -s -f1 >> time.logecho >> time.logdoneThe output is as shown belowID=791, getConnection2014-01-23 15:50:16,7032014-01-23 15:50:16,706ID=792, getConnection2014-01-23 15:50:16,7042014-01-23 15:50:16,704ID=793, getConnection2014-01-23 15:50:16,7042014-01-23 15:50:16,709ID=794, getConnection2014-01-23 15:50:16,7082014-01-23 15:50:16,712How I can change that? I need output as shown below:ID=792, getConnection 2014-01-23 15:50:16,703 2014-01-23 15:50:16,706ID=792, getConnection 2014-01-23 15:50:16,704 2014-01-23 15:50:16,704ID=793, getConnection 2014-01-23 15:50:16,704 2014-01-23 15:50:16,709ID=794, getConnection 2014-01-23 15:50:16,708 2014-01-23 15:50:16,712 | A shell script to write selected fields to a single line | bash;shell script;grep;bash script;cut | Don't use shell loops to process text, that's bad practice.The shell's job is to run commands (the right ones) and make them cooperate to a task.Here, the right command is the practical extraction and report language interpreter called once, not several commands run (in sequence!) for each line of a file.perl -lne ' if (/(.*?) \[.*getConnection (.*?), (ID=\d+)/) { if ($2 eq REQUEST) {$r{$3}=$1} elsif ($2 eq DONE) {print $3, getConnection $r{$3} $1 if $r{$3}} }' < your-file |
_webapps.18078 | My girlfriend is pulling her hair out using Kerio connect at home for accessing her work emails. Everything seems to operate at a snails pace. She is using firefox on a MacBook Pro. I was wondering if there was anything that could make her life easier. For example I remember that it is possible to somehow configure firefox so that it pre-fetched linked pages so that jumping from one page to another became faster... I also remember that when I tried this out myself years ago it had some unwanted side effects so I undid that option and never tried it again. Is it possible to switch on this feature for just one specific site? And would help with kerio anyway?Anything else we could try? | Any way to speed up kerio connect? | webmail | null |
_scicomp.4864 | First I'm not 100% sure I'm on the good stack for asking my question. I would like to get a bilinear form for linear elasticity that separate a rotational part from a pure divergence part, so starting from the Navier equation \begin{equation} \mu \nabla^2 \mathbf u +(\mu+\lambda)\nabla(\nabla \cdot \mathbf u) + \mathbf f =0 \end{equation}Then I use the vector Laplacian identity $\nabla(\nabla \cdot \mathbf A)= \nabla^2 \mathbf A +\nabla \times \nabla \times\mathbf A$ to write\begin{equation} (\lambda +2\mu) \nabla^2 \mathbf u +(\mu+\lambda)\nabla \times (\nabla \times\mathbf u) + \mathbf f =0 \end{equation}So multiplying by a test function $\mathbf v$ I get\begin{equation}\int_\Omega \bigg((\lambda +2\mu) \nabla^2 \mathbf u \cdot \mathbf v +(\mu+\lambda)\nabla \times (\nabla \times\mathbf u)\cdot \mathbf v + \mathbf f \cdot \mathbf v \bigg) d\Omega=0 \end{equation}and using Green formula, \begin{equation}\int_\Omega \bigg((\lambda +2\mu) (\nabla \mathbf u :\nabla \mathbf v) +(\mu+\lambda)(\nabla \times \mathbf v)\cdot(\nabla \times\mathbf u) + \mathbf f \cdot \mathbf v \bigg) d\Omega=0 \end{equation}I'm skeptical about this for, since when I compare the bilinear form\begin{equation}a(\mathbf u,\mathbf v) := \int_\Omega \bigg((\lambda +2\mu) (\nabla \mathbf u :\nabla \mathbf v) +(\mu+\lambda)(\nabla \times \mathbf v)\cdot(\nabla \times\mathbf u) \bigg) d\Omega\end{equation}With the classical one\begin{equation}a(\mathbf u,\mathbf v) := \int_\Omega \sigma(\mathbf u):\varepsilon(\mathbf v) d\Omega\end{equation}I got few different terms. For instance, in 2D the classical form (noted $a_1$) gives \begin{eqnarray}a_1(\mathbf u,\mathbf v) &=& \int_\Omega \sigma(\mathbf u):\varepsilon(\mathbf v) d\Omega \\&=& \bigg(2\mu \frac{\partial u_x}{\partial x}+\lambda(\frac{\partial u_x}{\partial x}+\frac{\partial u_y}{\partial y}) \bigg)\frac{\partial v_x}{\partial x}+\mu\bigg(\frac{\partial u_y}{\partial x}+\frac{\partial u_x}{\partial y}\bigg)\bigg(\frac{\partial v_x}{\partial y}+\frac{\partial v_y}{\partial x}\bigg)+\bigg(2\mu \frac{\partial u_y}{\partial y}+\lambda(\frac{\partial u_x}{\partial x}+\frac{\partial u_y}{\partial y})\bigg) \frac{\partial v_y}{\partial y}\\&=&(\lambda+2\mu) \bigg(\frac{\partial u_x}{\partial x} \frac{\partial v_x}{\partial x} +\frac{\partial u_y}{\partial y}\frac{\partial v_y}{\partial y}\bigg) + \mu\bigg(\frac{\partial u_y}{\partial x}+\frac{\partial u_x}{\partial y}\bigg)\bigg(\frac{\partial v_x}{\partial y}+\frac{\partial v_y}{\partial x}\bigg)+\lambda\bigg(\frac{\partial u_y}{\partial y}\frac{\partial v_x}{\partial x} +\frac{\partial u_x}{\partial x}\frac{\partial v_y}{\partial y}\bigg)\end{eqnarray}Whereas, the rotational form gives\begin{eqnarray}a_2(\mathbf u,\mathbf v) &=& \int_\Omega \bigg((\lambda +2\mu) (\nabla \mathbf u :\nabla \mathbf v) +(\mu+\lambda)(\nabla \times \mathbf v)\cdot(\nabla \times\mathbf u) \bigg) d\Omega\\&=& (2\mu+\lambda)\bigg(\frac{\partial u_x}{\partial x}\frac{\partial v_x}{\partial x} +\frac{\partial u_x}{\partial y}\frac{\partial v_x}{\partial y}+\frac{\partial u_y}{\partial x}\frac{\partial v_y}{\partial x} +\frac{\partial u_y}{\partial y}\frac{\partial v_y}{\partial y}\bigg)+ (\lambda+\mu)\bigg(\frac{\partial u_y}{\partial x} -\frac{\partial u_x}{\partial y}\bigg)\bigg(\frac{\partial v_x}{\partial y} -\frac{\partial v_y}{\partial x}\bigg)\end{eqnarray}The $(\lambda +\mu)$ terms may be developped and some terms may be factorized with some other terms of $(2\mu+\lambda)$\begin{eqnarray}a_2(\mathbf u,\mathbf v) &=& (2\mu+\lambda)\bigg(\frac{\partial u_x}{\partial x}\frac{\partial v_x}{\partial x} +\frac{\partial u_y}{\partial y}\frac{\partial v_y}{\partial y}\bigg)+\mu\bigg(\frac{\partial u_x}{\partial y}\frac{\partial v_x}{\partial y} + \frac{\partial u_y}{\partial x}\frac{\partial v_y}{\partial x}\bigg)+ (\lambda+\mu)\bigg(\frac{\partial u_y}{\partial x}\frac{\partial v_x}{\partial y} +\frac{\partial u_x}{\partial y}\frac{\partial v_y}{\partial x}\bigg)\end{eqnarray}The $\mu$ terms in two and second expressions may be factorized \begin{eqnarray}a_2(\mathbf u,\mathbf v) &=& (2\mu+\lambda)\bigg(\frac{\partial u_x}{\partial x}\frac{\partial v_x}{\partial x} + \frac{\partial u_y}{\partial y}\frac{\partial v_y}{\partial y}\bigg)+\mu\bigg(\frac{\partial u_y}{\partial x}+\frac{\partial u_x}{\partial y}\bigg)\bigg(\frac{\partial v_x}{\partial y}+\frac{\partial v_y}{\partial x}\bigg)+ \lambda\bigg(\frac{\partial u_y}{\partial x}\frac{\partial v_x}{\partial y} +\frac{\partial u_x}{\partial y}\frac{\partial v_y}{\partial x}\bigg)\end{eqnarray}This equation is almost the same as $a_1$ except for the $\lambda$ term.Could someone correct me ?PS: the rotational being defined by\begin{eqnarray}\nabla \times \mathbf u =\left|\begin{array}{l}\partial_x\\\partial_y \\\partial_z\end{array}\right.\times\left|\begin{array}{l}u_x\\u_y \\u_z\end{array}\right.=\left|\begin{array}{l}\partial_y u_z -\partial_z u_y\\\partial_z u_x -\partial_x u_z \\\partial_x u_y -\partial_y u_x\end{array}\right.\end{eqnarray}We have\begin{eqnarray}(\nabla \times \nabla \times \mathbf u ) \cdot \mathbf v =\left|\begin{array}{l}\partial_y (\partial_x u_y -\partial_y u_x) - \partial_z(\partial_z u_x -\partial_x u_z)\\\partial_z (\partial_y u_z -\partial_z u_y) - \partial_x(\partial_x u_y -\partial_y u_x)\\\partial_x (\partial_z u_x -\partial_x u_z) - \partial_y (\partial_y u_z -\partial_z u_y)\end{array}\right.\cdot \left|\begin{array}{l}v_x \\v_y\\v_z\end{array}\right.\end{eqnarray}And using integration by part (but I suspect that the flaw stands here), \begin{eqnarray}\int_\Omega (\nabla \times \nabla \times \mathbf u ) \cdot \mathbf v &=&-\int_\Omega \partial_y v_x(\partial_x u_y -\partial_y u_x) - \partial_z v_x (\partial_z u_x -\partial_x u_z)\\&&+\partial_z v_y(\partial_y u_z -\partial_z u_y) - \partial_x v_y (\partial_x u_y -\partial_y u_x)\\&&+\partial_x v_z(\partial_z u_x -\partial_x u_z) - \partial_y v_z(\partial_y u_z -\partial_z u_y)\\&=& - \int_\Omega (\partial_y v_x - \partial_x v_y )(\partial_x u_y -\partial_y u_x) +(\partial_z v_y-\partial_y v_z) (\partial_y u_z -\partial_z u_y) +(\partial_x v_z- \partial_z v_x )(\partial_z u_x -\partial_x u_z)\\&=& \int_\Omega (\nabla \times \mathbf v )\cdot (\nabla \times \mathbf u)\end{eqnarray}Thank you very much. | variational formulation of linear elasticity | pde;well posedness;elliptic pde | null |
_webmaster.48313 | I have a website where Google Webmaster Tools reports 15,000 links as 404 errors. However, all links return a 200 when I visit them. The problem is, that eventhough I can visit these pages and return a 200, all those 15,000 pages won't index in Google. They aren't appearing in search results. These are constant errors Google Webmaster Tools keeps reporting and I'm not sure what the problem is. We've thought of a DNS issue, but it shouldn't be a DNS issue, because if it were, no page would be indexed (I have 10,000 perfectly indexed).Regarding URL parameters, my pages do not share a similarity in URL parameters that can make it obvious to me what could be causing the error. | Google Webmaster Tools reports fake 404 errors | seo;indexing;404;magento;web crawlers | null |
_unix.74862 | Today for testing purpose I installed KDE alongside Cinnamon in Linux Mint 14. Unfortunately, after that my system language switch to Chinese!!! All the menus and notification is in Chinese now!! How can I switch back to English? | Linux Mint 14 system language turns into chinese. How can I switch back to English? | linux mint;kde;locale | You should be able to choose the language at the login screen. If not, open a terminal (you can use Alt+F2 to get the run dialog) and run (source):echo -e 'LANG=en_US\nLANGUAGE=en_US:en' | sudo tee /etc/default/localeecho -e 'LANG=en_US\nLanguage=en_US' > ~/.pam_environmentThen log out and log back in again.EDIT (in response to the OP's comment)The commands above are just a quick way of editing a couple of text files. If they don't work for whatever reason, you can just edit the files manually using a text editor (I believe the default on KDE is write). So, open a terminal and run:sudo kwrite /etc/default/locale` Edit the file to contain only these lines:LANG=en_USLANGUAGE=en_US:enNow open ~/.pam_environment:sudo kwrite ~/.pam_environmentEdit the file to contain only these lines:LANG=en_USLanguage=en_USTake care: if you write and save the incorrect values to your locale, you might have troubles on booting. |
_codereview.10763 | Is this going to leak memory or is it ok? Please also let me know if there is something else that I need to pay attention to.typedef struct {int len;UC * message; }pack;pack * prepare_packet_to_send(const int length,const unsigned char tag,const int numargs, ... ){pack *layer= malloc(sizeof(pack));va_list listp;va_start( listp, numargs );int step = 0;layer->message = (unsigned char *) malloc(length);layer->len = length;int i = 0;int len = 0;unsigned char *source_message ; for( i = 0 ; i < numargs; i++ ){source_message = va_arg( listp, unsigned char *);len = va_arg( listp, long);memcpy(layer->message+step, source_message, (long) len);step+=len;}va_end( listp ); return layer;}main(){pack *test = call prepare_packet_to_send(sizeof(var1)+sizeof(var2),any tag,any args) // are following two frees correct/enough? or is there something else i need to do to prevent mem leak?free(test->message);free(test);} | Free memory outside function | c;memory management | null |
_softwareengineering.186324 | I am writing an application to report to the user(devs) when their website fails. And what I mean by fails which is unfunctional or needs to report the problem to devs. I do understand that status code 2XX means 'Success' according to wiki. But does that really do? I have access my website once and returned 204 'No-Content', which is unfunctional to me. So the question is, what are the list of status codes return should It be considered website is functional? | Which HTTP status codes are really OK? | web development;programming practices;http response | Every code is acceptable in some circumstances, but indicate a problem in other circumstances.Take 404. It may indicate:that a link on your website is broken (which is actually a problem you may want to fix),that the client is trying deliberately to break the website (which is a problem too, but should be included in security reports instead),that somewhere, some website has a broken link or that a person misspelled an address (which doesn't matter, since you can't do anything with it),or that the page is not intended to exist (which is an expected situation and should not worry anybody). Example: /wpad.dat.Take 200. It may indicate:a success,or that your security system is not working any longer, and is not forbidding the access to some very confidential web page to guests (the only acceptable response being 401 Unauthorized).If you want to report problems to developers, do it the right way: through logging and exception handling, not through something which was never intended for that, like HTTP status codes. |
_unix.230707 | Is there any way to add android to Yumi? I want to be able to boot my computer from a USB stick and install android.So, how can I install Android using Yumi or any other multiboot USB creator? | How to add Android x86 to Yumi! | usb;android;bootable | Download any ISO Image from the website http://www.android-x86.org. It's an Android distribution that works on normal x86 processors. For example, Android 4.4. Then write that ISO to a flash drive. |
_scicomp.14617 | I'm student of computer science (BS) and considering computational science as the field to major in for MS program.I have two questions which might look silly but I'm really confused:1- Are Scientific Computing and Computational Science fields the same?. In Iran we just have Scientific Computing as an MS program in computer science. After searching for days in Google I saw there were some websites stating that Scientific Computing and Computational Science are the same...2- Is Computer Science a good major to enter computational science?. We have many courses in Numerical Mathematics, Algorithms, and Programming in CS but it seems like you need good background in physics or chemistry. I feel that it's a major for Mechanical engineers or physicists. | General question about Computational Science | computational physics | Scientific Computing and Computational Science are the same field. Both involve using computation to answer scientific question through numerical methods.Almost all technical fields can lead into computational science. Very few people at the end of their undergraduate degree have all the skills needed to be successful in this field. For instance, I got my undergraduate degree in mechanical engineering, which meant that I had a strong understanding of the physics, but my programming and algorithm knowledge was relatively weak. I had to pick most of this up as I went. For you it would likely be the opposite, with you needing to learn the physics. My experience is that this is not significantly more ground to make up than the average graduate student needs to learn when they join any other (non-computational) lab.In fact, computational science as a program is actually more common in computer science and mathematics departments, since the engineering and physical science departments are usually more focused on what question is being answered rather than how it is being answered. |
_datascience.19922 | When training a neural network with keras for the categorical_crossentropy loss, how exactly is the loss defined? I expect it to be the average over all samples of$$\textstyle\text{loss}(p^\text{true}, p^\text{predict}) = -\sum_i p_i^\text{true} \log p_i^\text{predict}$$but couldn't find a definitive answer in the docs nor in the code. An authoritative reference is desirable.Looking at the code I'm not sure if the computation is delegated to tensorflow/theano.(There is an analogous question concerning the accuracy; the code is clearer, but I don't see a call to mean()?)PS.From this code, it appears that loss and accuracy are computed as in loss_and_acc(...) but before the last training epoch (keras version 2.0.4, same results for tensorflow and theano backend).#!/usr/bin/python3import numpy as npfrom numpy.random import randint, seedfrom keras import __version__ as keras_versionfrom keras.models import Sequentialfrom keras.layers import DenseN = 4 # ClassesS = 10 # Samplesnn = Sequential()nn.add(Dense(input_dim=1, units=N, kernel_initializer='normal', activation='softmax'))nn.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])seed(7)X = np.random.random((S, 1))Y = np.vstack([np.eye(1, N, k=randint(0, N)) for _ in range(S)])#for (x, y) in zip(X, Y) : print(x, y)def loss_and_acc(NN, X, Y) : loss = [] acc = [] for (p, q) in zip(Y, NN.predict(X)) : loss += [ -sum(a*np.log(b) for (a, b) in zip(p, q) if (b != 0)) ] acc += [ np.argmax(p) == np.argmax(q) ] return (np.mean(loss), np.mean(acc))print(Keras version: , keras_version)for _ in range(10) : print(Before: loss = {}, acc = {}.format(*loss_and_acc(nn, X, Y))) H = nn.fit(X, Y, epochs=1, verbose=0).history print(History: loss = {}, acc = {}.format(H['loss'][-1], H['acc'][-1]))Output:Using Theano backend.Keras version: 2.0.4Before: loss = 1.3843669414520263, acc = 0.2History: loss = 1.3843669891357422, acc = 0.20000000298023224Before: loss = 1.3834303855895995, acc = 0.2History: loss = 1.3834303617477417, acc = 0.20000000298023224Before: loss = 1.3824962615966796, acc = 0.3History: loss = 1.3824962377548218, acc = 0.30000001192092896Before: loss = 1.381564486026764, acc = 0.3History: loss = 1.3815644979476929, acc = 0.30000001192092896Before: loss = 1.380635154247284, acc = 0.3History: loss = 1.380635142326355, acc = 0.30000001192092896Before: loss = 1.3797082901000977, acc = 0.3History: loss = 1.3797082901000977, acc = 0.30000001192092896Before: loss = 1.378783941268921, acc = 0.2History: loss = 1.378783941268921, acc = 0.20000000298023224Before: loss = 1.3778621554374695, acc = 0.2History: loss = 1.3778622150421143, acc = 0.20000000298023224Before: loss = 1.3769428968429565, acc = 0.2History: loss = 1.3769428730010986, acc = 0.20000000298023224Before: loss = 1.3760262489318849, acc = 0.3History: loss = 1.3760262727737427, acc = 0.30000001192092896 | Keras categorical_crossentropy loss (and accuracy) | keras;categorical data;reference request;loss function | null |
_webapps.23186 | I've sent an email to [email protected] and I would like to CC the email to [email protected], I've forgotten to CC a copy to [email protected]. If I resend another email to [email protected] and CC it to [email protected], [email protected] would have received 2 emails from me.Is there a way to CC a copy of an email which is already sent? | Is there a way to CC a copy of an email which is already sent? | gmail;email | There is no way to do it. The first email you sent out will never know about the 2nd email. Even if there is a way to recall the first email, recalled emails never work flawlessly. The only option: think of something new to add to the chain, then forward it to both A and B. It could be as simple as saying that you are adding B to the CC line. Using forward makes sure the newest email has any attachments that were on the first email. |
_webmaster.103585 | I bought an example.org domain and created an account on a free web host. When signing up, I was forced to choose a 3rd level domain name for my site. Then I was allowed to specify my 2nd level domain name. Now example.org is under my hosting account waiting for the nameservers to take effect, but my 3rd level domain is already functioning. I put an index.html on it, and it shows as expected.There is a good chance that I will not be able to delete that 3rd level domain at all and will have the two mirror sites as shown below:example.organynameyouchoose.myfreewebhostingservername.comMay this lead to Google penalizing my 2nd level domain for content duplication? | My 2nd level domain has a non-deletable 3rd level domain mirror. Will Google penalize it for this? | seo;domains;penalty;mirror | May this lead to Google penalizing my 2nd level domain for content duplication?Just to clarify, there is no penalty as such for duplicate content, it's just that your ranking will be divided between the two domains if both are returned in the SERPs. Not only could this reduce the ranking for your primary domain, the 3rd level domain could even rank higher and result in confusion for your users.However, Google is pretty good at deciding for itself which is the canonical domain so the above scenario may not cause you much of a problem. But you can bet that Google will find the 3rd level domain and this will be searchable.So, steps should be taken to avoid the duplicate content and to avoid the 3rd level domain being indexed:If you can, you should set up a 301 redirect from the 3rd level domain to your primary domain. eg. Using .htaccess on Apache. However, this might not be possible on your free host. As a fallback, you could perhaps implement a JavaScript redirect instead.Use a rel=canonical element in the head section of your HTML document that points to the primary domain.Use absolute URLs/links throughout your site. Or, root-relative URLs and a base element in the head section that points to the primary domain.Also note that there can be other issues with free hosts/subdomains. For example:Free subdomain not indexed |
_unix.228137 | So I've installed WANem and the only way to download it is by downloading a WANem custom version of Knoppix OS with WANem already installed. I want to add a start up script to configure something every time I start this OS, but since there's no option for me to install the OS and I have to run it from USB every time, I see no way to do this.Is there a way for me to add a start up script to a bootable USB? | Debian: Add start up script to bootable USB | debian;scripting;startup | null |
_unix.192624 | I want to create multi-bootable USB with GRUB2. But I don't want to use physical USB stick to experiment with.How can I create virtual USB to play with it as it is real device using qemu? I want to boot guest machine from it, setup GRUB to it from guest OS and so on.Later, I want to be able to take the virtual image and copy it to my real USB stick. How could I do that? Perhaps with if=usb_image.vmdk of=/dev/sdx? | Boot from virtual usb drive in qemu-kvm | debian;usb;qemu;bootable | Are you using an abstraction layer such as libvirt? If so then simply add a disk image file as a USB Disk.If you're running kvm/qemu directly, then the man page (man kvm or man qemu) provides the answers:USB options:-usb Enable the USB driver (will be the default soon)-usbdevice devname Add the USB device devname.disk:[format=format]:file Mass storage device based on file. The optional format argument will be used rather than detecting the format. Can be used to specify format=raw to avoid interpreting an untrusted format header.So, something like this should workdd if=/dev/zero bs=1M count=8000 of=usb.img # Create the usb disk imagekvm ... -usb -usbdevice disk:raw:usb.img # Start kvm/qemuLater, you can run dd if=usb.img bs=1M of=/dev/sdX, but you should make sure your /dev/sdX really is the USB device! You'll also need to make your virtual image the same size as your stick (or smaller). Remember a 1GB stick is only 10^9 bytes, not 2^31 bytes. |
_cogsci.3557 | J.Campbell suggest that the difference between age groups on being politically conservative is small. But F.Glamsers article concludes: there was a significant positive correlation between age and conservative opinions even when social class, education, father's SES, and the size of the respondent's childhood community were controlled.While these articles are quite old (1981 & 1974) a more recent poll indicates that old people tend to be more conservative. I'm wondering whether there is an neurological and psychological explanation of that phenomena. | Are older people more likely to be politically conservative and why? | social psychology;political psychology;cognitive neuroscience | null |
_unix.170050 | Is it possible to install CouchBase in ArchLinux?This database looks so promising, but they only provide .deb, .rpm, windows, and mac version.http://www.couchbase.com/nosql-databases/downloads | How to install Couchbase on ArchLinux | arch linux;rpm;deb | It is pretty easy to build it from sources if you need it on your development machine: https://github.com/couchbase/manifest#building-with-reporepo init -u git://github.com/couchbase/manifest.git -m rel-3.0.1.xmlrepo syncmakeit will install server for you to $PWD/install |
_unix.85868 | Suppose that I have a desktop computer such that everything works except keyboard. Is it possible to install and run Linux to this computer? I guess the answer is no as super user password requires keyboard but I'm not completely sure about this fact. | Can I do everything on Linux without keyboard? | keyboard;mouse | Actually, you can, as long as the proper tools are installed.A few years ago, I ended up playing quite a bit with a Compaq TC1000 tablet. It had a detachable keyboard and a stylus.Typing without the keyboard was a bit of a challenge, but I had installed an on-screen keyboard that activated during the display manager login and once my graphical session was established and ready. This setup used standard Debian packages during the Gnome 2.0 heyday.I typically used it in its undocked mode to either browse the web or to take notes with Xournal. Xournal's ability to either annotate PDF's or appear just like a legal pad made it very easy to take handwritten notes for later transcription.If standard text was desired, the on-screen keyboard I was using could be trained to recognize your block handwriting, in some ways acting like the Palm Pilot-style Graffiti handwriting recognition, except that you could use your natural handwriting, rather than use a dedicated alphabet.It was functional for a couple of years until the hardware on that tablet became incredibly slow (as software bloated) and then finally died altogether. I see no reason that a modern touchscreen device couldn't do the same thing. |
_webapps.70834 | I have a Google Docs form that I use to track my customers complaints. Is it possible to have a counter field pre-fill with an incremental number? I want my customers to have a complaints number when I'm talking with them. | Pre-fill field with formula incremental counter in Google form | google spreadsheets | null |
_scicomp.20615 | I am working to solve Poisson's equation in 2D axisymmetric cylindrical coordinates using the Jacobi method. The $L^2$ norm decreases from $\sim 10^3$ on the first iteration (I have a really bad guess) to $\sim 0.2$ very slowly. Then, the $L^2$ norm begins to increase over many iterations.My final matrix is weakly diagonally dominate, except for the 2nd order Neumann condition at $r = 0$.Can I make a small tweek to make this work, is it numeric or do I need a new algorithm?My geometry is parallel plates with sharp points at $r = 0$ on both plates.My boundary conditions are$$\left. \frac{\partial V}{\partial r} \right|_{r=0} = 0$$Although I would like my second radial BC to be$$\left. \frac{\partial V}{\partial r} \right|_{r=\infty} = 0$$I settled for$$\left. \frac{\partial V}{\partial r} \right|_{r=a} = 0$$Then Dirichlet conditions at the upper and lower boundaries$$V(r, L(r) ) = V_0$$$$V(r, U(r) ) = V_L$$where$$L(r) = \begin{cases} & 0 \text{ if } r \geq R_L \\ & H_L (1 - \frac{r}{R_L} ) \text{ if } r \leq R_L \end{cases}$$and $$U(r) = \begin{cases} & H \text{ if } r \geq R_U \\ & H + H_U (\frac{r}{R_U} - 1 ) \text{ if } r \leq R_U \end{cases}$$ | Jacobi method converging then diverging | pde;algorithms;finite difference;numerics;boundary conditions | null |
_unix.25451 | I am using MySQL v5.1 on Ubuntu machine.I have a database named db_test which contain tables like cars, customers, departments, prices , and so on.I know I can use the following commands to dump out the db_test database and dump the database back into a new database in following way:mysqldump -u username -p -v db_test > db_test.sqlmysqladmin -u username -p create new_databasemysql -u username -p new_database < db_test.sqlBut for my new_database , I only needs some tables from db_test database, not all the tables. So, How can I dump out some tables from db_test database and dump these tables back to my new_database ? | dump out some tables of the database | linux;mysql;database | You'll find what you need directly in the mysqldump documentation:mysqldump -u username -p db_test table1 table2 ... > db_test.sqlLoad the dump the same way as if it was a full database dump. |
_webapps.11457 | Is it possible to rotate (90 degrees) already uploaded video's on YouTube? | Can I rotate already uploaded video's on YouTube? | youtube;video editing | YouTube's video editing has changed from how it was back in 2011 when this answer was first posted. You can now rotate your videos by going to the Video Manager page and choosing the Enhancements option from the Edit menu next to your uploaded video. You can also get there by clicking the Enhancements option below the player when viewing your video: On the enhancements page, the rotate options are on the bottom, next to the Trim button: |
_softwareengineering.228686 | I work on a lot of projects for fun, so I have the freedom to choose when I want to finish the project and am not constrained by deadlines.Therefore, if I wanted to, I could follow this philosophy:Whenever you hit a bug, don't debug. Instead, spend time learning about topics related to the bug from textbooks and work on other projects until one day you can come back to the bug and solve it instantly thanks to your piled up knowledge.However, maybe the 'philosophy' is bad because debugging is a skill that should be practiced so that when I need to finish projects by a deadline I will have acquired the skills necessary to debug quickly.staring at lines of code and struggling to understand them when debugging makes you a much better programmer than writing new lines of code does.debugging isn't a waste of time for some reason which I hope you'll tell me. | Is debugging a waste of time? | debugging;personal projects | Whenever you hit a bug, don't debug. Instead, spend time learning about topics related to the bug from textbooks and work on other projects until one day you can come back to the bug and solve it instantly thanks to your piled up knowledge.You make the false assumption that people write bugs because of lack of knowledge. A lot of bugs are mistakes, and making false assumptions. And actually the debugging in itself is a learning experience which will develop you as programmer.Yes, debugging is usefull because of:3: you would never deliver a working product if you didn't. |
_unix.199236 | My Bash script:declare -a lang=('english' 'spainsh')sms=Free msg: Due to upgrades on apps youll need a new version by yyyy/mm/dd to app running. Visit a store or go to url=google.com/UA2392 to upgrade your app. awk '{print $1 , '${servicegrade[0]}' , '${lang[1]}' ,,, '$sms' , '$url'}' inputfile.csv > inputfile.txtERROR:awk: cmd. line:1: {print $1 , 267 , en ,,, Freeawk: cmd. line:1: ^ unexpected newline or end of string | AWK is throwing an error unexpected newline or end of string | bash;awk | The problem you are seeing is directly related to the way that you are quoting (or more accurately, not quoting) your awk command line and the interpolated shell variables. (Both for the shell and for awk.)You have this:awk '{print $1 , '${servicegrade[0]}' , '${lang[1]}' ,,, '$sms' , '$url'}' inputfile.csv > inputfile.txtEmpirically I can see from the error message that servicegrade=267, lang=en, sms=Free msg:..., but url is not visible (that's ok) so we'll assume url=http://example.net.The important part is to look at your quotes on the commnd line. Anything inside the 'single quotes' is treated as a single command line. If you abut a single quote against a double quote you're also ok (echo 'hello'world has a single argument). But as soon as you introduce an unquoted space it becomes a second parameter (echo 'hello' world is two words, not one). Additionally, none of your variables is quoted so any whitespace in their values will be treated by the shell as a word break.Let's assume those variables do not contain whitespace, and interpolate them into the command line, as if they were actual values rather than variables:awk '{print $1 , '267' , 'en' ,,, 'Free msg:...' , 'http://example.net'}' inputfile.csv > inputfile.txtNow we'll remove redundant quotes:awk '{print $1 , 267 , en ,,, Free msg:..., http://example.net}' inputfile.csv > inputfile.txtIt shouldn't take more than a moment to realise that awk is now seeing unquoted strings, which it cannot view as awk variables. I suspect that what you really wanted was this:awk '{print $1 ,267,en,,,Free msg:...,http://example.net}' inputfile.csv > inputfile.txt(possibly with double-quoted arguments if your output is also CSV style).We can reverse the process easily enough to allow shell variables to be interpolated, but a better approach is to assign those shell variables to awk variables and use those:awk '{print $1 , servicegrade , lang ,,, sms , url}' servicegrade=${servicegrade[0]} lang=${lang[1]} sms=$sms url=$url inputfile.csv > inputfile.txtIf you decide your output text needs double-quoted parameters, awk (well, at least my version of it) understands this sort of structure: awk '{print $1 \ servicegrade \,\ lang \,\ sms \,\ url \}' |
_cstheory.36257 | Classically, it's very easy to create an incrementing function that can perform up to $n$ increments with $O(n)$ work:class Counter: def __init__(self): self.bits = [] def increment(self): for i in range(len(self.bits)): self.bits[i] = !self.bits[i] if self.bits[i]: return # SHORT CIRCUIT self.bits.append(True)Although any given increment may take $O(n)$ work individually, it must also create a situation where the following increments are cheap due to short-circuiting.When working with qubits, the above approach doesn't work. The short-circuiting test would require a measurement, and various parts of the superposition would have to short-circuit at different times.With that in mind, consider the following circuit. It keeps applying some unspecified and possibly varying operation to a qubit then doing a conditional increment:Each increment here is being done naively, so each of the $n$ increments requires $O(\lg n)$ gates and the overall circuit has $O(n \lg n)$ cost. Even though, within each component of the superposition, most of that work is wasted on most increments. Classically we would only need $O(n)$ gates total.Is there some way to optimize the circuit down to $O(n)$ gates, without depending on the details of $U$?My initial idea for this problem was to store all the controlled outcomes separately, then merge them pairwise until they were all in a single counter. That would be $O(n)$ aggregate work as desired. But for it to work identically to the original circuit you need to uncompute all the sub-counters used during merging, and the uncomputing doesn't seem to work when the counted values don't commute (e.g. if $U = H$). | Non-commutative quantum counting with aggregate constant work per increment | quantum computing | null |
_codereview.141603 | The code below is my solution in python 3 to exercise 1.5 in Cracking the Coding Interview. I would appreciate feedback on both the algorithm (improvements to space and time complexity) and/or coding style. I think the time and space complexity of the code below is \$O(n^{2})\$ and \$O(n)\$ respectively. The exercise statement is as follows:Given 2 Strings write a function to check if they are 1 edit away. There are three type of edits1) Insert a character2) Remove a character3) Replace a characterI wrote the code in Python 3.5 and confirmed that it passed a small unit test. For this problem I am particularly interested in feedback on where in my code (if at all) I should include more comments.import unittestdef is_one_away(first: str, other: str) -> bool: Given two strings, check if they are one edit away. An edit can be any one of the following. 1) Inserting a character 2) Removing a character 3) Replacing a character if len(first) < len(other): first, other = other, first if len(first) - len(other) > 1: return False elif len(first) - len(other) == 1: for pos in range(len(first)): if first[:pos] + first[pos+1:] == other: return True return False else: num_different_chars = sum(1 for pos in range(len(first)) if first[pos] != other[pos]) return num_different_chars < 2class MyTest(unittest.TestCase): def test_is_one_away(self): self.assertEqual(is_one_away('pale', 'ale'), True) self.assertEqual(is_one_away('pales', 'pale'), True) self.assertEqual(is_one_away('pale', 'bale'), True) self.assertEqual(is_one_away('pale', 'bake'), False) self.assertEqual(is_one_away('ale', 'pale'), True) self.assertEqual(is_one_away('aale', 'ale'), True) self.assertEqual(is_one_away('aael', 'ale'), False) self.assertEqual(is_one_away('motherinlaw', 'womanhitler'), False) self.assertEqual(is_one_away('motherinlaw','motherinlow'), True) | Check if two strings are one 'edit' apart using Python | python;strings;python 3.x;complexity;edit distance | All three cases are the same: you iterate over both string until there is a difference, you skip that difference and you check that the remaining of the strings are the same.The only difference being how you skip the difference: you can store that in a dictionnary to also help short circuit in cases the length difference is 2 or more:def is_one_away(first: str, other: str) -> bool: Given two strings, check if they are one edit away. An edit can be any one of the following. 1) Inserting a character 2) Removing a character 3) Replacing a character skip_difference = { -1: lambda i: (i, i+1), # Delete 1: lambda i: (i+1, i), # Add 0: lambda i: (i+1, i+1), # Modify } try: skip = skip_difference[len(first) - len(other)] except KeyError: return False # More than 2 letters of difference for i, (l1, l2) in enumerate(zip(first, other)): if l1 != l2: i -= 1 # Go back to the previous couple of identical letters break # At this point, either there was no differences and we exhausted one word # and `i` indicates the last common letter or we found a difference and # got back to the last common letter. Skip that common letter and handle # the difference properly. remain_first, remain_other = skip(i + 1) return first[remain_first:] == other[remain_other:] |
_unix.272580 | For a class on IT security, I want to demonstrate privilege escalation to the students. To do so, I looked through the exploit/linux/local list in the Metasploit Framework, finding (among others) exploit/linux/local/sock_sendpage from August 2009.I set up a VM with 32-bit Ubuntu Server 9.04 (http://old-releases.ubuntu.com/releases/9.04/ubuntu-9.04-server-amd64.iso) from April 2009. uname -r gives me 2.6.28-11-generic. According to the exploit's descriptionAll Linux 2.4/2.6 versions since May 2001 are believed to be affected: 2.4.4 up to and including 2.4.37.4; 2.6.0 up to and including 2.6.30.4So it seems that the Ubuntu server that I set up should be suitable for demonstration. However, I was not able to get it to work.I added a (regular) user on the server and SSH access works. From within the Metasploit Framework, I can create an SSH session using auxiliary/scanner/ssh/ssh_login. However, when I run the exploit, I get[*] Writing exploit executable to /tmp/mlcpzP6t (4069 bytes)[*] Exploit completed, but no session was created.I don't get any further information, not even when setting DEBUG_EXPLOIT to true. /tmp is writabe, also from within the Metasploit SSH session:$ sessions -c touch /tmp/test.txt[*] Running 'touch /tmp/test.txt' on shell session 1 ([redacted])$ sessions -c ls -l /tmp[*] Running 'ls -l /tmp' on shell session 1 ([redacted])total 0-rw-r--r-- 1 [redacted] [redacted] 0 2016-03-28 09:44 test.txtI also tried setting WriteableDir to the user's home directory on the server, but without any changes. What am I missing here? Is this version of Ubuntu server (that I have deliberately not updated!) not vulnerable? | Vulnerability demonstration on Ubuntu 9.04 | ubuntu;security;privileges;metasploit | The 9.04 release was supported until October 23 2010. The vulnerability you found was reported in August 2009. It seems reasonable that, since the release was still current and supported at the time, the ISO was patched and what you downloaded was a version that is no longer vulnerable. Furthermore, you seem to have demonstrated quite nicely that it isn't vulnerable. After all, you tried the exploit and it looks like it failed. Why don't you try a newer exploit? Something like CVE-2013-2094 which should also affect Ubuntu, for example. |
_cs.33069 | I need to equally distribute a variable number of spheres within a larger sphere (the volume of the spheres depends on how many there are). Are there any algorithms for doing this? An approximate solution would be acceptable.When searching, I was only able to find material about equally distributing points on the surface of a sphere, whereas I want to distribute the points within the volume of the sphere. | Equally distributed/packed spheres within a sphere | algorithms;packing | null |
_unix.346834 | The goal is to trigger an automatic alert when disk usage goes above a given threshold. So far I have only found the command df -hP /disk/path that returns disk usage. However, it returns lots of other information as well, as in the image below. I am looking for the most convenient way to retrieve the Use% statistic. Either through Regex or another Linux command.It is different from existing question in that it only deals with extracting the right value from the df command while the other questions deal with this part, plus sending the alert as well. The top answer given to this question which I accepted is the most elegant way I have seen to extract the right value. | Get disk usage as a shell variable | shell;disk usage | Try with this :df -hP /disk/path | awk '{print $5}' |tail -1|sed 's/%$//g' |
_softwareengineering.329944 | After reading this question Reasons NOT to use email for system integrationI want to ask the opposite question.What is email ingestion?When it is OK to use it for process or system integration? | What is email ingestion and are there modern uses for that technology? | email;email ingestion | Email ingestion is reading emails from an inbox and processing them.It is used to achieve a degree of automation between two companies, where neither company wants to go through the time and expense of publishing and consuming a first-class API like a REST service.It is suitable:When the communication is not critical, or can be retried (since email is not guaranteed delivery).When the communication is of a document-centric nature.When the chunk of data being sent is relatively large and the number of messages over time is relatively small.There's lots of things you can do with emails. You can put a chunk of JSON or XML in them for a machine to uptake. You can put a GUID in the email address that steers the email to a particular record in a database.You can extract the attachments and put them in a document system, etc.A simple example of such intake is used by Trello. You can send an email to Trello with a specifically-crafted email address, and it will create a new Trello card in the Trello Board you specify, containing the email body as the content of the Trello card. |
_reverseengineering.8804 | I am trying to retrieve text from another program. I used Ollydbg to find the address for the function I need to hook to get the info. I used EasyHook to inject the code below. The hook works fine until I call the original function. It crashes each time I do. I think it may have something to do with the return type of the function. Since I am new to reversing, I am having trouble determining the correct return type. I tried several different return types ranging from void to int. After the function returns, EAX points to a unicode string but the value isn't used. From what I read, EAX is where a returned variable would be stored.Update:I now see that this exception is occurring. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at ServerDLL.Injector.DoSomeThingDelegate.Invoke(Int32 argument1, Int32 argument2) at ServerDLL.Injector.DoSomeThing(Int32 argument1, Int32 argument2)Calling the function:Address Hex dump Command Comments00425373 |. 894424 04 MOV DWORD PTR SS:[ESP+4],EAX ; /Arg200425377 |. 8B45 A8 MOV EAX,DWORD PTR SS:[EBP-58] ; |0042537A |. 890424 MOV DWORD PTR SS:[ESP],EAX ; |Arg10042537D |. E8 8EC3FFFF CALL DoSomething;00425382 |. 8B4D 8C MOV ECX,DWORD PTR SS:[EBP-74]00425385 |. 8B45 A8 MOV EAX,DWORD PTR SS:[EBP-58]static string DoSomeThing(int argument1, int argument2){ Log.WriteLine(argument1); Log.WriteLine(argument2); DoSomeThingDelegate del = Marshal.GetDelegateForFunctionPointer(new IntPtr(0x421810), typeof(DoSomeThingDelegate)) as DoSomeThingDelegate; if (del == null) return ; return del(seatnumber, stack); }[UnmanagedFunctionPointer(CallingConvention.Cdecl, SetLastError = true, CharSet = CharSet.Auto)]delegate string DoSomeThingDelegate(int argument1, int argument2);public void Run(RemoteHooking.IContext InContext, String InArg1){ CreateRecvHook = LocalHook.Create(new IntPtr(0x421810), new DoSomeThingDelegate(DoSomeThing), this); CreateRecvHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });} | Why does calling the original function from my hook fail? | assembly;ollydbg;c#;injection | null |
_codereview.138592 | I'm a teacher and I built a one-page web app to display random question sets for quizzes and tests. The script I wrote selects one question from a set (array) of questions. The script works fine, but I wonder if it follows best practices or if it could be made more efficient. I want to share my app with other teachers, but I don't want to spread bad practices.Here's a fiddle of the app itself.Clicking anywhere on the page brings up a spinner. Clicking again brings up five new random questions. There is more JS in the app, but I'm mainly concerned about the JS related to the question randomization.// change questions here -- in quotes, comma separatedvar qset1 = new Array(Set 1 Question 1,Set 1 Question 2,Set 1 Question 3,Set 1 Question 4,Set 1 Question 5);var qset2 = new Array(Set 2 Question 1,Set 2 Question 2,Set 2 Question 3,Set 2 Question 4,Set 2 Question 5);var qset3 = new Array(Set 3 Question 1,Set 3 Question 2,Set 3 Question 3,Set 3 Question 4,Set 3 Question 5);var qset4 = new Array(Set 4 Question 1,Set 4 Question 2,Set 4 Question 4,Set 4 Question 4,Set 4 Question 5);var qset5 = new Array(Set 5 Question 1,Set 5 Question 2,Set 5 Question 5,Set 5 Question 4,Set 5 Question 5);function setUP() {var set1=Math.floor(Math.random()*qset1.length);var set2=Math.floor(Math.random()*qset2.length);var set3=Math.floor(Math.random()*qset3.length);var set4=Math.floor(Math.random()*qset4.length);var set5=Math.floor(Math.random()*qset5.length);document.getElementById('set_1').innerHTML = qset1[set1];document.getElementById('set_2').innerHTML = qset2[set2];document.getElementById('set_3').innerHTML = qset3[set3];document.getElementById('set_4').innerHTML = qset4[set4];document.getElementById('set_5').innerHTML = qset5[set5];} | Displaying random elements for a quiz app | javascript;beginner;random;quiz | I assume your sets won't actually look like that, and that was just for the sake of this example. Right now you're doing the same operation on a bunch of virtually identical things - this is exactly the use case for a for-loop.First we need to put all of our questions into an array of arrays, and then we can loop over them and do whatever we want. I made a few other changes as well - by using the nth-child() selector I don't have to have the ids - you can switch between the two methods by changing which lines are commented out. You can run this code snippet and see how it works down below.function populateQuestions() { var questionSets = [ [Set 1 Question 1, Set 1 Question 2, Set 1 Question 3, Set 1 Question 4, Set 1 Question 5], [Set 2 Question 1, Set 2 Question 2, Set 2 Question 3, Set 2 Question 4, Set 2 Question 5], [Set 3 Question 1, Set 3 Question 2, Set 3 Question 3, Set 3 Question 4, Set 3 Question 5], [Set 4 Question 1, Set 4 Question 2, Set 4 Question 4, Set 4 Question 4, Set 4 Question 5], [Set 5 Question 1, Set 5 Question 2, Set 5 Question 5, Set 5 Question 4, Set 5 Question 5] ]; for (var setIndex = 0; setIndex < questionSets.length; ++setIndex) { var questionSet = questionSets[setIndex]; var questionIndex = Math.floor(Math.random() * questionSet.length); var question = questionSet[questionIndex]; var selector = '#questions li:nth-child(' + (setIndex + 1).toString() + ')'; //var setId = 'set_' + (setIndex + 1).toString(); document.querySelector(selector).innerHTML = question; //document.getElementById(setId).innerHTML = question; }}<ul id=questions> <li id=set_1>First question</li> <li id=set_2>Second question</li> <li id=set_3>Third question</li> <li id=set_4>Fourth question</li> <li id=set_5>Fifth question</li></ul><button type=button onclick=populateQuestions()>Populate the questions!</button>I do have one potential concern - right now you're still presenting the sets in the same order, but you might want to randomize what order the sets appear in. I'll leave that as an exercise to the reader, but it isn't much more complicated than this. You might also want to not present questions that have already been seen before, which is a little tricky. You either want to remove them from the sets once they've been used, or have an object to keep track of ones that have already been used.Lastly, it might be worthwhile to write a function like getQuestions that looks like thisfunction getQuestions(callback) { // do something to get the questions var questions = ...; // once the questions are ready, use the callback callback(questions);}function populateQuestions(questionSets) { // same code, minus the creation of questionSets}getQuestions(populateQuestions);We use the callback so this can become an asynchronous method - if you ever wanted to get this data via AJAX, or a web-service, or database, or wherever, it becomes much easier to integrate that into your workflow. |
_softwareengineering.267657 | So far I have only done personal projects at home. I hope to get involved in some open source project some time next year. The languages I that have been using the most are C and C++. I have used both languages for over a year and I feel like I have become quite proficient with both of them, but I really don't know which one I like better.I personally like C because I think it is simple and elegant. To me C++ seems bloated many unnecessary features that just complicates the design process. Another reason to why I like to use plain C is because it seems to be more popular in the free and open-source software world.The feature that I miss the most from C++ when I use plain C is probably the std::vector from STL (Standard Template Library).I still haven't figured out how I should represent growing arrays in C. Up to this point I duplicated my memory allocation code all over the place in my projects. I do not like code duplication and I know that it is bad practice so this does not seems like a very good solution to me.I thought about this problem yesterday and came up with the idea to implement a generic vector using preprocessor macros.It looks like this:int main(){ VECTOR_OF(int) int_vec; VECTOR_OF(double) dbl_vec; int i; VECTOR_INIT(int_vec); VECTOR_INIT(dbl_vec); for (i = 0; i < 100000000; ++i) { VECTOR_PUSH_BACK(int_vec, i); VECTOR_PUSH_BACK(dbl_vec, i); } for (i = 0; i < 100; ++i) { printf(int_vec[%d] = %d\n, i, VECTOR_AT(int_vec, i)); printf(dbl_vec[%d] = %f\n, i, VECTOR_AT(dbl_vec, i)); } VECTOR_FREE(int_vec); VECTOR_FREE(dbl_vec); return 0;}It uses the same allocation rules as std::vector (the size starts as 1 and then doubles each time that is required). To my surprise I found out that this code runs more than twice as fast as the same code written using std::vector and generates a smaller executable! (compiled with GCC and G++ using -O3 in both cases).My question is:Would you recommend using this in a serious project?If not then I would like you to explain why and what a better alternative would be. | Using macros to implement a generic vector (dynamic array) in C. Is this a good idea? | c;data structures;generics;macros;generic programming | My question is: Would you recommend using this in a serious project?Yes! Here is something that is mostly true about library functions: they necessarily have to be generally applicable in order to accommodate many users with different requirements. If you know the underlying algorithm, the library function is going to be larger and slower than your own implementation. Most of the time we don't care, because size and speed aren't an issue. However once speed does become an issue and the bottleneck is the library function (very often with library sorting algorithms), simply understanding the algorithm and writing something that works for you can result in dramatic speed improvements. I understand you discovered this in another way (reproducing a feature from std::vector in C) and aren't asking an optimization question. But it's worth mentioning that what you've learned will come in very handy in the future when working in Java, C++, etc. and you run into a speed bottleneck that crushes your project. This can happen often in computationally-intensive projects. |
_vi.12892 | So I'm trying to use Vim-Hybrid as my native Vim theme but I've been running into a couple issues with it. Everytime I run the vim command now, I've been receiving the following error message:E488: Trailing characters: </tr>line 2194:E488: Trailing characters: <tr>line 2195:There's a lot more trailing character errors that are firing but I believe that there might be an error with my ~/.vim/colors/hybrid.vim - which I copied and pasted from the repo into the the respective path.Here's the content within my .vimrc: I followed the installation instructions, which told me to:Add to ~/.vimrc:set background=darkcolorscheme hybridFurther down in the instructions, I was also told to add the following:let g:hybrid_custom_term_colors = 1let g:hybrid_reduced_contrast = 1 Remove this line if using the default palette.colorscheme hybridMy .vimrc currently looks like this now:let g:hybrid_custom_term_colors = 1let g:hybrid_reduced_contrast = 1set background=darkcolorscheme hybridAny idea what went wrong? Any help would be appreciated!Ninja Edit: Forgot to mention that I'm using iTerm! | E488: Trailing Characters error after attempting to install vim-hybrid | vimrc;colorscheme;macvim;iterm2 | You apparently copy and pasted some html code into your colorscheme file. If you open the file in github, click on the RAW link and copy paste again and make sure to overwrite the previous version. (Even better would be to simply download that file using wget or similar) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.