qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
20,709,711
I have a play application that needs to upload files to S3. We are developing in scala and using the Java AWS SDK. I'm having trouble trying to upload files, I keep getting 403 SignatureDoesNotMatch when using presigned urls. The url is being genereated using AWS Java SDK by the following code: ``` def generatePresignedPutRequest(filename: String) = { val expiration = new java.util.Date(); var msec = expiration.getTime() + 1000 * 60 * 60; // Add 1 hour. expiration.setTime(msec); s3 match { case Some(s3) => s3.generatePresignedUrl(bucketname, filename, expiration, HttpMethod.PUT).toString case None => { Logger.warn("S3 is not availiable. Cannot generate PUT request.") "URL not availiable" } } } ``` For the frontend code we followed [ioncannon article](http://www.ioncannon.net/programming/1539/direct-browser-uploading-amazon-s3-cors-fileapi-xhr2-and-signed-puts/). The js function that uploads the file (the same as the one used in the article) ``` function uploadToS3(file, url) { var xhr = createCORSRequest('PUT', url); if (!xhr) { setProgress(0, 'CORS not supported'); } else { xhr.onload = function() { if(xhr.status == 200) { setProgress(100, 'Upload completed.'); } else { setProgress(0, 'Upload error: ' + xhr.status); } }; xhr.onerror = function() { setProgress(0, 'XHR error.'); }; xhr.upload.onprogress = function(e) { if (e.lengthComputable) { var percentLoaded = Math.round((e.loaded / e.total) * 100); setProgress(percentLoaded, percentLoaded == 100 ? 'Finalizing.' : 'Uploading.'); } }; xhr.setRequestHeader('Content-Type', 'image/png'); xhr.setRequestHeader('x-amz-acl', 'authenticated-read'); xhr.send(file); } } ``` The server's response is ``` <?xml version="1.0" encoding="UTF-8"?> <Error><Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <StringToSignBytes>50 55 bla bla bla...</StringToSignBytes> <RequestId>F7A8F1659DE5909C</RequestId> <HostId>q+r+2T5K6mWHLKTZw0R9/jm22LyIfZFBTY8GEDznfmJwRxvaVJwPiu/hzUfuJWbW</HostId> <StringToSign>PUT image/png 1387565829 x-amz-acl:authenticated-read /mybucketname/icons/f5430c16-32da-4315-837f-39a6cf9f47a1</StringToSign> <AWSAccessKeyId>myaccesskey</AWSAccessKeyId></Error> ``` I have configured CORS, double checked aws credentials and tried changing request headers. I always get the same result. Why is Amazon telling me that signatures dont match?
2013/12/20
[ "https://Stackoverflow.com/questions/20709711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694832/" ]
I just encountered this problem using the NodeJs AWS SDK. It was due to using credentials that were valid, *but without sufficient permissions.* Changing to my admin key fixed this with no code changes!
If your access keys and secret keys are good but it is saying "SignatureDoesNotMAtch", check your secret key, it probably has any of some special charaters, e.g +/ - / \* Go to aws and generate another access key, where the the secret key does not have those. Then try again :)
9,935
A big part of my daily job is developing software for use on machines with different versions of the same software, like `bash`, `find`, and `grep`. When encountering a feature which would be useful for example to simplify code, it is important to know whether this feature is available in the oldest installed tools. For critical stuff, it would also be useful to know whether this feature was new or has existed for years in the oldest installed tools. What are quick ways to answer this **authoritatively** for Linux tools, especially the GNU Core Utils? Some possibilities in order of decreasing accuracy: * **Binary binary search** (sic) by running the different versions is of course the ultimate answer, but is by far the most time consuming. Older installations are often not available for security reasons. * **Reading the code** is almost as good, but it can be prohibitively time consuming if the feature is vaguely named, the name doesn't correspond directly to variable/function/object names, or it was implemented before it was enabled. * **Change logs**, when available, usually connect feature changes to software versions. * **Commit logs** can provide hints, but do not know which version they will be included in. * **man pages** rarely mention dates. * The same applies to **Googling**, and you'd also have a hard time excluding all the non-authoritative sources.
2011/03/23
[ "https://unix.stackexchange.com/questions/9935", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/3645/" ]
On **Debian** and Debian-derived platforms such as **Ubuntu**: ``` sudo apt-get changelog coreutils > changelog.txt ``` provides the GNU Core Utilities' changelog all the way back to version `4.5.1-1`. Not sure if there are similarly convenient solutions on other platforms.
Check the [coreutils NEWS](http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob_plain;f=NEWS;hb=HEAD) file from its [git repo](http://git.savannah.gnu.org/gitweb/?p=coreutils.git).
18,125,785
so i have a string that can look like this: ``` UPDATE 12.7543.81 ParmA="dk.asterix.org" [Denmark] (9.1) ParmB="de.asterix.org" [Germany] (1.0) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA) Internal=0 State=2 UPDATE 12.7543.81 ParmB="de.asterix.org" [Germany] (1.0) ParmA="dk.asterix.org" [Denmark] (9.1) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA) Internal=0 State=2 UPDATE 12.7543.81 Internal=0 State=2 ParmB="de.asterix.org" [Germany] (1.0) ParmA="dk.asterix.org" [Denmark] (9.1) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA) UPDATE 12.7543.81 Internal=0 State=2 ParmB="de.asterix.org" [Germany] (1.0) Calling=45xxxxxxxx (LOA) ParmA="dk.asterix.org" [Denmark] (9.1) Called=49xxxxxxx (GBH) ``` all compleetly randomly added to the list, however they still follow 1 specific chunk pattern: ``` xxx = String ddd = decimal iii = integer chunk 1: UPDATE chunk 2: xxx.xxx.xxx chunk x: ParmA="xxx" [xxx] (ddd) chunk x: ParmB="xxx" [xxx] (ddd) chunk x: Calling=xxx (xxx) chunk x: Called=xxx (xxx) chunk x: Internal=iii chunk x: State=iii ``` i wanted to extract all the string data into variables, however a regex don't like a random order, so i was thinking of using split(" "), and cykle trough each Word. but i Thord before i started doing that, i could ask if there was another way to extract the data? idea to seperate chunks example: ``` import java.util.ArrayList; import java.util.List; public class Test { final static String[] lines = new String[]{ "UPDATE 12.7543.81 ParmA=\"dk.asterix.org\" [Denmark] (9.1) ParmB=\"de.asterix.org\" [Germany] (1.0) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA) Internal=0 State=2", "UPDATE 12.7543.81 ParmB=\"de.asterix.org\" [Germany] (1.0) ParmA=\"dk.asterix.org\" [Denmark] (9.1) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA) Internal=0 State=2", "UPDATE 12.7543.81 Internal=0 State=2 ParmB=\"de.asterix.org\" [Germany] (1.0) ParmA=\"dk.asterix.org\" [Denmark] (9.1) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA)", "UPDATE 12.7543.81 Internal=0 State=2 ParmB=\"de.asterix.org\" [Germany] (1.0) Calling=45xxxxxxxx (LOA) ParmA=\"dk.asterix.org\" [Denmark] (9.1) Called=49xxxxxxx (GBH)" }; public static void main(String[] args){ for(String line : lines){ String[] parms = splitParm(line); for(String parm : parms){ System.out.println(parm); } } } static public String[] splitParm(String text){ String[] textarr = text.split(" "); List<String> parms = new ArrayList<>(); parms.add(textarr[0]); // UPDATE parms.add(textarr[1]); // 12.7543.81 for(int i = 2;i<textarr.length;i++){ if(textarr[i].matches("^([A-Za-z]+)=([\\S ]+)$")){ parms.add(textarr[i]); } else{ parms.set(parms.size()-1, parms.get(parms.size()-1) + " "+textarr[i]); } } return parms.toArray(new String[]{}); } } ```
2013/08/08
[ "https://Stackoverflow.com/questions/18125785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490998/" ]
Following code should work: ``` String s = "UPDATE 12.7543.81 ParmA=\"dk.asterix.org\" [Denmark] (9.1) ParmB=\"de.asterix.org\" [Germany] (1.0) Called=49xxxxxxx (GBH) Calling=45xxxxxxxx (LOA) Internal=0 State=2"; Pattern p = Pattern.compile("([^\\s]+)\\s+([^\\s]+)\\s+"); Pattern p1 = Pattern.compile("([^\\s]+)\\s*=\\s*\"?([^\\s\"]+)\"?"); Matcher m = p.matcher(s); if (m.find() && m.groupCount() == 2) { System.out.printf("%s%n%s%n", m.group(1), m.group(2) ); Matcher m1 = p1.matcher(s.substring(m.end(2))); while (m1.find()) { System.out.printf("\t%s=%s%n", m1.group(1), m1.group(2) ); } } ``` **OUTPUT:** ``` UPDATE 12.7543.81 ParmA=dk.asterix.org ParmB=de.asterix.org Called=49xxxxxxx Calling=45xxxxxxxx Internal=0 State=2 ```
Don't use regex for this. You'll get far more maintainable code just by splitting and looping.
12,234,545
How do I maintain the $post value when a page is refreshed; In other words how do I refresh the page without losing the Post value
2012/09/02
[ "https://Stackoverflow.com/questions/12234545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218638/" ]
You can't do this. POST variables may not be re-sent, if they are, the browser usually does this when the user refreshes the page. The POST variable will never be re-set if the user clicks a link to another page instead of refreshing. If `$post` is a normal variable, then it will never be saved. If you need to save something, you need to use cookies. `$_SESSION` is an implementation of cookies. Cookies are data that is stored on the user's browser, and are re-sent with every request. Reference: <http://php.net/manual/en/reserved.variables.session.php> The $\_SESSION variable is just an associative array, so to use it, simply do something like: ``` $_SESSION['foo'] = $bar ```
You can use the same value that you got in the `POST` inside the form, this way, when you submit it - it'll stay there. An little example: ``` <?php $var = mysql_real_escape_string($_POST['var']); ?> <form id="1" name="1" action="/" method="post"> <input type="text" value="<?php print $var;?>"/> <input type="submit" value="Submit" /> </form> ```
48,180,098
It's my understanding that the default behavior of Rails, when storing a session e.g. `session[:id] = 1`, is that it will save the id to a cookie, which will expire when the user closes the browser window. However, in my app, when I close (exit out) the browser and restart it, the browser still 'remembers' me as being logged in. Here is my controller code: ``` class SessionsController < ApplicationController def new end def create user = User.find_by(email: params[:email]) if user && user.authenticate(params[:password]) log_in user redirect_to user else flash.now[:notice] = "Invald email / password combination" render 'new' end end def destroy end end ``` and my helper file: ``` module SessionsHelper def log_in(user) session[:user_id] = user.id end def current_user @current_user ||= User.find_by(id: session[:user_id]) end def logged_in? !current_user.nil? end def user_name @current_user.first_name ? (@current_user.first_name + " ") : nil end end ``` I have nothing in the application controller nor did I ever mess with the initializers or config files regarding the session. What could be causing my session to persist and not expire the cookie?
2018/01/10
[ "https://Stackoverflow.com/questions/48180098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217750/" ]
You can use user defined function such as ``` def isprime(n): if n < 2: return False for i in range(2,(n**0.5)+1): if n % i == 0: return False return True ``` it will return boolean values. You can use this function for verifying prime factors. OR you can continuously divide the number by 2 first ``` n = 600851475143 while n % 2 == 0: print(2), n = n / 2 ``` n has to be odd now skip 2 in for loop, then print every divisor ``` for i in range(3,n**0.5+1,2): while n % i== 0: print(i) n = n / i ``` at this point, n will be equal to 1 UNLESS n is a prime. So ``` if n > 1: print(n) ``` to print itself as the prime factor. Have fun exploring
First calculate the sqrt of your number as you've done. ``` number = 600851475143 number_sqrt = (number**0.5)+1 ``` Then in your outermost loop only search for the prime numbers with a value less than the sqrt root of your number. You will not need any prime number greater than that. (You can infer any greater based on your list). ``` for x in range(2, number_sqrt+1): ``` To infer the greatest factor just divide your number by the items in the factor list including any combinations between them and determine if the resultant is or is not a prime. No need to recalculate your list of prime numbers. But do define a function for determining if a number is prime or not. I hope I was clear. Good Luck. Very interesting question.
1,590,491
Evaluate $\int \sin^{13}x\,dx$. My solution so far: $$\int\sin^{13}x\,dx=\int\sin x\sin^{12}x\,dx=\int\sin x(\sin^{2}x)^6\,dx$$ Let $t=\cos x$, then $dt=-\sin x\,dx$. Now we have: $$\int\sin^{13}x\,dx=-\int(1-t^2)^6,\ dt$$. How do I proceed from here? I need detailed answer.
2015/12/27
[ "https://math.stackexchange.com/questions/1590491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/271941/" ]
An alternative approach is given by De Moivre's formula and the binomial theorem. Since $$\begin{eqnarray\*} \sin^{13}(x) &=& -\frac{i}{2^{13}}\left(e^{ix}-e^{-ix}\right)^{13}\\&=&-\frac{i}{2^{13}}\left(2i\sin(13x)-26i\sin(11 x)+156i\sin(9x)-572i\sin(7x)+1430i\sin(5x)-2574i\sin(3x)+3432i\sin(x)\right)\end{eqnarray\*}$$ we have: > > $$ \int \sin^{13}(x)\,dx = C-\frac{429 \cos(x)}{1024}+\frac{429\cos(3x)}{4096}-\frac{143\cos(5x)}{4096}+\frac{143\cos(7x)}{14336}-\frac{13\cos(9x)}{6144}+\frac{13\cos(11x)}{45056}-\frac{\cos(13x)}{53248}.$$ > > >
Apply Integral Reduction:$$\quad \int \:\sin ^n\left(x\right)dx=-\frac{\cos \left(x\right)\sin ^{n-1}\left(x\right)}{n}+\frac{n-1}{n}\int \sin ^{n-2}\left(x\right)dx$$ $$\color{red}{\int \sin ^{13}\left(x\right)dx=-\frac{\cos \left(x\right)\sin ^{12}\left(x\right)}{13}+\frac{12}{13}\int \sin ^{11}\left(x\right)dx}$$
21,869,969
``` class SuperClass{ static int x = 15; public void setX(int x){ this.x = x; } public int getX(){ System.out.println(x); return x; } } public class StaticVariableExample { /** * @param args */ public static void main(String[] args) { SuperClass sc1= new SuperClass(); sc1.setX(3); SuperClass sc2= new SuperClass(); sc2.setX(4); SuperClass sc3= new SuperClass(); sc3.setX(5); // since X is static variable Each instance of class calling add() and all instances will have same value even // assigned different values 3 4 5 sc1.getX(); sc2.getX(); sc3.getX(); } } ``` X is static variable. Calling setX() doesn't give neither compilation nor runtime. It is behaving similar to normal variable Set(). Can u please explain why x setX() is working?
2014/02/19
[ "https://Stackoverflow.com/questions/21869969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3326121/" ]
Static members (variables and methods ) are allowed to be accessed by objects. `this` refers to the current object and hence using current object reference, java allows to access static variable.
Well, it's working specifically because the static field isn't `final`. If it were, then you couldn't assign anything to it again once it had been already assigned (as evidenced by `setX()`). `this` always refers to the current object - and since `x` is in the current object, `this` knows where to reference it.
22,196,141
I have a string coming in as ``` FirstName LastLast (WorkerId) ``` so for example: ``` "Joe Thompson (234DerX)" ``` and i want to parse this out into this person object ``` class Person { public string Name; //Joe Thompson public string WorkerId; //234DerX } ``` what is the best way to parse out both the worker Id and the Name. Regex? something simpler. Some names have middles names or multiple first names so the only thing i can rely on is that the worker id is surrounded by "(" + ")"
2014/03/05
[ "https://Stackoverflow.com/questions/22196141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
If you use regex, the following regex should do what you want: ``` @" *(?<name>.*) \((?<id>.*)\)" ``` The `Name` is stored in capturing group `name` and `WorkerId` is stored in capturing group `id`. This assumes that worker ID is in the last pairs of parentheses. The solution should work even if the name contains parentheses for some reason (e.g. `John (The Third) (JK4532R)`). However, it won't be able to differentiate between a name and a worker ID if the worker ID is missing in the input and the name has something in parentheses at the end (e.g. `John (The Third)`)
If I understand correctly, then you can simply split the string on intervals, then take the last resulting string, trim it from brackets front and back and you will have the id. As for the name, since you do not know exactly how many names there are, it will be harder if you want to put only some of them in the string. If you just need the first of the first names and the last of the last names then just take the first and the second-to-last string in the array resulting from the split. Something like this: ``` var splitArray = "Joe Thompson (234DerX)".Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); var id = splitArray.Last().Trim(new char['(',')']); var name = splitArray[0] + " " + splitArray[splitArray.Length - 2]; var person = new Person(); person.Id = id; person.Name = name; ```
30,959,141
The Android app I'm working on has a single MainActivity and each screen of the app is implemented as a Fragment. Each fragment is instantiated like this in the MainActivity as a private class variable: ``` public class MainActivity extends Activity implements MainStateListener { private FragmentManager fm = getFragmentManager(); private BrowseFragment browseFragment = BrowseFragment.newInstance(); ... ``` There is a single 'fragment frame' that loads each screen fragment. When switching screens in the app this code is called to load a fragment: ``` FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.frag_frame, incoming); ft.addToBackStack(null); ft.commit(); fm.executePendingTransactions(); ``` Each screen fragment has a listener that enables the fragment to call various methods in the MainActivity: ``` public void onAttach(Activity activity) { super.onAttach(activity); try { mainStateListener = (MainStateListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement MainStateListener"); } } ``` The issue I am having is updating an aspect of a fragment from a Navigation Drawer that exits in the MainActivity. The navigation drawer has to update the fragment, and it uses this code to do that: ``` navigationDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { browseFragment.doSomethingOnBrowserFragment(); } }); ``` Things work fine when until you change the orientation. Then the current screen fragment loads fine (browseFragment). But then when you click the navigation drawer causing the doSomethingOnBrowserFragment() method to execute I get a null pointer exception due to the mainStateListener object itself (attached to in the browseFragment) being null. From what I know about the Fragment lifecycle this variable shouldn't be null because the onAttach() method executes first before anything and sets mainStateListener variable. Also if I have a button on that browserFragment that uses the mainStateListener object (following an orientation change), clicking the button never has this null pointer issue. Stack trace: ``` 08-04 16:23:28.937 14770-14770/co.openplanit.totago E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: co.openplanit.totago, PID: 14770 java.lang.NullPointerException at co.openplanit.totago.MapFragment.enableOfflineMode(MapFragment.java:489) at co.openplanit.totago.MainActivity.setMapMode(MainActivity.java:663) at co.openplanit.totago.MainActivity.itineraryMapDrawerSelectItem(MainActivity.java:610) at co.openplanit.totago.MainActivity.access$200(MainActivity.java:52) at co.openplanit.totago.MainActivity$5.onItemClick(MainActivity.java:420) at android.widget.AdapterView.performItemClick(AdapterView.java:299) at android.widget.AbsListView.performItemClick(AbsListView.java:1158) at android.widget.AbsListView$PerformClick.run(AbsListView.java:2957) at android.widget.AbsListView$3.run(AbsListView.java:3850) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5103) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606) at dalvik.system.NativeStart.main(Native Method) ``` It seems to me the issue may be that using the Navigation Drawer is actually interacting with the browseFragment lifecycle and causing it to detach or something. Any suggestions on how to resolve this would be much appreciated.
2015/06/20
[ "https://Stackoverflow.com/questions/30959141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381843/" ]
I notice you're basically caching fragments due to code of: ``` public class MainActivity extends Activity implements MainStateListener { private FragmentManager fm = getFragmentManager(); private BrowseFragment browseFragment = BrowseFragment.newInstance(); ``` But implementing this may be tricky. Either you create code/class that manages these fragments like using Array of fragments, or use class like `FragmentPagerAdapter`. If I may suggest, don't cache fragments since you have to understand its lifecycle, caching is a good idea only if the fragment's layout is complicated. Simply just create a new instance of it in your code `public void onItemClick()` like at Google's suggestion @ [Creating a Navigation Drawer](https://developer.android.com/training/implementing-navigation/nav-drawer.html), in case you did not read it. Code snippet in the webpage: ``` private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { // Create a new fragment and specify the planet to show based on position Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); fragment.setArguments(args); // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); ``` Note: A new instance of fragment is done with `new PlanetFragment()`.
What I think may be happening is that your activity's browseFragment may be different that the BrowseFragment that is being shown by the fragment manager (which seems to work fine as you said if you click a button in that fragment). On rotation, the activity will create a NEW BrowseFragment instance for your browseFragment variable (which is not attached to the activity) - *private BrowseFragment browseFragment = BrowseFragment.newInstance()* runs each time the activity is created, but the fragment manager will reuse the EXISTING BrowseFragment instance which your variable does NOT point to. The reused BrowseFragment will get attached and run that code to update the mainStateListener, the unused new browseFragment won't be attached to the activity unless you run through a fragmentTransaction that adds it - so the mainStateListener in it will be null (uninitialized). Instead of creating the fragment and storing it in a variable and then trying to access that variable after a rotation, you would be better off using a fragment tag and getting the fragment based on the tag from the fragment manager. i.e. ``` private static final String BROWSE_TAG = "browseFrag"; ft.replace(R.id.frag_frame, browseFragment, BROWSE_TAG); navigationDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Fragment browseFragment = fm.findFragmentByTag(BROWSE_TAG); if (browseFragment != null) { browseFragment.doSomethingOnBrowserFragment(); } } }); ```
9,923,062
I disabled the click event of image using unbind method. But I don't know how to recover the click event again. Here is the code, `<img src="testimg.jpg" id="sub_form">` disabled the click event of above image using the code ``` $('#sub_form').unbind('click'); ``` How do i recover the click event? I tried with the bind event ``` $('#sub_form').bind('click'); ``` but it wont work. Why I'm going for click event of image is ajax form submission. The code is, ``` $("#sub_form").click(function() { var input_data = $('#testform').serialize(); $.ajax({ //my code }); }); ``` how can i achieve this after unbind of image is performed.
2012/03/29
[ "https://Stackoverflow.com/questions/9923062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101208/" ]
If you saved the handler, you can just invoke it again: ``` var handler = function() { alert('click'); }; $('#sub_form').click(handler); // disabling: $('#sub_form').unbind('click', handler); // reenabling: $('#sub_form').click(handler); ``` If you don’t know what handlers that are bound, you can find and save them before unbinding: ``` // save the click handlers var events = $('#sub_form').data('events'), handlers = 'click' in events ? Array.prototype.slice.call(events.click) : [], handler = function() { $.each(handlers, function() { this.handler(); }); }; // disable $('#sub_form').unbind('click'); // reenable $('#sub_form').bind('click', handler);​ ``` <http://jsfiddle.net/sPPnE/>
You can specify a `function reference` when calling `.unbind()`: For instance: ``` function myHandler( event ) { } // bind the click handler $('#sub_form').bind('click', myHandler); // remove only this exact click handler $('#sub_form').unbind('click', myHandler); // bind it again $('#sub_form').bind('click', myHandler); ``` **Sidenote**: As for jQuery 1.7.x you should use the `.on()` and `.off()` equivalent methods. Reference: [`.on()`](http://api.jquery.com/on/), [`.off()`](http://api.jquery.com/off/), [`.bind()`](http://api.jquery.com/bind/), [`.unbind()`](http://api.jquery.com/unbind/)
1,659,296
Prove $\sqrt{60}$ is irrational. I'm trying to base this off a proof that $\sqrt{6}$ is irrational, which I found [here](http://mathcentral.uregina.ca/QQ/database/QQ.09.06/sylvia1.html). I followed the exact same steps and ended up with $c^2$ = $15b^2$. This was at the point where the example had $2c^2$ = $3b^2$, but the example was able to deduce that $3b^2$ is even, as it is equal to a number times $2$ which is always even, meaning $b^2$ itself has to be even because its coefficient is odd. And because $b^2$ is even, $b$ must be as well, which leads to the contradiction I'm trying to get to. With my example, I can't immediately say that $15b^2$ is even because there is not an even coefficient in front of $c^2$. I've been stumped from there.
2016/02/17
[ "https://math.stackexchange.com/questions/1659296", "https://math.stackexchange.com", "https://math.stackexchange.com/users/307092/" ]
$\sqrt{60}=2\sqrt{15}$, so we just need to prove $\sqrt 15$ is irrational. Suppose not; $\sqrt{15}=a/b$. Then $15b^2=a^2$. But the factor $3$ appears an odd number of times on the left and must appear an even number of times on the right (the same is true of $5$), so this equality is impossible.
Just a more tricky strategy using [Continued Fractions](https://en.wikipedia.org/wiki/Continued_fraction): it is not hard to show that a real number is rational iff it has a continued fraction representation which has all $0$'s starting from a certain point like this: $[a\_0;a\_1,\cdots a\_n,0,0,0,\cdots]$ with $a\_0 \geq 0$ integer and $a\_i > 0$ integers. In fact if you have this kind of CF it is trivially in $\mathbb Q$, the converse is given by the euclidean division in $\mathbb Z$ which eventually ends. Now compute $\sqrt {60}=[7;\overline{1,2,1,14}]$ for example with a calculator or by hands, this is periodic so it is not $0$ definitively. Morover, since it is periodic, it is a [quadratic irrational number](https://en.wikipedia.org/wiki/Periodic_continued_fraction), which is not a big surprise since it solves $x^2 - 60=0$.
34,197,669
I have no idea what I am doing. I thought I had everything going well with html, then I had to add some simple javascript. I am just trying to change the background color when the user clicks a button. This is what I have so far: CSS ``` body { background-color:grey; } ``` Javascript ``` function changeBackground() { if (document.body.style.backgroundColor = 'grey') { document.body.style.backgroundColor = 'black'; } else { document.body.style.backgroundColor = 'grey'; } } ``` Html ``` <button type="button" onclick="changeBackground()"> Click Me! </button> ```
2015/12/10
[ "https://Stackoverflow.com/questions/34197669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5663236/" ]
Your `if` clause is wrong (you are assigning instead of testing the background color): ``` function changeBackground() { if (document.body.style.backgroundColor == 'grey'){ document.body.style.backgroundColor = 'black'; } else { document.body.style.backgroundColor = 'grey'; } } ```
Try: ``` $("button").click(function(){ $("body").css("background-color", "blue"); }); ```
65,886,635
I'm new to NoSQL and I'm trying to figure out the best way to model my database. I'll be using ArangoDB in the project but I think this question also stands if using MongoDB. The database will store 12 categories of products. Each category is expected to hold hundreds or thousands of products. Products will also be added / removed constantly. There will be a number of common fields across all products, but each category will also have unique fields / different restrictions to data. Keep in mind that there are instances where I'd need to query all the categories at the same time, for example to search a product across all categories, and other instances where I'll only need to query one category. Should I create one single collection "Product" and use a field to indicate the category, or create a seperate collection for each category? I've read many questions related to this idea (1 collection vs many) but I haven't been able to reach a conclusion, other than "it dependes". So my question is: In this specific use case which option would be most optimal, multiple collections vs single collection + sharding, in terms of performance and speed ? Any help would be appreciated.
2021/01/25
[ "https://Stackoverflow.com/questions/65886635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14781777/" ]
As you mentioned, you need to play with your data and use-case. You will have better picture. Some decisions required as below. 1. Decide the number of documents you will have in near future. If you will have 1m documents in an year, then try with at least 3m data 2. Decide the number of indices required. 3. Decide the number of writes, reads per second. 4. Decide the size of documents per category. 5. Decide the query pattern. Some inputs based on the requirements 1. If you have more writes with more indices, then single monolithic collection will be slower as multiple indices needs to be updated. 2. As you have different set of fields per category, you could try with multiple collections. There is [$unionWith](https://docs.mongodb.com/manual/reference/operator/aggregation/unionWith/#examples) to combine data from multiple collections. But do check the performance it purely depends on the above decisions. Note this [open issue](https://jira.mongodb.org/browse/SERVER-48121) also. 3. If you decide to go with monolithic collection, defer the sharding. Implement this once you found that queries are slower. 4. If you have more writes on the same document, writes will be executed sequentially. It will slow down your read also. 5. Think of reclaiming the disk space when more data is cleared from the collections. Multiple collections do good here. --- 6. The point which forces me to suggest monolithic collections is that `I'd need to query all the categories at the same time`. You may need to add more categories, but combining all of them in single response would not be better in terms of performance. 7. As you don't really have a join use case like in RDBMS, you can go with single monolithic collection from model point of view. I doubt you could have a join key. If any of my points are incorrect, please let me know.
To SQL or to NoSQL? =================== I think that before you implement this in NoSQL, you should ask yourself why you are doing that. I quite like NoSQL but some data is definitely a better fit to that model than others. The data you are describing is a classic case for a relational SQL DB. That's fine if it's a hobby project and you want to try NoSQL, but if this is for a production environment or client, you are likely making the situation more difficult for them. Relational or non-relational? ============================= You mention common fields across all products. If you wish to update these fields and have those updates reflected in all products, then you have relational data. Background ---------- It may be worth reading [Sarah Mei 2013 article about this](http://www.sarahmei.com/blog/2013/11/11/why-you-should-never-use-mongodb/comment-page-1/). Skip to the section **"How MongoDB Stores Data"** and read from there. Warning: the article is called "Why You Should Never Use MongoDB" and is (perhaps intentionally) somewhat biased against Mongo, so it's important to read this through the correct lens. The message you should get from this article is that MongoDB is not a good fit for every data type. Two strategies for handling relational data in Mongo: ----------------------------------------------------- 1. every time you update one of these common fields, update every product's document with the new common field data. This is generally only ok if you have few updates or few documents, but not both. 2. use references and do joins. * In Mongo, joins typically happen code-side (multiple db calls) * In Arango (and in other graph dbs, as well as some key-value stores), the joins happen db-side (single db call) Decisions ========= These are important factors to consider when deciding which DB to use and how to model your data I've used MongoDB, ArangoDB and Neo4j. * Mongo definitely has the best tooling and it's easy to find help, but I don't believe it's good fit in this case * Arango is quite pleasant to work with, but doesn't yet have the adoption that it deserves * I wouldn't recommend Neo4j to anyone looking for a NoSQL solution, as its nodes and relations only support flat properties (no nesting, so not real documents) * It may also be worth considering MariaDB or Postgres
16,585,528
After upgrading to Android ADT version 22 and cleaning my project, the R.java files went missing. I can't use setViewContent(R.layout.activity\_main) because the activity cannot reference to the xml layout (due to the missing R.java). Also, when using the (ctrl + space) to get suggestions for setContentView, the code is not typed in. Upon looking at the error log, it shows that there was an "Unhandled event loop exception". The plug-in involved is the org.eclipse.ui. Also, whenever I create a new Hello World project, the gen folder is empty. After a few hours, I tried the android studio. But I didn't like it there. Then, when I went back to Eclipse, there was an update for SDK platform tools and build tools. I updated them but I still get the errors. I tried cleaning the project but no luck. What seems to be the problem?
2013/05/16
[ "https://Stackoverflow.com/questions/16585528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2371061/" ]
I had the same problem just solved it. check:[Java/Eclipse - No more R file ever](https://stackoverflow.com/questions/16584015/java-eclipse-no-more-r-file-ever/16584243#16584243) More info:<https://groups.google.com/forum/?fromgroups=#!topic/android-developers/rCaeT3qckoE%5B1-25-false%5D>
The solution for this is, open "Android SDK Manager". Download "Android SDK build tools". Then for safety, restart your eclipse. That's it. Back to normal. All apps start building.
18,500,811
How to do this in Scala way: return the first element as `Some[String]` from `Option[Seq[String]]`, if it's `Some[Seq[String]]` and has least one string, otherwise return `None`
2013/08/29
[ "https://Stackoverflow.com/questions/18500811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1138245/" ]
`headOption` does what you want on the `Seq`, and `flatMap` on the `Option` can do the rest: ``` def first[A](maybe: Option[Seq[A]]): Option[A] = maybe.flatMap(_.headOption) ``` This is essentially the same as the following, but more concise and idiomatic: ``` def first[A](maybe: Option[Seq[A]]): Option[A] = maybe match { case Some(xs) => xs.headOption case None => None } ``` Note that both versions are a little more generic than what you requested, but you can drop the type parameter and replace `A` with `String` if you only want it to work with strings.
``` def getHead(strings: Option[Seq[String]]): Option[String] = { strings.collectFirst { case seq if seq.nonEmpty => seq.head } } ```
1,203,237
Here's an example: ``` from django import forms class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() from django.forms.formsets import formset_factory ArticleFormSet = formset_factory(ArticleForm) formset = ArticleFormSet(initial=my_data) ``` So 'my\_data' in the example is the data I want to form to show when it is first loaded before any user input. But I'd like to go ahead and run the form's validation on the data so the user can see if there are any existing errors before they edit the data. I tried doing this: ``` formset = ArticleFormSet(initial=my_data) formset.is_valid() ``` But it didn't help.
2009/07/29
[ "https://Stackoverflow.com/questions/1203237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
ASP.Net CssClass is an abstract wrapper around the css "class" specifier. Essentially, for most intents and purposes, they are the same thing. When you set the `CssClass` property to some string like "someclass", the html that the WebControl will render will be `class = "someclass"`. --- EDIT: The CSS selectors you have written are both "correct", but they do two different things. ".someclass th" matches any *descendant* th element of an element that has the "someclass" class. The second one matches the th element itself that has the "someclass" class. Hope that's clear. Regardless of the way you specify the class for the elements (using ASP.Net's CSSClass, or just setting the class), your CSS selectors will do the same thing. They don't have anything to do with ASP.Net specifically.
When you use the `CssClass` attribute on an ASP.NET server control, it will render out as `class` in the HTML. For example, if I were to use a label tag in my mark up: ``` <asp:label runat="server" CssClass="myStyle" AssociatedControlID="txtTitle" /> ``` would render to: ``` <label class="myStyle" for="txtTitle" /> ```
308,735
This is a Sony EVO-9500A (old 8mm tape player/recorder). [![Picture of the PCB in a Sony EVO-9500A showing the mystery component](https://i.stack.imgur.com/Vfehe.jpg)](https://i.stack.imgur.com/Vfehe.jpg) What is the cartridge fuse style component? It is 1/4" by 1 1/8" about the same size as a 3AG fuse. It has a scale on the front going from 0 to 10 and looks like a thermometer. The only markings on it are on the back "FC". The PCB has its slot labeled "FC901" (as can be seen in the last picture). This thing reads about 3.2k ohms resistance (readings fluctuate quite a bit 10k on the high end down to 2k ohms). I'm not sure if those reading can even help because I don't know if this component even works. (The tape player is not sending video or audio out, which is what started all this.) [![close up of the thing, front and back](https://i.stack.imgur.com/9ykFu.jpg)](https://i.stack.imgur.com/9ykFu.jpg) [![slot on the PCB for the thing. labeled "FC901"](https://i.stack.imgur.com/3RHBK.jpg)](https://i.stack.imgur.com/3RHBK.jpg) So what is that thing and what does it do?
2017/06/02
[ "https://electronics.stackexchange.com/questions/308735", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/94416/" ]
The text beside the mounting clips says "X 200 Hour", so I'd guess that it records operating time of the tape player.
These were common on Japanese professional video recorders from the 1980s. I believe it's a a capillary tube of mercury and was told back then that they can be reversed. The helical scan heads typically had a life of around 300 hours and various pullies and belts also needed periodic replacement. The counter was non-resettable, so a reliable indicator of the life of the machine. In my experience, the machines were just as likely to become obsolete as to wear out!
405,183
I've been assigned to a code base responsible for millions of dollars of transactions, per quarter, and has been in use for over a decade. Sifting through the solution, I see **doubles** used everywhere to represent money and arithmetic is done on these variables; on the rare occasion is a **decimal** type used. What is an apt approach to understand the extent of possible damage done by rounding errors due to using an inappropriate type for currency?
2020/02/14
[ "https://softwareengineering.stackexchange.com/questions/405183", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/218080/" ]
You're right in being concerned about the use of floats for monetary amounts. Unless they are just used to calculate something which is then properly represented as a rounded scaled decimal (or an integral number of cents, which is equivalent,) they shouldn't be used to represent money. However, the damage that could possibly be caused is very dependent on the exact use of these values, so you will indeed need to find out where these numbers are used in transactions and reports and where discrepancies in the sums can happen. Unless round-off errors have been systematically siphoned off into some malevolent developer's private bank account (which happened in the past somewhere if I remember correctly) the direct monetary damage to the company or its customers is likely within reasonable limits, but you can't be certain before you've done your analysis. The effort needed to fix the problem may be several orders of magnitude higher than the damage, but may still be unavoidable.
Floating point numbers are simply not suitable for storing exact but arbitrary numeric values; every floating point number is just an approximation of a numeric value. Sure, some numbers can be represented exactly as a floating point value but many cannot and then you will have an error that can vary a lot, so it's better to always treat them as an approximation. E.g. even a simple value as 0.2 cannot be exactly represented as a double value. Calculating 0.2 + 0.1 in C# (assuming both are double values) results in 0.30000000000000004, whereas 0.3 would have been correct. Money can actually easily be represented as integers, just store it as cent values. A 64 bit integer value is more than suitable for this task. During calculations you can convert it to higher precision values first (like decimals), perform the operation, and finally convert it back to cent at the end, using appropriate rounding but for many tasks you don't have to (addition, subtraction, and multiplication will be fine with integer values). The problem with determining the error is that errors sum up. If you calculate interests, the error will be too small to be significant but if you calculate compound interests of a huge amount of money and then use the result in other calculations, the error can become significant. So if you just look what the error of a single operation is, then this may not be useful as this operation may be used as one operation in a set of operations to calculate a single result in the end. Also errors can sum up over the years. If you store an account balance as a double and always round the value to two digits after the period for displaying but internally keep the full precession, you may get correct results for years and after 30 years all of a sudden you will be off by one cent which does not only depend on the balance of the account but also on the number of transactions over the years. Sure, most people will think "One cent, is nowhere near significant". Well, if you are a finance institute and you have 100 million accounts and each is off by just one cent, your total balance is off by 1 million dollar and I would call that significant. I'm not sure of what exactly your code is calculating and how often a day it is doing so without interim rounding, so I cannot really provide a better answer here. E.g. if the money is really just transferred (subtracted from account A and added to account B), using double will not easily cause significant issues. You usually need more complex operations that include multiplications, exponentiations/square roots to quickly accumulate significant errors.
14,781,281
I have two django template pages, one of them is "base.html", with basic html tags setup as a base template. Now I have a page "child.html" that extends it, with something like `{% extends "base.html" %}` in it. Now I have to change `<body>` background color for this particular page, so in the css of "child.html" I wrote: ``` body { background-color: #000000; /* some other css here */ } ``` But the body doesn't seem to respond to any changes. I think I must have missed something. Please help, thanks. **Edit:** In "child.html", I simply have ``` <link rel="stylesheet" type="text/css" href="/site-media/css/template_conf.css"/> ``` and I try to change body css in `template_conf.css`, and there's no other page that includes `template_conf.css`.
2013/02/08
[ "https://Stackoverflow.com/questions/14781281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636625/" ]
To do this add a block in base.html in the head that allow you to inset another css AFTER the one in base.html ``` <head> .... other head tags .... <link rel="stylesheet" type="text/css" href="/site-media/css/template_conf.css"/> {% block extra_css %}{% endblock %} </head> ``` This allows you to override css tags in `template_conf.css` by adding in another `<link>` tag in child.html ``` {% block extra_css %} <link rel="stylesheet" type="text/css" href="/site-media/css/child_template.css"/> {% endblock %} ``` This allows you to override the partd of base.html that needs to change, while still being able to tweak the parts of the page in child.html that are required.
if you see the new css loaded in the firebug or other browser debugger, please try: ``` body { background-color: #000000 !important; /* some other css here */ ``` }
199,480
I tried several times but without success to get the trimmer changing the output voltage of the LM317T . I tired to link the Pin 1 and 2 then all goes to ADJ pin of the LM317T and pin 3 to ground or 2 and 3 to ADJ and pin 1 to ground or using only 2 pins as shown below but nothing worked . Nothing wokred means the voltage remains constant . Note that the trimmer is working fine when it is not combined with the voltage regulator ( 1 to + , 2 to Vout, 3 to - ) Could you advise which pins numbers to use and how? [![enter image description here](https://i.stack.imgur.com/YKps5.jpg)](https://i.stack.imgur.com/YKps5.jpg) Last update : The input voltage is 5V of an arduino uno . The output voltage required is 3.6 V [![enter image description here](https://i.stack.imgur.com/JGII9.jpg)](https://i.stack.imgur.com/JGII9.jpg)
2015/11/06
[ "https://electronics.stackexchange.com/questions/199480", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/91060/" ]
There are lots of application notes on this. Google for "Tantalum vs ceramic capacitors". Ceramic capacitors are best for its ESR & ESL. So that they can handle huge ripple currents at less temperature rise in power supplies. Same way, they don't disturb signal quality in High-speed systems (AC coupling capacitors). But their DC Bias characteristics are poor. Like a 47uF X5R 6.3V is ~23uF @ 3.3V. This Low ESR & ESL may be bad in some cases. For instance, some Buck converters that require enough ripple at the output to be stable. And lower ESL will react with cable capacitances to give unnecessary oscillations. Tantalum capacitors are best known for Volumetric efficiency and Cheap cost, but they are prone to failure due to surge currents. There are alternatives like POSCAPs (polymer capacitors). [![enter image description here](https://i.stack.imgur.com/3be6x.png)](https://i.stack.imgur.com/3be6x.png)
The only place where I've seen them [personally] in a mass-market product this century was in the VCO [for the wireless] of a Uniden cordless phone. Since you made me curious about this, I've done a bit of googling (for tantalum and VCO) and found [MAX2572EVKIT](https://datasheets.maximintegrated.com/en/ds/MAX2560EVKIT-MAX2572EVKIT.pdf) which doesn't terribly ancient (2004), and has some tantalum caps in its BOM. This is a GSM VCO. Also found a [teardown](http://www.greatrecovery.org.uk/resources/deconstruction-2-old-mobile-phone/) of a [rather looking ancient] GSM phone, and they found tantalum caps in it, but the don't say in what subsystem. Also found some in the datasheet of [HMC836LP6CE](https://www.hittite.com/content/documents/data_sheet/hmc836lp6c.pdf); this isn't clearly dated, but the revision number looks like 2011 or 2012. This is a [4G PLL/VCO](https://www.hittite.com/products/view.html/view/HMC836LP6CE) so it can't be incredibly ancient. Another teardown found some on the [PCB of the iPhone 6](https://www.arrow.com/en/research-and-events/articles/capacitors-play-an-essential-role-in-apples-iphone-6); these ones made by Rohm, their role in the phone not stated there, but claimed to be "the most expensive capacitor in the iPhone 6". Also note [this story](https://www.baldengineer.com/ouch-the-arduino-gsm-shield-has-a-pretty-serious-design-flaw-with-its-capacitors.html) for a tantalum cap on an Arduino GSM module catching fire. Of course, parts selection for an Arduino shield is probably done at much lower standards than Apple's... It's not totally clear to me what you mean by "discarding specifically power electronics applications", but in case others are interested in this, some were also found in a [teardown of an iPhone charger](http://www.righto.com/2012/05/apple-iphone-charger-teardown-quality.html).
39,148,759
I got a data.table base. I got a term column in this data.table ``` class(base$term) [1] character length(base$term) [1] 27486 ``` I'm able to remove accents from a string. I'm able to remove accents from a vector of string. ``` iconv("Millésime",to="ASCII//TRANSLIT") [1] "Millesime" iconv(c("Millésime","boulangère"),to="ASCII//TRANSLIT") [1] "Millesime" "boulangere" ``` But for some reason, it does not work when I apply the very same function on my term column ``` base$terme[2] [1] "Millésime" iconv(base$terme[2],to="ASCII//TRANSLIT") [1] "MillACsime" ``` Does anybody know what is going on here?
2016/08/25
[ "https://Stackoverflow.com/questions/39148759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383566/" ]
It might be easier to use the [stringi](/questions/tagged/stringi "show questions tagged 'stringi'") package. This way, you don't need to check the encoding beforehand. Furthermore [stringi](/questions/tagged/stringi "show questions tagged 'stringi'") is consistent across operating systems and `iconv` is not. ``` library(stringi) base <- data.table(terme = c("Millésime", "boulangère", "üéâäàåçêëèïîì")) base[, terme := stri_trans_general(str = terme, id = "Latin-ASCII")] > base terme 1: Millesime 2: boulangere 3: ueaaaaceeeiii ```
Three ways to remove accents - shown and compared to each other below. The data to play with: ``` dtCases <- fread("https://raw.githubusercontent.com/ccodwg/Covid19Canada/master/retired_datasets/individual_level/cases_2021_1.csv", stringsAsFactors = F ) dim(dtCases) # 751526 16 ``` Bench-marking: ``` > system.time(dtCases [, city0 := health_region]) user system elapsed 0.009 0.001 0.012 > system.time(dtCases [, city1 := base::iconv (health_region, to="ASCII//TRANSLIT")]) # or ... iconv (health_region, from="UTF-8", to="ASCII//TRANSLIT") user system elapsed 0.165 0.001 0.200 > system.time(dtCases [, city2 := textclean::replace_non_ascii (health_region)]) user system elapsed 9.108 0.063 9.351 > system.time(dtCases [, city3 := stringi::stri_trans_general (health_region,id = "Latin-ASCII")]) user system elapsed 4.34 0.00 4.46 ``` Result: ``` > dtCases[city0!=city1, city0:city3] %>% unique city0 city1 city2 city3 <char> <char> <char> <char> 1: Montréal Montreal Montreal Montreal 2: Montérégie Monteregie Monteregie Monteregie 3: Chaudière-Appalaches Chaudiere-Appalaches Chaudiere-Appalaches Chaudiere-Appalaches 4: Lanaudière Lanaudiere Lanaudiere Lanaudiere 5: Nord-du-Québec Nord-du-Quebec Nord-du-Quebec Nord-du-Quebec 6: Abitibi-Témiscamingue Abitibi-Temiscamingue Abitibi-Temiscamingue Abitibi-Temiscamingue 7: Gaspésie-Îles-de-la-Madeleine Gaspesie-Iles-de-la-Madeleine Gaspesie-Iles-de-la-Madeleine Gaspesie-Iles-de-la-Madeleine 8: Côte-Nord Cote-Nord Cote-Nord Cote-Nord ``` Conclusion: The `base::iconv()` is the fastest and preferred method. Tested on French words. Not tested on other languages.
25,675,223
I'm doing ex13 from Learn Python The Hard Way I'm trying to pass: ``` python ex13.py raw_input() raw_input() raw_input() ``` my code is below: ``` from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third ``` The error I keep getting is: ``` Traceback (most recent call last): File "ex13.py", line 5, in <module> script, first, second, third = argv ValueError: too many values to unpack ``` I want to know why i'm getting this error and how to fix it
2014/09/04
[ "https://Stackoverflow.com/questions/25675223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4009605/" ]
If you are trying to complete the Exercise 13 study drill from Learn Python the Hard Way, then you are trying to combine argv and raw\_input(). The author suggests you use raw\_input() to get more input from the user. With help from this thread I came up with this: ``` from sys import argv ScriptName, first, second, third = argv print "What is your fourth variable?" fourth = raw_input() print "What is your fifth variable?" fifth = raw_input() print "What is your sixth variable?" sixth = raw_input() print "The script is called: ", ScriptName print "Your first variable is: ", first print "Your second variable is: ", second print "Your third variable is: ", third print "Your fourth variable is: ", fourth print "Your fifth variable is: ", fifth print "Your sixth variable is: ", sixth print "For your script %r, these are the variables: %r, %r, %r, %r, %r, and %r." % (ScriptName, first, second, third, fourth, fifth, sixth) ``` Does this seem to be what the author is suggesting?
Yes you can do that, but it's a bit tricky and the author didn't mention it in previous exercises. argv is actually a list[] (or data array), so you can address its individual elements within the script. Here is my example: ``` from sys import argv script, first, second, third = argv # one way to unpack the arguments script_new = argv[0] # another way first_new = argv[1] second_new = argv[2] third_new = argv[3] print "original unpacking: ", script, first, second, third print "argv[] unpacking: ",script_new, first_new, second_new, third_new argv[0] = raw_input("argument 0? ") argv[1] = raw_input("argument 1? ") argv[2] = raw_input("argument 2? ") argv[3] = raw_input("argument 3? ") print argv[0], argv[1], argv[2], argv[3] ```
55,181
Challenge --------- Write a program to factor this set of 10 numbers: ``` 15683499351193564659087946928346254200387478295674004601169717908835380854917 24336606644769176324903078146386725856136578588745270315310278603961263491677 39755798612593330363515033768510977798534810965257249856505320177501370210341 45956007409701555500308213076326847244392474672803754232123628738514180025797 56750561765380426511927268981399041209973784855914649851851872005717216649851 64305356095578257847945249846113079683233332281480076038577811506478735772917 72232745851737657087578202276146803955517234009862217795158516719268257918161 80396068174823246821470041884501608488208032185938027007215075377038829809859 93898867938957957723894669598282066663807700699724611406694487559911505370789 99944277286356423266080003813695961952369626021807452112627990138859887645249 ``` Each of these: * Is a 77-digit number less than 2^256. * Is a semiprime (e.g., the product of exactly 2 primes). * Has something in common with at least one other number in the set. Thus, this challenge is not about general factoring of 256-bit semiprimes, but about factoring *these* semiprimes. It is a puzzle. There is a trick. The trick is fun. It is possible to factor each of these numbers with surprising efficiency. Therefore, the algorithm you choose will make a much bigger difference than the hardware you use. Rules ----- 1. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins. 2. You may use any method of factoring. (But don't precompute the answers and just print them. You program should do actual work.) 3. You may use any programming language (or combination of languages), and any libraries they provide or you have installed. However, you probably won't need anything fancy.
2015/08/23
[ "https://codegolf.stackexchange.com/questions/55181", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/29806/" ]
J, 2 bytes ---------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") now, so I assume efficiency doesn't actually matter, which means: ``` q: ``` (J's "factor prime" function) will return the right answer (in the form of a neatly formatted `2x10` array!) if you pass it an array of bignums give it a couple of hours/days to factor the semiprimes.
Pyth, 15 13 12 bytes ==================== ``` jbmS{iLd.Q.Q ``` Expects the list of primes seperated by newlines on stdin. Outputs in the following format: ``` [1, 123830525223423718982054269884856893727, 126652934104061135988638942588043498971, 15683499351193564659087946928346254200387478295674004601169717908835380854917] [1, 123830525223423718982054269884856893727, 196531562802139162910711939551924590851, 24336606644769176324903078146386725856136578588745270315310278603961263491677] [1, 126652934104061135988638942588043498971, 313895598975456800331958744266933545471, 39755798612593330363515033768510977798534810965257249856505320177501370210341] [1, 196531562802139162910711939551924590851, 233835251470362519313085185758275325847, 45956007409701555500308213076326847244392474672803754232123628738514180025797] [1, 218051709768607497734800854124975705007, 260261943488556401874345256435550440693, 56750561765380426511927268981399041209973784855914649851851872005717216649851] [1, 218051709768607497734800854124975705007, 294908745103709254641398276907437631131, 64305356095578257847945249846113079683233332281480076038577811506478735772917] [1, 233835251470362519313085185758275325847, 308904433345854212511531098349325333463, 72232745851737657087578202276146803955517234009862217795158516719268257918161] [1, 260261943488556401874345256435550440693, 308904433345854212511531098349325333463, 80396068174823246821470041884501608488208032185938027007215075377038829809859] [1, 294908745103709254641398276907437631131, 318399740590727338211743341325021840319, 93898867938957957723894669598282066663807700699724611406694487559911505370789] [1, 313895598975456800331958744266933545471, 318399740590727338211743341325021840319, 99944277286356423266080003813695961952369626021807452112627990138859887645249] ```
25,796,156
I needed to display different text based on the day of the week and successfully created the following code snippet using if/else. Now my client wants forward/back arrows to simulate going forwards and backwards from the current day of the week. Is there a way to enhance this script to \_get a value in the URL and +1 or -1 of the $today variable? ``` <?php $today = date('N'); if( $today == 7) { ?> <th class="WADAResultsTableHeader">Sunday</th> <?php } elseif( $today == 1 ) { ?> <th class="WADAResultsTableHeader">Monday</th> <?php } elseif( $today == 2 ) { ?> <th class="WADAResultsTableHeader">Tuesday</th> <?php } elseif( $today == 3 ) { ?> <th class="WADAResultsTableHeader">Wednesday</th> <?php } elseif( $today == 4 ) { ?> <th class="WADAResultsTableHeader">Thursday</th> <?php } elseif( $today == 5 ) { ?> <th class="WADAResultsTableHeader">Friday</th> <?php } elseif( $today == 6 ) { ?> <th class="WADAResultsTableHeader">Saturday</th> <?php } ?> ```
2014/09/11
[ "https://Stackoverflow.com/questions/25796156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090213/" ]
This is a working tested example ``` if (array_key_exists('day', $_GET)) { $add_day = $_GET['day']; } else { $add_day = 0; } $yesterday = $add_day - 1; $tomorrow = $add_day + 1; $link_yesterday = $_SERVER['PHP_SELF'] . '?day=' . $yesterday ; $link_tomorrow = $_SERVER['PHP_SELF'] . '?day=' . $tomorrow ; $display_day = mktime(0, 0, 0, date("m") , date("d") + $add_day, date("Y")); $today = date('N', $display_day); ?> <table> <tr> <?php if( $today == 7) { ?> <th class="WADAResultsTableHeader">Sunday</th> <?php } elseif( $today == 1 ) { ?> <th class="WADAResultsTableHeader">Monday</th> <?php } elseif( $today == 2 ) { ?> <th class="WADAResultsTableHeader">Tuesday</th> <?php } elseif( $today == 3 ) { ?> <th class="WADAResultsTableHeader">Wednesday</th> <?php } elseif( $today == 4 ) { ?> <th class="WADAResultsTableHeader">Thursday</th> <?php } elseif( $today == 5 ) { ?> <th class="WADAResultsTableHeader">Friday</th> <?php } elseif( $today == 6 ) { ?> <th class="WADAResultsTableHeader">Saturday</th> <?php } ?> </tr> </table> <a href="<?php echo $link_yesterday;?>">Previous Day</a> <a href="<?php echo $link_tomorrow;?>">Next day</a> ```
Using a hyperlink you can do: ``` echo "<a href=\"page.php?today=".$today-1."\">Back</a>"; ``` And then to retrieve the today variable: ``` $today=$_GET["today"]; ```
26,225,191
Working on building JavaScript sourcemaps into my workflow and I've been looking for some documentation on a particular part of debugging source maps. In the picture below I'm running compressed Javascript code, but through the magic of source maps Chrome debugger was able to reconstruct the seemingly uncompressed code for me to debug: ![Source Maps](https://i.stack.imgur.com/UFYyc.png) However, if you look at the local variables, `someNumber` and `someOtherNumber` are not defined. Instead, we have `a` and `r`, which are the compiled variable names for this function. This is the same for both Mozilla Firefox and Chrome. I tried looking through the [Chrome DevTools Documentation](https://developer.chrome.com/devtools/docs/javascript-debugging#source-maps) on sourcemaps, but I didn't see anything written about this. Is it a current limitation of sourcemap debugging and are there any workarounds for this? **update**: I've since found [this thread](https://code.google.com/p/chromium/issues/detail?id=327092) in chromium project issues. It doesn't look like it has been or is being implemented. This is becoming an increasingly more important problem as teams are beginning to implement Babel in their build systems to write ES2015 code. Have any teams found a way around this?
2014/10/06
[ "https://Stackoverflow.com/questions/26225191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506980/" ]
Using `Watch Expressions` on the right hand side, *usually* solves this. Expand the menu, and use the plus button to add your variables. You can use `someNumber` and `someOtherNumber`, and even `someNumber + someOtherNumber`.
There's still no solution to mapping variable names in Javascript source maps, but there's a solution for Babel 6. As we've adopted ES2015, the mangled import names became a major pain point during development. So I created an alternative to the CommonJS module transform that does not change the import names called [babel-plugin-transform-es2015-modules-commonjs-simple](https://github.com/jamietre/babel-plugin-transform-es2015-modules-commonjs-simple). As long as you aren't writing modules that depend on exporting [dynamic bindings](http://www.2ality.com/2015/07/es6-module-exports.html) it is a drop-in replacement for the default babel commonjs module transform: ``` npm install --save-dev babel-plugin-transform-es2015-modules-commonjs-simple ``` and `.babelrc`: ``` "plugins": ["transform-es2015-modules-commonjs-simple"] ``` This will compile ES2015 modules to CommonJS without changing any of the symbol names of imported modules. Caveats are described in the readme. This won't help you with minifying/uglifying, though, so the best solution seems to be to just don't use minification during development. Then at least it's only a problem if you have to debug something on a production web site.
21,272,732
I have something similar to the following situation: ``` <div id="block"> <span data-type="a">a</span> <span data-type="b">b</span> <span data-type="c">c</span> </div> ``` when clicking on one of the spans, I'd like to return back the data-type. I tried doing: ``` $('#block').on('click', function(event) { var text = $('#block').data('type'); return text; }); ``` However it's always coming back as undefined. Any idea as to why this is happening/what the correct solution is? Thanks
2014/01/22
[ "https://Stackoverflow.com/questions/21272732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1417998/" ]
It's because your div `#block` doesn;t have the `data-type` tag but `span` does. So, handle the click event on span. ``` $('#block span').on('click', function(event) { var text = $(this).data('type'); console.log(text); }); ```
``` $('#block > span').on('click', function(event) { var text = $(this).attr('data-type'); return text; }); ```
29,173,782
If i have an array that I've used to create 50 random numbers, I then sort them numerically. Now lets say I wanted to print out the 10 biggest number (elements 40 to 50) I could say: `print($array[40]) print($array[41]) print($array[42])` etc etc. But is there a neater way to it? Hope I'm making myself clear. Cheers
2015/03/20
[ "https://Stackoverflow.com/questions/29173782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4432758/" ]
You could loop over the indexes. ``` say $array[$_] for 40..49; ``` Offsets from the end make more sense here. ``` say $array[$_] for -10..-1; ``` You could also use an array slice. ``` say for @array[-10..-1]; ``` To print them on one line, you can use `join`. ``` say join ', ', @array[-10..-1]; ```
Try this : ``` print join ',',@array[-10..-1] ,"\n"; ```
45,911
I am wondering what would be the right set up to record the sound of a pipe organ in a cathedral/church. If this is the church: ``` + | -----------------------| / \ / () \ | ()() | | ()()=* ^ ============================ ^ ^Organist Pipe organ ``` The organist will not hear the same sound which is in the center the church. Also, there are the sounds of the keys and pedals being pressed. I assume there should be a microphone somewhere in the middle of the church to capture the sound of the organ, without capturing the sound of the keys. I have a studio microphone which I have used for recording human voice in a studio-like environment. Will that do the job? What is the right microphone/setup to record the sound of the organ in the best way?
2019/06/14
[ "https://sound.stackexchange.com/questions/45911", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/25354/" ]
Distance is your key. Do not record too close to the organ or it will sound very weak. The larger/louder the instrument, the further away you would want to place the mic array. You want to balance the distance so that you are getting an even balance of reverberant sound and direct sound from the organ. Of course, if you were recording a chamber organ, then you could record closer, but most cathedral organs don't fall into this category. You can get a decent recording with two mics, but I generally use 4 for a little more control in the mix. Two mics will be directional - I find ORTF Cardioid works well. The other two will be omnidirectional and very widely spaced either side of the ORTF mics. Try to use high stands if at all possible. Mine are large manfrotto lookout and lighting stands which get me about 10-12 meters high. At the distance you need to record, the sound of the keys, stops and pedals won't be an issue. Capsules used in this setup: MK4 (ORTF) MK2s (Wide spaced outriggers). Each pair panned hard L/R in the mix. Considering your 'studio' voice mic - the frequency response of your organ mics need to be as flat as possible. Studio 'voice' mics generally don't exhibit a flat frequency response as they are tailored for voice frequencies and will likely have an attenuated lower end to cope with 'proximity effect'. Consequently they are not suitable for recording instruments at a distance, which you need when recording an organ. Example sound is: <https://www.dropbox.com/s/0yaqavubuur80xs/ANSCO-NOTREDAME-003_5.m4a?dl=0> [![Melbourne St Patricks Recording](https://i.stack.imgur.com/6RyLz.jpg)](https://i.stack.imgur.com/6RyLz.jpg)
You say you "have a studio micro microphone". Does the microphone call itself a studio microphone, possibly using the attribute "professional"? Or does it have (documented) equivalent noise levels and frequency/directional characteristics that give some credence to its claim? The distance (if any) with which the microphone (of which you will need several anyway) can be used quite depends on this. Basically you get more reverb the more you move backwards from the organ. A placement within the first third of a church is usually called for to get a reasonable amount of direct sound. Is there an actual audience? If it is, you want to rather get closer than if there isn't because an audience is noisy in itself. Microphone stands with sufficient height may allow you to record over their heads. There usually is a significant amount of reverb from most directions. A cardioid microphone tends to offer the best way to balance the sound since it is insensitive at its back. If audience noise is a problem, a hypercardioid might offer better options of avoiding crowd noise, particularly when using high microphone stands. If you are recording from closer up, be sure to get a sound check: organs can be super loud and you don't want to have microphone or recording equipment clip.
19,307,877
I'm a C noob, but have experience in Java and Python. I'm currently doing an assignment on bit operations and found a guide that showed me how to do it, problem is that I don't quite understand. ``` c=(c&(1<<n))>>n; ``` c = an unsigned char n = integer, represents the nth bit of a c. I understand that & = the AND logic gate, and I'm aware of how that works also. I understand that << = left shift, and >> = right shift. However, I'm unable to comprehend how this all works together. Could someone explain how this code executes and how it's able to return the nth bit.
2013/10/10
[ "https://Stackoverflow.com/questions/19307877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692517/" ]
Also took me a second to figure it out (I'm used to do this another way), but here it is: Let's start with the first thing the snippet does (because of the brackets). ``` 1<<n ``` 1 is written in binary like this 00000001 and to shift it to the left n steps, basically just shifts the 1, e.g. 2 steps would result in 00000100 and 5 in 00100000. So what you got is a number whith only the nth bit 'switched on'. Then this number is AND with you char, so wich will either return the same number or 0. To see why this happens lets look at some example (read up to down): ``` Your number is 0 1 0 1 0 1 1 0 & & & & & & & & And 1<<4 is 0 0 0 1 0 0 0 0 | | | | | | | | result: 0 0 0 1 0 0 0 0 ``` or ``` Your number is 0 1 0 1 0 1 1 0 & & & & & & & & And 1<<5 is 0 0 1 0 0 0 0 0 | | | | | | | | result: 0 0 0 0 0 0 0 0 ``` So if the nth bit of c is 'switched on', the result after the AND logic gate also gonna have this bit set to 1. Last but not least we want this bit not to be somewhere in our c but at the beginning (or to be honest the end, but you know what I mean, so that we can check if it is 0 or 1, because 00000001 equals 1 and 00000000 equals 0), so we shift the bit, to the last place (which is easy, because we know it is at the nth place, so we can just say, "Hey bit, move n-places to the left", e.g. `00010000>>4` equals 00000001). And that's it, by the way, you could also use `((c<<n)>>n)`, that's what I usually use, and I think it's kind of easier to understand (or?)
`c&(1<<n)` this is testing to see if the nth bit is a one or zero. after this operation you will have either all zeros, or `n-1` zero followed by a one. then applying `>>n` get the nth bit from the previous operation to be the LSB. and you assign that to the variable.
1,635,333
I want to learn .NET and I have 2 weeks time of this. I have sound knowledge of CLR, Assemblies and certain basics. I have a copy of "CLR via C#". But I need to learn advanced C# concepts like delegates, reflection, generics and so on. And then I need to quickly jump into coding. Remember, I have 2 weeks time. I suppose a quick grasp of C# advanced concepts and then some thorough coding practice is the need of the hour. Can you suggest me on: 1) My approach. 2) Sites or books to learn these advanced C# concepts fast. 3) Practicing the things learnt by coding....suggestion on practice/programming questions. Since I also believe one can only learn any language by practicing it. Please pour in your suggestions. Regards, Justin Samuel.
2009/10/28
[ "https://Stackoverflow.com/questions/1635333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175624/" ]
I recommend [C# 2005: The Base Class Library](http://www.dotnet2themax.com/blogs/fbalena/PermaLink,guid,6d4703fa-edb4-441d-ae2a-dd9bc1303689.aspx) by Francesco Balena. Its a bit of an older book, but I found it to be an amazing read. I learnt a ton with it.
Refer this link, <http://sharpertutorials.com/tutorials/> This site having hands on guides for programming areas includes **1. Introduction to C#** **2. Intermediate C# Tutorials,** **3. Advanced C# Tutorials** **4. Object Orientation** **5. Real World Object Orientated Programming** **6. Testing and Debugging** **7. Security and Encryption** **8. Using .Net Assemblies** **9. Software Engineering Principles** **..........etc**
956,498
I'd like to tinker with the auto-generated columns in a gridview a bit. What event would I want to override to modify them just after they are generated but before the control is rendered?
2009/06/05
[ "https://Stackoverflow.com/questions/956498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116645/" ]
The columns are added to the GridView when the DataBind() method is called
Those two links are for the Datagrid not Gridview.
61,740,925
We use an asp.net application using web forms and viewing the page source there is a field generated as below ``` input type="hidden" name="__VIEWSTATE_KEY" id="__VIEWSTATE_KEY" value="VIEWSTATE_xxooxx...." ``` Our company recently had a security scan run against our application with a flag raised for `Cross-Site Request Forgery`. The scan suggested it updated the value of this hidden field and did another post that resulted in a valid request. Is this a false positive test?
2020/05/11
[ "https://Stackoverflow.com/questions/61740925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4118953/" ]
Your pattern matches if a `0` is either followed by or preceded by a `1` but there's no restriction that it must be only one of them. You can add a negative Lookbehind and a negative Lookahead to achieve that. Try something like following: ``` (?<!1)0(?=1)|(?<=1)0(?!1) ``` **[Demo](https://regex101.com/r/cHzsmK/1)** --- ### Edit If you want to match if the `0` has a `1` neighbor or a `1` that is 3 characters away, things will get a little more complicated but we basically follow the same rule. Something like this would work: ``` (?<!1|1.{2})0(?=1|.{2}1)|(?<=1|.{2}1)0(?!1|.{2}1) ``` **[Demo](https://regex101.com/r/iGOEjp/1)**.
The following regular expression addresses a generalization of the question. It matches every character in a string that: 1) is followed by the same character and not preceded by the same character; or 2) is preceded by the same character and not followed by the same character. ``` ^(.)(?=\1)|(?<=(.))(?=\2).$|(?<=(.))(?:(?=\3).(?!\3)|(?!\3)(.)(?=\4)) ``` [Demo](https://regex101.com/r/VeqRrJ/1/) The regex engine performs the following operations. ``` ^ match beginning of line (.) match first char and save to capture group 1 (?=\1) following char is the same char | or (?<=(.)) save the preceding char to capture group 2 (?=\2) char equals preceding char . match char $ match end of line | or (?<=(.)) save preceding char to capture group 3 (?: begin a non-capture group (?=\3) char equals preceding char . match char (?!\3) following char is a different | or (?!\3) char does not equal preceding char (.) save char in capture group 4 (?=\4) following char is the same ) end non-capture group ```
34,842,582
What's wrong with this piece of code? ``` if key == 'w' then if charastate == neutral then charamov = up end elseif charastate == lr then charastate = neutral then charamov = up end end ``` Error is : > > "unexpected symbol near 'then'" > > > Also it doesn't matter if it's changed for "and" Thanks, I'm trying to learn by myself but is quite exhausting.
2016/01/17
[ "https://Stackoverflow.com/questions/34842582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802390/" ]
The error message is telling you to omit the last `then` because it is not paired off with an `if`. Indenting the code properly will help you see it.
Try this code. You are using "then" two times in else if statement. ``` if key == 'w' then if charastate == neutral then charamov = up elseif charastate == lr then charastate = neutral charamov = up end end ```
57,246,369
This video covers an implementation of the min coins to make change. <https://en.wikipedia.org/wiki/Change-making_problem> The place I'm not clear on is where the interviewer goes into the details of optimization, starting from here. <https://youtu.be/HWW-jA6YjHk?t=1875> He suggests that to make the min number of coins, using denominations [25, 10, 1], we only need to use the algorithm to make change for numbers above 50 cents, after which we can safely just use 25 cents. So if the number was $100.10, we can use 25 cents till we hit 50 cents at which time we need to use the algorithm to compute the precise value. This makes sense for the list of denominations give [25, 10, 1]. To get the breakpoint figure he suggests using LCM of the denominations which is 50 in this case. ``` For example 32 - 25 * 1 + 1 * 7 = 8 coins. But with 10 cents we can do 32 - 10 * 3 + 1 * 2 = 5 coins. ``` So we cannot just assume 25 cents is going to be included in the minimum number of coins calculation. Here is my question -- Suppose we have denominations [25, 10, 5, 1], the lcm is still 50. But there is no min solution for any number over 25 cents has doesn't include the 25. eg - ``` 32 - 25 * 1 + 5 * 1 + 1 * 2 = 4 coins. 32 - 10 * 3 + 1 * 2 = 5 coins ``` So shouldn't the breakpoint be 25 cents in this case? Instead of the lcm? Thanks for answering.
2019/07/29
[ "https://Stackoverflow.com/questions/57246369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1792945/" ]
I'm posting this answer here since this question is the first Google result for the problem I had: When referencing the `usdz` file exactly like Apple's documentation proposes, the AR button is rendered on top of the teaser image. When clicking the linked image, Safari opens the Quick Look screen, but the message "Object could not be opened." pops up. However, when I access the `usdz` file directly by its URL, the AR model does get rendered properly. The problem was that the complete site was protected by HTTP Basic Auth configured with an `.htaccess` file. Apparently, Safari will not use the existing session to access the `usdz` file and thus the file cannot be loaded. In my case, it helped to remove the HTTP Basic Auth protection from the site. As soon as the site was publicly accessible, the AR model could be loaded without any problems.
Embed a link to USDZ Files for direct AR-scenes usage. **Here's a code for multiple usdz files**: ``` <html> <head> <meta charset="utf-8"> <title>Augmented Reality</title> </head> <body> <div> <a href="yourDirectory/ar_pixar_file_01.usdz" rel="ar"> <img src="ar_image_01.png" alt="AR Image" width="360" height="240"> </a> <a href="yourDirectory/ar_pixar_file_02.usdz" rel="ar"> <img src="ar_image_02.png" alt="AR Image" width="360" height="240"> </a> <a href="yourDirectory/ar_pixar_file_03.usdz" rel="ar"> <img src="ar_image_03.png" alt="AR Image" width="360" height="240"> </a> </div> </body> </html> ``` > > The most important part of this code snippet is **`rel="ar"`** attribute, indicating that the link attached to the image is referring to content usable with the iOS AR-Viewer. > > >
18,059,124
What I'm trying to do is create a list of swatches that, upon mouseover, show a preview of the color that is being hovered on. I'm using a CSS sprite to deliver both the swatches and the previews. I have it working, but I feel there is a far more efficient way to deliver the associated jQuery. I'm seeking help to find a more elegant solution. **Below is my HTML:** ``` <div class="chip-preview"></div> <div class="style-swatches"> <ul> <li class="c1"></li> <li class="c2"></li> <li class="c3"></li> <li class="c4"></li> <li class="c5"></li> <li class="c6"></li> <li class="c7"></li> <li class="c8"></li> <li class="c9"></li> <li class="c10"></li> <li class="c11"></li> <li class="c12"></li> </ul> </div> ``` **And my associated jQuery:** ``` $('.c1').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-195px 0"); }); $('.c2').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-390px 0"); }); $('.c3').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-585px 0"); }); $('.c4').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-780px 0"); }); $('.c5').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-975px 0"); }); $('.c6').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-1170px 0"); }); $('.c7').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-1365px 0"); }); $('.c8').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-1560px 0"); }); $('.c9').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-1755px 0"); }); $('.c10').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-1950px 0"); }); $('.c11').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-2145px 0"); }); $('.c12').hover(function () { $(this).parents().find('.chip-preview').css("background-position","-2340px 0"); }); ``` Each increment of class cN moves the background -195px on the horizontal. Ideas on how to make this better?
2013/08/05
[ "https://Stackoverflow.com/questions/18059124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2653224/" ]
Try this: ``` var xPosition = -195; $(".style-swatches li").each(function(){ $(this).hover(function(){ $(this).parents().find('.chip-preview').css("background-position", (xPosition - ($(this).index() * 195)) + "px 0"); }); }); ``` [Fiddle](http://jsfiddle.net/zPtr6/3/)
Try ``` $('.c1, .c2, .c3').hover(function () { var $this = $(this), pos = $this.attr('class').match(/\bc(\d+)\b/)[1]; $(this).parents().find('.chip-preview').css('background-position','-' + (pos * 195) + 'px 0'); }); ```
28,483
Trying to design a circuit that can reliably detect a situation where a child wets their bed. The 3 key requirements are -- 1. Reliability of the approach 2. Ease of use, i.e. a no-fuss approach 3. Child's safety (from harm) due to electronics Can the soil moisture detection technique be used ? How can I make this easy-to-use given s.t. while changing bed line ? This shouldn't require messing with the device, rewiring etc.
2012/03/21
[ "https://electronics.stackexchange.com/questions/28483", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/6406/" ]
I like @DavidKessner's solution, but a PCB on the mattress seems ... uncomfortable to me. I would sew in [conductive thread](http://www.conductivethread.ca/) (google for other suppliers) into several bedtime underwear, creating several lines across the area that gets wet. Connect every other line together so you now have a pair of sensor lines. Visualize it this way: ``` +----------------------------------- A + -----------------------+ +----------------------- + + -----------------------+ +----------------------- + -----------------------+--------- B ``` When the underwear gets wet, the resistance between A and B will go down dramatically. You could connect A and B to any kind of small snap connector (I'm thinking of a 9V battery connector) which then leads away to the actual circuit which could be tiny and zippered/buttoned to a convenient location on the leg/front/back of the pyjama. You could power this off a couple of coin cells, and there are NUMEROUS "water detector" circuits online which could be made VERY small and light. Washing is as simple as unsnapping the underwear from the circuit and tossing in the wash.
You could use a relative humidity sensor, [this kind of thing](http://www.sparkfun.com/products/10167).
48,359,636
I'm trying to split a cell on the 2nd space character. Is this possible? Or is it just possible to split on a space character? ``` LeBron James SF ORL @ CLEThu 7:00pm LeBron James SF ORL @ CLEThu 7:00pm ```
2018/01/20
[ "https://Stackoverflow.com/questions/48359636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9216039/" ]
Please try regular expression: `=REGEXEXTRACT(A1,"^([^ ]+ [^ ]+) (.*)")` * `(...) (...)` is to find 2 groups on a string * `^` at the beginning means to look at the start of a string * `[^ ]+` means 1+ no space char. * `.*` means any number of chars References: 1. [RegexExtract](https://support.google.com/docs/answer/3098244?hl=en) 2. [Regex Syntax](https://github.com/google/re2/blob/master/doc/syntax.txt)
A simple way is to [SUBSTITUTE](https://support.google.com/docs/answer/3094215) the second instance of a space with a character not otherwise in service (I chose `£`), then [SPLIT](https://support.google.com/docs/answer/3094136) on that character: ``` =split(substitute(A1," ","£",2),"£") ```
49,316,282
How can I plot 2 density plots in one output. Here are my codes for the density plot. ``` #Density Plot d <- density(dataS) plot(d, main= "Density plots of Revenue") o <- density(RemoveOutlier) plot(o, main= "Density plots of Revenue excluding outliers") ``` So basically I want to see both plots on one output. And maybe change the color line of each plot and a legend on the top right. Attached is the picture of the 2 plots in R. **image 1** ![](https://i.stack.imgur.com/qGeiq.png) **image 2** ![](https://i.stack.imgur.com/TSerx.png)
2018/03/16
[ "https://Stackoverflow.com/questions/49316282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Or instead of the second "plot()" function call, use "lines()", then you get two overlapping density plots.
If the support of your PDFs is quite spread apart, using `lines` will not suffice. You'll need to control the range of the calculated values to the density. Here's an example: ``` x1 = rnorm(1e5) x2 = rnorm(1e5, mean = 4) #looks bad because the support has little overlap plot(density(x1)) lines(density(x2)) ``` To overcome this, leverage the `to` and `from` parameters to `density` ``` rng = range(c(x1, x2)) d1 = density(x1, from = rng[1L], to = rng[2L]) d2 = density(x2, from = rng[1L], to = rng[2L]) matplot(d1$x, cbind(d1$y, d2$y), type = 'l', lty = 1L) ``` Add bells and whistles to taste.
53,743,329
I need to get an input from a file. This input is any binary number of any length where the digits are separated by a semicolon like this: > > 0; 1; 1; 0; 1; 0; > > > What I would do is pass the file to a variable like ``` if (myfile.is_open()) { while ( getline (myfile,line) ) { File = line; } myfile.close(); } ``` But I'm not sure what data type I would make the variable `File` be. After this I'd have to store the digits in an `array` or `vector`.
2018/12/12
[ "https://Stackoverflow.com/questions/53743329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10745795/" ]
We can use `ave` grouped by `A` and remove the groups that has `all` `NA`s ``` df[!with(df, ave(is.na(B), A, FUN = all)), ] # A B #2 2 NA #3 3 77 #5 2 81 ``` --- Using the same logic with `dplyr` ``` library(dplyr) df %>% group_by(A) %>% filter(!all(is.na(B))) ```
We can use `data.table` ``` library(data.table) setDT(df1)[, .SD[any(!is.na(B))], A] # A B #1: 2 NA #2: 2 81 #3: 3 77 ``` ### data ``` df1 <- structure(list(A = c(1L, 2L, 3L, 1L, 2L), B = c(NA, NA, 77L, NA, 81L)), class = "data.frame", row.names = c(NA, -5L)) ```
655,797
I have the following definition: Let ($X$,$\mathcal{T}$) and ($X'$, $\mathcal{T'}$) be topological spaces. A surjection $q: X \longrightarrow X'$ is a quotient mapping if $$U'\in \mathcal{T'} \Longleftrightarrow q^{-1}\left( U'\right) \in \mathcal{T} \quad \text{i.e. if } \mathcal{T'}=\{ U' \subset X' : q^{-1}\left( U' \right) \in \mathcal{T} \}$$ and the properties: 1. $q$ is a bijective quotient mapping $\Leftrightarrow$ $q$ is a homeomorphism 2. In general, $q$ quotient $\not \Rightarrow q$ open. If $U \in \mathcal{T}, q(U)\subset X'$ is open if $q^{-1}\left( q\left( U \right) \right) \in \mathcal{T}$ but not in general. I could not find an example of quotient mapping for which $q^{-1}\left( q\left( U \right) \right)$ is not open. I would understand the idea better if you could show me one.
2014/01/29
[ "https://math.stackexchange.com/questions/655797", "https://math.stackexchange.com", "https://math.stackexchange.com/users/122136/" ]
Here is a "visual" example: Wrap the unit interval $[0,1]$ around the unit circle $S^1$ by identifying $0$ and $1$. The interval $[0,1/2) $ is open in $[0,1]$, but its image in $S^1$ is not open.
Partition $X=ℝ$ (under the usual topology) into two equivalence classes $(-\infty, 0]$ and $(0,\infty)$ to get a two-point quotient space $X'$ (called the [Sierpiński space](https://en.wikipedia.org/wiki/Sierpi%C5%84ski_space)) and let $q:X\to X'$ be the canonical projection mapping that takes each element of $ℝ$ to its equivalence class. Then $q$ is a quotient mapping that satisfies $q^{-1}(q((-\infty,0)))=(-\infty,0]$.
2,075
My bathroom walls were a mix of plaster and drywall with various layers of paint, primer, and skim coating. I attempted to skim coat the walls myself to prepare for priming and painting, but I wasn't happy with the results so I hired someone to do it right. The walls are smooth now but not quite flat. For example, if you put a baseboard against one wall the baseboard touches the wall at two high points horizontally and there is space between the rest of the baseboard and wall. The drywall guy said he would come back and fix anything that needs to be done such as those gaps and any other wall imperfections. He said however, that I should prime the walls and finish and nail the baseboards before he fixes the imperfections. He said that many of the subtle nicks and grooves in the wall would stand out better once the primer had been applied. He also said that he could achieve better results if the baseboards were nailed in first rather than using a straight edge to even out the low points, and that he would fill in from the top of the baseboards on up. It seems to me that it would be easier to use a straight edge to even it out and that the baseboards would only get in the way. He said he didn't want to make it flat only to have me put on the baseboards and find out that it still looked off. I don't really buy that. It also seems odd to prime first before getting all the imperfections since the primer seals the wall and putting patches on top of that doesn't seem quite right. I'm not a professional and I don't want to tell him how to do his job, but if he's cutting corners I don't want to be taken advantage of either. Personally I think he should have evened out the low points at the beginning. Hidden nicks I can understand. I'd be grateful for any informed opinions.
2010/10/06
[ "https://diy.stackexchange.com/questions/2075", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/697/" ]
I had to have my walls skim coated and I waited until I was completely done with everything before putting the baseboards on. I didn't want to take any chances scuffing them up or getting paint on them. My vote is do them absolutely last.
I agree with baseboard last. The drywall guy can hold a board up to the wall for a straight edge. If the baseboard fit isn't perfect (hardly ever is) when you go to install it, then you can run a bead of calk down the top after you put it on. Then paint the calc either the wall o the baseboard color or split it.
60,641,472
I receive one of these errors when attempting to open up a session. > > selenium.common.exceptions.SessionNotCreatedException: Message: session not created > from chrome not reachable > (Session info: chrome=80.0.3987.132) > > > selenium.common.exceptions.SessionNotCreatedException: Message: session not created > from disconnected: Unable to receive message from renderer > (Session info: chrome=80.0.3987.132) > > > ChromeDriver = 80.0.3987.106 I googled these errors and none of the solutions helped, here's my current code: (one of the solutions suggested adding Chrome options) ```py from selenium import webdriver class YoutubeBot(): def __init__(self): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') self.driver = webdriver.Chrome('/usr/local/bin/chromedriver', chrome_options=chrome_options) ``` EDIT: I have now found out that this issue is fixed by using headless, I'd still like to test my code while writing it, is there another solution perhaps? (I'm using the Xfce4 DE on Arch Linux)
2020/03/11
[ "https://Stackoverflow.com/questions/60641472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8814286/" ]
I solved the issue using a workaround for my initial intend by passing a css style property to the template of the parent vue-component: ``` <template> <div> <span v-for="(line, index) in paragraph.lines" :key="index"> <p v-if="line.length"> <span v-for="(lineFragment, index) in line" :key="index"> <component class="inline-component" :element="lineFragment" :is="lineFragment.type"/> </span> </p> </span> </div> </template> <script lang="ts"> import { Component, Prop } from 'vue-property-decorator' import ElementHook from '@/views/ElementHook.vue' @Component export default class ParagraphWrapper extends ElementHook { @Prop() element!: ParagraphElement } </script> <style scoped> .inline-component { display: inline; } </style> ``` The ElementHook component serves as a basic abstract class which imports all the sub components which can be displayed via `:is="lineFragment.type" (e.g. 'text' for TextWrapper component). If one wants to ensure the paragraphs are stilled wrapped around the borders of the parental container object, you want to consider adding `white-space: pre-wrap;` to the css-class defined in the bottom part of the SFC.
Vue component templates should have root element that exists in DOM. Commonly `div` or `span` wrapper elements are used. This is rarely a a problem because root element can be styled to fit the layout. There's [vue-fragment](https://github.com/y-nk/vue-fragment) plugin that provides the functionality of `React.Fragment` in Vue. It basically unwraps root element on mount. Since it's a hack, it may not work in all situations as expected. Render function [can be used to render text nodes](https://stackoverflow.com/questions/38716105/angular2-render-a-component-without-its-wrapping-tag) with `_v` internal method. That it uses undocumented API suggests that it's a hack as well.
2,890,229
first time at stack overflow. I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of *Class*. This doesn't mean that I want to rewrite a *specific* class during run time, but rather I want to make my own conceptualization of what a *Class* is. To be a smidge more specific here, I want to make something that is *like* what people normally call a Class, but I want to follow an "[open world](http://en.wikipedia.org/wiki/Open_world_assumption)" assumption. In the "closed world" of normal Classes, if I declare Poodle to be a subclass of Dog to be a subclass of Animal, then I know that Poodle is not going to also be a type of FurCoat. However, in an open world Class, then the Poodle object I've defined may or may not be and object of type FurCoat and we won't know for sure until I explain that I can wear the poodle. (Poor poodle.) This all has to do with a study I'm doing concerning OWL ontologies. Just so you know, I've tried to find information online, but due to the overloading of terms here I haven't found anything helpful. Super thanks, John UPDATE: I just thought of a good use case for my open-world concept of Class. Perhaps this will provide a better understanding of what I really wish to do. I want to be able to "describe" a Class rather than define it. For instance, I want to be able to say that a Dog is anything that a) has four legs b) barks. Then I want to be able to create an object of unspecified Class, and describe that this object has four legs. At this point the object is still of unspecified type. Then I want to say that the object barks. At this point, the object will be known to be (possibly among other things) a Dog.
2010/05/23
[ "https://Stackoverflow.com/questions/2890229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348056/" ]
I agree with Samir that it just sounds like duck typing. You don't need to care what 'type' an object really 'is' you only need bother with what an object can 'do'. This is true in both Ruby and Python. However if you really are checking the types of classes and you really do need to have a `Poodle` object optionally also be a `FurCoat` at runtime, then the way to do this in Ruby is to mixin a `FurCoat` module into the `Poodle` object, as follows: ``` class Poodle; end module FurCoat; def wear; end; end my_poodle = Poodle.new my_poodle.is_a?(Poodle) #=> true my_poodle.is_a?(FurCoat) #=> false my_poodle.wear #=> NoMethodError # now we mix in the FurCoat module my_poodle.extend(FurCoat) # my_poodle is now also a FurCoat my_poodle.is_a?(Poodle) #=> true (still) my_poodle.is_a?(FurCoat) #=> true my_poodle.wear #=> the wear method now works ``` **EDIT** (due to your updated question): You still do not need to rewrite `Class` to achieve what you want, you just need to monkey-patch the `kind_of?` and `is_a?` (and potentially `instance_of?`) methods on Ruby's `Kernel` module. Since Ruby has open classes this is easily done: ``` class Module def obj_implements_interface?(obj) false end end module Kernel alias_method :orig_is_a?, :is_a? def is_a?(klass) orig_is_a?(klass) || klass.obj_implements_interface?(self) end end ``` And then define for each class (or module) what it means for an object to implement its interface: ``` class Dog def self.obj_implements_interface?(obj) obj.respond_to?(:bark) && obj.respond_to?(:num_legs) && obj.num_legs == 4 end end module FurCoat def self.obj_implements_interface?(obj) obj.respond_to?(:wear) end end ``` Now test it: ``` my_poodle = Poodle.new my_poodle.is_a?(FurCoat) #=> false # now define a wear method on my_poodle def my_poodle.wear; end my_poodle.is_a?(FurCoat) #=> true ```
In Python you can change the inheritence of a class at runtime, but at every given time a class is not a subclass of another one unless declared otherwise. There is no "may or may not" - that would need ternary logic which Python doesn't support. But of course you can write your own "Is-a" and "Has-a" functions to map OWL ontologies to Python classes.
52,407,951
I am trying to pass parameter to URL. For which I am using Angular HttpParams. How do I set date param only if date is not null or undefined? Code: ``` let params = new HttpParams() .set('Id', Id) .set('name', name) if (startDate !== null) { params.set('startDate', startDate.toDateString()); } if (endDate !== null) { params.set('endDate', endDate.toDateString()); } ```
2018/09/19
[ "https://Stackoverflow.com/questions/52407951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341455/" ]
`set` does not mutate the object on which it is working - it returns a *new object* with the new value set. You can use something like this: ``` let params = new HttpParams() .set('Id', Id) .set('name', name) if (startDate != null) { params = params.set('startDate', startDate.toDateString()); } if (endDate != null) { params = params.set('endDate', endDate.toDateString()); } ``` Note how the `params` object is being *reassigned*. Also note the use of `!=` to protect against both `null` and `undefined`.
Instead of using the HttpParams object you can define and mutate your own object and pass it within the http call. ``` let requestData = { Id: Id, name: name } if (startDate) { //I am assuming you are using typescript and using dot notation will throw errors //unless you default the values requestData['startDate'] = startDate } if (endDate) { requestData['endDate'] = endDate } //Making the assumption this is a GET request this.httpClientVariableDefinedInConstructor.get('someEndpointUrl', { params: requestData }) ```
4,362,831
I find that my C++ *header files* are quite hard to read (and really tedious to type) with all the fully-qualified types (which goes as deep as 4 nested namespaces). This is the question (all the answers give messy alternatives to implementing it, but that's *not* the question): ***Is there a strong reason against introducing scoped using-directive in structs and classes in the C++ language*** (while it's permissible to have scoped using-declaration in functions)? e.g. ``` class Foo : public Bar { using namespace System; using namespace System::Network; using namespace System::Network::Win32::Sockets; using Bar::MemberFunc; // no conflict with this // e.g. of how messy my header files are without scoped using-directive void FooBar(System::Network::Win32::Sockets::Handle handle, System::Network::Win32::Sockets::Error& error /*, more fully-qualified param declarations... */); }; ``` Since `namespace` is a keyword, I would've thought it's distinct enough to cause no conflict with the scoped using declaration such as `Bar::MemberFunc`. EDIT: Read the question carefully ---> I've bolded it. Reminder: we're **not** discussing how to improve readability of the example here. Suggesting how scoped using-directive could be implemented (i.e. by means of adding keywords / constructs etc.) in the C++ language is *NOT* an answer (if you could find an elegant way to implement this using existing C++ language standards, then it would of course be an answer)!
2010/12/06
[ "https://Stackoverflow.com/questions/4362831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383306/" ]
Given that `using` declarations at class scope are not inherited, this could work. The name would only be valid inside that class declaration, or inside the declarations of nested classes. But I think it's sort of overloading the concept of a class with an idea that should be larger. In Java and Python individual files are treated in a special way. You can have `import` declarations that inject names from other namespaces into the file. These names will (well, not exactly with Python, but it's too complicated to explain here) only be visible within that file. To me that argues for this sort of ability not being tied to a class declaration, but given a scope of its own instead. This would allow injected names to be used in several class declarations if it made sense, or even in function definitions. Here is an idea I prefer because it allows these things while still giving you the benefits of a class level using declaration: ``` using { // A 'using' block is a sort of way to fence names in. The only names // that escape the confines of a using block are names that are not // aliases for other things, not even for things that don't have names // of their own. These are things like the declarations for new // classes, enums, structs, global functions or global variables. // New, non-alias names will be treated as if they were declared in // the scope in which the 'using' block appeared. using namespace ::std; using ::mynamespace::mytype_t; namespace mn = ::mynamespace; using ::mynamespace::myfunc; class AClass { public: AClass(const string &st, mytype_t me) : st_(st), me_(me) { myfunc(&me_); } private: const string st_; mn::mytype_t me_; }; // The effects of all typedefs, using declarations, and namespace // aliases that were introduced at the level of this block go away // here. typedefs and using declarations inside of nested classes // or namespace declarations do not go away. } // end using. // Legal because AClass is treated as having been declared in this // scope. AClass a("Fred", ::mynamespace::mytype_t(5)); // Not legal, alias mn no longer exists. AClass b("Fred", mn::mytype_t); // Not legal, the unqualified name myfunc no longer exists. AClass c("Fred", myfunc(::mynamespace::mytype_t(5)); ``` This is analogous to declaring a block for local variables in a function. But in this case you are declaring a very limited scope in which you will be changing the name lookup rules.
Maybe namespace alias? ``` namespace MyScope = System::Network::Win32::Sockets; ```
19,952,520
I have a string which is a simple `<a>` element. ``` var str = '<a href="somewhere.com">Link</a>' ``` Which I want to turn into: ``` Link ``` I can remove the `</a>` part easily with `str.replace("</a>", "")`but how would I remove the opening tag `<a href="somewhere.com>`?
2013/11/13
[ "https://Stackoverflow.com/questions/19952520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703569/" ]
Use `unwrap` like ``` $('a').contents().unwrap(); ``` But it work with the elements that are related to DOM.For your **Better** solution try like ``` str = ($(str).text()); ``` See this [**FIDDLE**](http://jsfiddle.net/NATnr/43/)
Since you are using jQuery, you can do it on the fly as follows ``` $('<a href="somewhere.com">Link</a>').text() ```
24,982,476
I have been trying to delete certain rows from the database using a few checkboxes. So far I've managed to echo out the content of the MySQL table but deleting rows through the checkboxes doesn't seem to work. ``` <table class="ts"> <tr> <th class="tg-031e" style='width:1px'>ID</th> <th class="tg-031e">IP address</th> <th class="tg-031e">Date added</th> <th class="tg-031e">Reason</th> </tr> <?php include 'connect.php'; $SQL = "SELECT `ID`, `IPaddress`, `DateAdded`, `Reason` FROM `banned`"; $exec = mysql_query($SQL, $connection); while ($row = mysql_fetch_array($exec)){ echo "<tr class='tg-031h'>"; echo "<td class='tg-031e'><form method='post'><input type='checkbox' name='checkbox' value=" . $row['ID'] . "></form></td>"; echo "<td class='tg-031e'>" . $row['IPaddress'] . "</td>"; echo "<td class='tg-031e'>" . $row['DateAdded'] . "</td>"; echo "<td class='tg-031e'>" . $row['Reason'] . "</td>"; echo "</tr>"; } echo "</table><form method='post'><input name='delete' type='submit' value='Delete'></form>"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) { foreach($_POST['checkbox'] as $id){ $id = (int)$id; $delete = "DELETE FROM banned WHERE ID = $id"; mysql_query($delete); } } ?> ``` I don't get any result as the check does not pass but I don't know what's wrong with it. The query is correct though, so the issue must be with selecting the checkboxes and getting their ID.
2014/07/27
[ "https://Stackoverflow.com/questions/24982476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3849409/" ]
Here, it's tested and working while using `mysqli_` instead of `mysql_` Replace with your own credentials. A few things, your checkbox did need square brackets around the named element as I mentioned in my comment(s), i.e. `name='checkbox[]'` otherwise you would receive an invalid `foreach` argument error. Sidenote: There stands to do a bit of formatting, but it works. ``` <table class="ts"> <tr> <th class="tg-031e" style='width:1px'>ID</th> <th class="tg-031e">IP address</th> <th class="tg-031e">Date added</th> <th class="tg-031e">Reason</th> </tr> <?php $DB_HOST = "xxx"; $DB_NAME = "xxx"; $DB_USER = "xxx"; $DB_PASS = "xxx"; $con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); if($con->connect_errno > 0) { die('Connection failed [' . $con->connect_error . ']'); } $SQL = "SELECT `ID`, `IPaddress`, `DateAdded`, `Reason` FROM `banned`"; $exec = mysqli_query($con,$SQL); echo "<form method='post'>"; while ($row = mysqli_fetch_array($exec)){ echo "<tr class='tg-031h'>"; echo "<td class='tg-031e'><input type='checkbox' name='checkbox[]' value='" . $row[ID] . "'></td>"; echo "<td class='tg-031e'>" . $row['IPaddress'] . "</td>"; echo "<td class='tg-031e'>" . $row['DateAdded'] . "</td>"; echo "<td class='tg-031e'>" . $row['Reason'] . "</td>"; } echo "</tr></table>"; echo "<input name='delete' type='submit' value='Delete'></form>"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) { foreach($_POST['checkbox'] as $id){ $id = (int)$id; $delete = "DELETE FROM banned WHERE ID = $id"; mysqli_query($con,$delete); } } ?> ``` --- Do use [**`mysqli_*` with prepared statements**](http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php), or [**PDO**](http://php.net/pdo) with [**prepared statements**](http://php.net/pdo.prepared-statements) for this. --- **Edit:** `mysql_` version ``` <table class="ts"> <tr> <th class="tg-031e" style='width:1px'>ID</th> <th class="tg-031e">IP address</th> <th class="tg-031e">Date added</th> <th class="tg-031e">Reason</th> </tr> <?php include 'connect.php'; $SQL = "SELECT `ID`, `IPaddress`, `DateAdded`, `Reason` FROM `banned`"; $exec = mysql_query($SQL, $connection); echo "<form method='post'>"; while ($row = mysql_fetch_array($exec)){ echo "<tr class='tg-031h'>"; echo "<td class='tg-031e'><input type='checkbox' name='checkbox[]' value='" . $row[ID] . "'></td>"; echo "<td class='tg-031e'>" . $row['IPaddress'] . "</td>"; echo "<td class='tg-031e'>" . $row['DateAdded'] . "</td>"; echo "<td class='tg-031e'>" . $row['Reason'] . "</td>"; } echo "</tr></table>"; echo "<input name='delete' type='submit' value='Delete'></form>"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) { foreach($_POST['checkbox'] as $id){ $id = (int)$id; $delete = "DELETE FROM banned WHERE ID = $id"; mysql_query($delete); } } ?> ```
You should do something similar to this (semi pseudo): ``` <form method="post"> /begin loop/ echo '<input type="checkbox" name="row[' . $row['ID'] . ']" />'; /end loop/ <input type="submit" /> </form> ``` Then try to put this on the processor page, on top of it: ``` if ( !empty( $_POST ) ) { echo '<pre>' . print_r( $_POST, true ) . '</pre>'; die( 'see? :-)' ); } ``` . . . . Okay here's your code, edited: ``` <?php if ( !empty( $_POST ) ) { echo '<pre>'.print_r( $_POST, true ).'</pre>'; die( 'See?' ); ?> <form method="post"> <table class="ts"> <tr> <th class="tg-031e" style='width:1px'>ID</th> <th class="tg-031e">IP address</th> <th class="tg-031e">Date added</th> <th class="tg-031e">Reason</th> </tr> <?php include 'connect.php'; $SQL = "SELECT `ID`, `IPaddress`, `DateAdded`, `Reason` FROM `banned`"; $exec = mysql_query($SQL, $connection); while ($row = mysql_fetch_array($exec)){ echo "<tr class='tg-031h'>"; echo "<td class='tg-031e'><input type='checkbox' name='row[$row['ID']]'></td>"; echo "<td class='tg-031e'>" . $row['IPaddress'] . "</td>"; echo "<td class='tg-031e'>" . $row['DateAdded'] . "</td>"; echo "<td class='tg-031e'>" . $row['Reason'] . "</td>"; echo "</tr>"; } echo "</table><input name='delete' type='submit' value='Delete'>"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) { foreach($_POST['checkbox'] as $id){ $id = (int)$id; $delete = "DELETE FROM banned WHERE ID = $id"; mysql_query($delete); } } ?> </form> ``` The Deletion query hasn't been fixed yet. Try to fix it yourself :-)
343,732
In our app, we currently live with the legacy of a decision to store all engineering data in our database in SI. I worry that we may run the risk of not having sufficient precision and accuracy in our database or in .NET numeric types. I am also worried that we may see artifacts of floating-point maths (although that is probably a question all to itself). For example, the source data may have been a pressure quantity expressed (and read in from some 3rd party service) in Psi (pounds per square inch). The engineers will have chosen this unit of measure because (for the quantity being expressed) this will tend to give easily-digested, human-readable numbers without requiring scientific notation. When we 'standardise' the number, i.e. when we convert this quantity for our own persistence, we might convert it to Pa (Pascals) which will require either multiplying or dividing the number by some other potentially large number. We often end up storing very large or very small numbers, and worse - we might do further calculations on these numbers. At present we use ORACLE float and System.Double. What do people think of this? **UPDATE** Further research has unearthed [Units of Measure support](http://blogs.msdn.com/andrewkennedy/archive/2008/08/20/units-of-measure-in-f-part-one-introducing-units.aspx) in the forthcoming F# language (in CTP as I write). It seems we'll be able to have F# understand user input such as: ``` 9.81<n/s^2> // an acceleration ``` We'll also be able to create our own derived units and unit systems. [![creating a derived unit for Newtons in F#](https://i.stack.imgur.com/xMfVf.png)](https://i.stack.imgur.com/xMfVf.png) (source: [msdn.com](http://blogs.msdn.com/blogfiles/andrewkennedy/WindowsLiveWriter/UnitsofMeasureinFPartOneIntroducingUnits_A131/image_thumb_11.png))
2008/12/05
[ "https://Stackoverflow.com/questions/343732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5351/" ]
Keep *significant figures* in mind -- the accuracy of the measurement. If the PSI is known to only whole pounds, then after conversion to Pa there are 15 decimals, there is still only one significant figure. Precision is different from accuracy, and performing floating point operations on engineering units need to take this into account during the operations - don't store more precision than the accuracy of the measurement, don't use more precision in a calculation than is known. --- Edit: You might also consider using `NUMERIC(p,s)` where the precision (number of digits) and scale (number of digits to the right of the decimal) can be explicitly specified. If that is not an option, consider persisting the accuracy for a particular measurement so that it may be reported and/or used in calculations.
Well, it depends on how exact you want to be. Remember than when talking about engineering, it isn't enough to just store the number 3.20, because 3.2 isn't the same as 3.20 when it comes to engineering. 3.20 implies higher accuracy than 3.2, which could be *3.15 <= x < 3.25*.
974,031
We've Drupal multi-site (with different domain per site) running with single Drupal 8 code base and Nginx as web-server. Now we wanted to setup Drupal Milti-site with sub-directory for few websites in following format, and "subdirectory" should be case in-sensitive (i.e. site should be accessible with both "subdirectory" or "SubDirectory") : 1. <http://site1.com> (Drupal multi-site, served from "sites/site1.com") 2. <http://site1.com/subdirectory> (Drupal multi-site, served from "sites/site1.com.subdirectory") 3. <http://site2.com> (Drupal multi-site, served from "sites/site2.com") 4. <http://site2.com/subdirectory> (Drupal multi-site, served from "sites/site2.com.subdirectory") We're running these websites on Nginx on CentOS. We've been able to get the sub-site working in following structure (but not with above structure) : 1. <http://site1.com> (Static HTML page) 2. <http://site1.com/subdirectory> (Drupal multi-site) Following are nginx virtual host configuration we're using. NOTE : I've updated nginx config to remove SSL. ``` # VHOST Config. server { listen 80; server_name site1.com; root /var/www/html; index index.php index.html index.htm; # Prevent files from being accessed. location = /robots.txt { allow all; log_not_found off; access_log off; } location ~ /\.htaccess*$ { return 403; } location ~ (^|/)\. { return 403; } location ~ .*\.config$ { return 403; } location ~ /composer.*$ { return 403; } location ~ \..*/.*\.yml$ { return 403; } location / { try_files $uri $uri/ =404; } location @rewrite { try_files $uri /subdirectory/index.php?$query_string; } location /subdirectory/ { try_files $uri $uri/ @rewrite; } location ~ '\.php$|^/update.php' { include /etc/nginx/fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^(.+?\.php)(|/.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; proxy_cache_bypass 1; } } ``` Any help is greatly appreciated.
2019/07/05
[ "https://serverfault.com/questions/974031", "https://serverfault.com", "https://serverfault.com/users/172416/" ]
Answer: there are two parts to this. 1) `private/{process_name}` actually references `/var/spool/postfix/private/{process_name}` which you can check to see if it's there. I discovered this from <https://www.howtoforge.com/postfix-dovecot-warning-sasl-connect-to-private-auth-failed-no-such-file-or-directory> and extrapolated from that path.. ``` [...] (sample code for a process mapping) client { path = /var/spool/postfix/private/auth mode = 0660 user = postfix group = postfix } [...] ``` 2) after that I realized it was a user error (myself), and with `service postfix restart` the process showed.
I had the same problem about transport private/dovecot and I solved it. I didn't change /etc/dovecot.conf nor /etc/postfix/main.cf. I did the following actions: First, execute vi /etc/postfix/master.cf, then: ``` 1) Uncomment: 1.1) submission inet n line with -o lines 2.2) smtps inet n - n - - smtpd with -o lines 2) Add at the end of the file dovecot unix - n n - - pipe flags=DRhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${recipient} 3) Finally, restart postfix service. ```
21,726,948
Would the following code cause any issues?: ``` var a = 1; var a = 2; ``` My understanding is that javascript variables are declared at the start of the scope. For example: ``` var foo = 'a'; foo = 'b'; var bar = 'c'; ``` Is processed as: ``` var foo; var bar; foo = 'a'; foo = 'b'; bar = 'c'; ``` Therefore would my initial code snippet become: ``` var a; a = 1; a = 2; ``` Or would it become: ``` var a; var a; a = 1; a = 2; ``` I understand that declaring a javascript variable twice in the same scope isn't good practice, but I'm more interested in the impact of doing this.
2014/02/12
[ "https://Stackoverflow.com/questions/21726948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370103/" ]
As you said, by twice of more the same var, JavaScript moves that declaration to the top of the scope and then your code would become like this: ``` var a; a = 1; a = 2; ``` Therefore, it doesn't give us any error. This same behaviour occurs to `for` loops (they doesn't have a local scope in their headers), so the code below is really common: ``` for (var i = 0; i < n; i++) { // ... } for (var i = 0; i < m; i++) { // ... } ``` That's why JavaScript gurus like [Douglas Crockford](http://www.crockford.com/) suggest programmers to manually move those declarations to the top of the scope: ``` var i; // declare here for (i = 0; i < n; i++) { // initialize here... // ... } for (i = 0; i < m; i++) { // ... and here // ... } ```
If you initialize the same variable twice, there will be no error on the console but if you are working on some application (like guess my number) and want to reset all the elements to the initial state. All the elements will be set to the initial state but the variable that was initialized twice will stick to its modified value only. Example, If the initial score is 20 and then modified to say some number 15, now reset button is pressed in order to set the value to initial but it will not.
6,778,143
I'm looking for a constant or variable that will provide a public path to my application root. I have got so far as `FULL_BASE_URL` which gives me `http://www.example.com` but I have the added problem of my application being in a sub directory (e.g. `http://www.example.com/myapp/`). Is there any way to get the path like `http://www.example.com/myapp/` in my controller?
2011/07/21
[ "https://Stackoverflow.com/questions/6778143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/851885/" ]
``` $this->base; ``` <http://api.cakephp.org/class/dispatcher>
``` <?php ... $this->redirect( Router::url( "/", true )); ... ?> ``` Router is the static class used by the HtmlHelper::link, Controller::redirect etc. the Router::url method takes a string, or array and matches it to a route. Then it returns the url that matched the route info as a string. If you pass "/" to the Router::url call you get a relative link to the root of your app. If you pass "/" and true to the Router::url call you will prepend the full BASE\_URL to the resulting relative path. This should give you what you need. If not, here is the link to the Router documentation. Try experimenting with the second boolean param - it may or may not work as expected depending on what you read / your own testing. <http://api.cakephp.org/class/router#method-Routerurl>
19,424
In looking at European-designed fighters of the 4th and 4.5th generation, I keep seeing a common design feature; a box-like structure built into the tail, often in the top half or third. Some examples: **Saab Gripen** [![enter image description here](https://i.stack.imgur.com/foBMA.png)](https://i.stack.imgur.com/foBMA.png) --- **Mirage 2000** (this one's more complex and less box-like but the arrangement is very similar) [![enter image description here](https://i.stack.imgur.com/QbJXX.png)](https://i.stack.imgur.com/QbJXX.png) --- **Rafale** [![enter image description here](https://i.stack.imgur.com/MgVG6.png)](https://i.stack.imgur.com/MgVG6.png) --- **Eurofighter Typhoon** (this one looks markedly different, much lower and more like an intake) [![enter image description here](https://i.stack.imgur.com/kXII1.jpg)](https://i.stack.imgur.com/kXII1.jpg) --- **Panavia Tornado** (this one has two main protrusions from the tail, one much like the Typhoon's, the other more like the Gripens or Rafales) [![enter image description here](https://i.stack.imgur.com/sqMHl.jpg)](https://i.stack.imgur.com/sqMHl.jpg) --- **SEPECAT Jaguar** (you know what you're looking at by now) [![enter image description here](https://i.stack.imgur.com/Gtjie.jpg)](https://i.stack.imgur.com/Gtjie.jpg) --- What is this box? My best guess is some sort of avionics/sensor package, maybe RWR/missile warning. What's odd to me is that this box-in-tail arrangement is not seen on any relatively late-model U.S. or Soviet fighter; you'd think if the Europeans were onto something with this placement, the U.S. or Soviets would have tried it out at least once. The F-15 has what I think is an RWR probe on top of the left tail, but the tail itself is pretty clean: [![enter image description here](https://i.stack.imgur.com/0JJbU.jpg)](https://i.stack.imgur.com/0JJbU.jpg) The F-16 does have a boxy construction flaring out at the top of the tail, but the front is clean: [![enter image description here](https://i.stack.imgur.com/2Nvo1.jpg)](https://i.stack.imgur.com/2Nvo1.jpg) The F/A-18 has some trailing-edge bulges but again very clean: [![enter image description here](https://i.stack.imgur.com/isiUa.jpg)](https://i.stack.imgur.com/isiUa.jpg) Su-27, ditto to the F-18 (it does have that big probe between the engines though): [![enter image description here](https://i.stack.imgur.com/sxY1s.jpg)](https://i.stack.imgur.com/sxY1s.jpg) MiG-29, same thing: [![enter image description here](https://i.stack.imgur.com/X4iJ8.jpg)](https://i.stack.imgur.com/X4iJ8.jpg) I could go on but you get the point, Soviet and U.S fighters seem to have passed on whatever this package is in the tail. So, what is it, why is the arrangement limited to European fighters (for the most part) and how do other regional designers accomplish whatever these do?
2015/08/28
[ "https://aviation.stackexchange.com/questions/19424", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/7629/" ]
You're right. It's the ECM/EW antenna/equipment (fairing) in all the aircrafts except Typhoon. This photo shows the details of EW/ECM suite in Gripen. [![Gripen](https://i.stack.imgur.com/lQvy5.jpg)](https://i.stack.imgur.com/lQvy5.jpg) Source: www.w54.biz In Typhoon, it is the engine bleed air heat exchanger. The part is in detail here. [![Typhoon Heat exchanger](https://i.stack.imgur.com/YYkFJ.jpg)](https://i.stack.imgur.com/YYkFJ.jpg) Source: b-domke.de
On the tornado the box at the top of the fin is the RHWR basically to warn the A/C if there is a radar locking on to them. The lower protuberance like the typhoon is an intercooler intake.
42,224,845
I want to insert external JavaScript placed in the folder in WordPress. if I include using script tag it shows "<" expected error below is my code ``` global $wpdb; include("/asset/php/chart4php/inc/chartphp_dist.php"); $p = new chartphp(); $p->data_sql = $wpdb->get_results("select t2.name, count(t1.id) as score from custom_status as t2 left join wpsp_ticket as t1 on t2.name = t1.status group by t2.name"); $p->chart_type = "bar"; // Common Options $p->title = "Category Sales"; $p->xlabel = "Category"; $p->ylabel = "Sales"; $color = array("#1AAF5D","#F2C500","#F45B00","#8E0000","#0E948C"); $p->color = $color[rand(0,4)]; $out = $p->render('c1'); ``` Tried including js files ``` wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'ajax_search' ); wp_register_script( 'chartphp', plugins_url('/asset/php/chart4php/chartphp.js', __FILE__), array('jquery')); ``` wp\_enqueue\_script( 'chartphp' ); Also I want to include 3 move files ``` <script src="/asset/php/chart4php/jquery.min.js"></script> <script src="/asset/php/chart4php/chartphp.js"></script> <link rel="stylesheet" href="/asset/php/chart4php/chartphp.css"> ``` [![enter image description here](https://i.stack.imgur.com/hBRjf.png)](https://i.stack.imgur.com/hBRjf.png)
2017/02/14
[ "https://Stackoverflow.com/questions/42224845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6146203/" ]
Gone through same problem, and here's one firm solution to this. I am assuming you have generated an angular cli project and this is what you have ran into once you've started to code. Solution -------- So what happens is at times angular fails to install all the required dependencies, and does not even update on npm install. Steps ``` 1. Delete existing folders @angular & @angular-devkit inside node_modules folder 2. perform npm install, or yarn ``` And this should work for almost all scenarios. At Least worked for me couple of times.
I too faced this issue, delete the node modules folder and then clean the cache using >npm cache clean --force. Install the node modules again globally using npm install --save @ng-bootstrap/ng-bootstrap npm install --legacy-peer-deps it will work
3,428
I am planning to live with Buddhist monks. But I am hesitant. I am not sure whether I shall be able to live with them without leaving my current religion. I think, if Buddhism is a religion, I am bound to face hard times. Because, it will clash with my current religion. If it is a philosophy, then I dare to attempt. Is Buddhism a religion or philosophy?
2012/08/05
[ "https://philosophy.stackexchange.com/questions/3428", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/-1/" ]
There are two aspects to this question, a theoretical one and a practical one. I shall attempt to address each of these in turn. The theoretical question regards whether Buddhism is to be considered a philosophy or a religion. This is a definitional question; it assumes that we already have rigorous delimitations of the notions of "religion" and "philosophy"; needless to say, we don't. There is a large literature on the subject with regard to Buddhism, which comes to no real conclusion; most people consider Buddhism a religion, but this depends on the assumed definition of "religion." So, at the end of the day, it is not a useful distinction. The more practical question is whether Buddhism would conflict with your prior religious beliefs. Here, the answer is somewhat clearer: as Buddhism rejects the notion that there is anything eternal: any religion that posits an eternal God is going to be in conflict with Buddhism's main tenets. Furthermore, even if your religion posits a God that is not eternal, Buddhism rejects the notion of a creator God. However: the fact that you are planning to live with Buddhist monks while knowing so little about Buddhism itself is worrisome. I'd *strongly* recommend you check out a good, single-volume introduction to Buddhism, such as Peter Harvey's *An Introduction to Buddhism* (published by Cambridge) or Rupert Gethin's *Foundations of Buddhism* (published by Opus) which will give you a good overview of Buddhist doctrine.
One of the epithets of the Buddha is 'teacher of the devas'. There are various accounts of Buddha teaching devas or gods, even Brahman the supreme being/ultimate reality. <https://www.accesstoinsight.org/lib/authors/jootla/wheel414.html> This is a very different dynamic to Western thought, it is not arguing ontic priority, but saying there are insights in this practice for all beings. The bigger picture is, religion and philosophy are terms rooted in Greek thought. Why should we expect a really ancient practice that arose out of an even more ancient culture, to fit neatly into these categories? Consider <https://en.m.wikipedia.org/wiki/Parable_of_the_Poisoned_Arrow> The concern of Buddhism is not with cosmology, or hierarchies of being, or who's book is best, or even who's account of how we got here is best. It is about suffering, the causes of suffering, that it is possible to live in a way that doesn't cause suffering, and how to do that. They are the Four Noble Truths. At core that is all Buddhism is. The poison arrow is in all beings, it is part of the nature of being an arising phenomenon. It's cessation, however that is achieved, for all beings, is Buddhism. Buddhism is compatible, in principle, with all religions and cosmologies. But it is not concerned with things outside the area that it addresses, just like eg. science with areas outside it's conxern. That lack of concern can be interpreted as dismissal, but it shouldn't be. Just like scientific method has no concern with phenomena outside of external observations - yet other areas of consideration exist, so Buddhism is not concerned with phenomena outside of internal observations especially those honed by meditation - but such areas do exist. They are just not important to it's context. Buddhism is about identifying what it is to be awake. What obscures our view of pur being in the world? How do we numb, or distance, or or go to sleep to our experiences? How can we turn that around, be aware, engaged, and awake? In this very moment we decide. Namaste. Edited to add: Please note the nature of faith as viewed in Buddhism <https://www.accesstoinsight.org/lib/authors/thanissaro/faithinawakening.html> It is not unconditional, or unjustified, it does not require a leap from a standing start. But it does require going into the practice with faith in it, that this has seen others 'across the stream'. You might compare this to how science depends on us having faith in other scientists, and the community. But it must also go beyond the material, the practical, the explained, into something deeply and intrinsically personal. That is certainly not in the realm of science.
16,922
In the Book of Job, after Job has went through his first test from Satan there is another gathering in Heaven and, once again, Satan is there ([Job 2:1-3](https://www.biblegateway.com/passage/?search=Job%202%3A1-3&version=NIV)). The result of this gathering is that Job will have to endure another test. This is explained in [Job 2:4-6](https://www.biblegateway.com/passage/?search=Job%202:4-6). In verse 4, Satan replies to God with the following statement. **[Job 2:4](http://www.biblestudytools.com/parallel-bible/passage/?q=job%202:4&t=niv&t2=niv)** (NIV): > > "Skin for skin!" Satan replied." A man will give all he has for his own life. > > But stretch out your hand and strike his flesh and bones, > > and he will surely curse you to your face." > > > What is the meaning of **"skin for skin"?** It would appear that Satan has "sealed the deal" by skin in exchange for skin. In **[Job 19:20](http://biblehub.com/job/19-20.htm)** the word skin is recorded twice, although in a different context: > > I am nothing but **skin** and bones; > > I have escaped by only the **skin** of my teeth. > > > Interestingly, the above verse implies that Job has escaped "death" only by the skin of his teeth. This is after Satan was told by God. **Job 2:6**: > > The Lord said to Satan, "Very well, then, he is in your hands; **but you must spare his life."** > > > [Nine verses with reference to "skin"](http://www.kingjamesbibleonline.org/search.php?word=Skin&page=3&order=&bsec=) are recorded in the Book of Job (scroll down to view).
2015/03/02
[ "https://hermeneutics.stackexchange.com/questions/16922", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/2572/" ]
The first test to which Job is submitted takes everything from Job that is his property. This is the initial challenge posed by Satan: that Job only loves God because of the intelligence and wealth that God has provided Job. After God allows Satan to take Job's property, Job humbly accepts this in stating that God both gives and takes away. Satan then returns to God and states that any man would give their property if only to save their own life. Put in another way, if you are held up at gunpoint and told "your money or your life" you will gladly give up your money, otherwise you lose both. Satan's accusation, being the accuser, is that Job was presented with a similar problem: that while God took his money, Job submitted only to spare his life or flesh. "Skin for skin" is Satan's way of saying that if Job were held to the prospect of losing his life then he would surely curse God. This is the second test to which God permits Satan to submit Job to, which is why God says to Satan that he may do anything to Job BUT take his life. The idea is that Satan may inflict disease on Job's skin to the point that the disease makes Job feel as though he has lost more than his property but the very flesh that carries his soul is doomed. The test posed by Satan is: "if Job gives up his money in your name, would he actually be willing to give up his life without condemning you." The Satanic function in scripture is always aimed at undermining such faith, and Job's story does reappear in that of Jesus in which Jesus does give up his life willfully to the point of loving the other who crucifies him and praising his Father (God) in the process (Why have you forsaken me/It has been accomplished). While Job does not lose his life, the wager of Satan is that men only worship God so long as they receive something in return. However, both Job and Christ have no reservations about what happens to them and prove that it is possible to worship the Name of God to the very end and beyond. This is the significance of "Skin for Skin."
Seems to me that while surely skin means skin (hides and pelts) skin is his heart. We have all felt a darkened heart, then it becomes white as we purify ourselves once again by being faithful through the challenge.
9,027
I'm quite familiar with the theory behind VC-Dimension, but I'm now looking at the recent (last 10 years) advances in statistical learning theory: (local) Rademacher averages, Massart's Finite Class Lemma, Covering Numbers, Chaining, Dudley's Theorem, Pseudodimension, Fat Shattering Dimension, Packing Numbers, Rademacher Composition, and possibly other results / tools that I'm not aware of. Is there a website, survey, collection of articles, or, best of all, a book covering these topics? Alternatively, I'm looking at examples of how to bound the Rademacher average for simple classes, in the same way that people use axis-aligned rectangles to show how to bound VC-dimension. Thanks in advance.
2011/11/19
[ "https://cstheory.stackexchange.com/questions/9027", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/4828/" ]
This was a recently taught course. <http://www.cs.huji.ac.il/~shais/Handouts.pdf>. I haven't carefully read through it, but chapter 7 has material on Rademacher Complexities. Hope it helps.
The book by [Cesa-Bianchi and Lugosi](http://rads.stackoverflow.com/amzn/click/0521841089) has much of the modern aspects of generalization bounds and learning theory.
330,024
This is a quick question. When people write $f:I\to J$ for instance, does $J$ need to be the range of $f$ or can it be any set containing the range of $f?$ For example, is $g(x)=\pi$ an $\mathbb{R}\to\mathbb{R}$ function?
2013/03/14
[ "https://math.stackexchange.com/questions/330024", "https://math.stackexchange.com", "https://math.stackexchange.com/users/64804/" ]
$f:X\to\Bbb R$ simply means that all of our function values are real. It **doesn't** mean that all real values are obtained by our function. ($\Bbb R$ in this case is called a *[codomain](http://en.wikipedia.org/wiki/Codomain)* for our function $f$.) Your example $g$ is indeed an $\Bbb R\to\Bbb R$ function (so long as we require that $x$ is real, and allow $x$ to take on any real value), even though it's certainly not the case that all real values are obtained by $g$.
condensed from comments received : $$f:X \to Y \equiv \forall x \in X \quad \exists y \in Y \text{ such that } f(x)=y$$ $$f:X \to Y \land f\_\text{ onto/surjective} \equiv \forall y \in Y, \, \exists x \in X \text{ such that } f(x)=y$$ $$f:X \to Y \land f\_\text{ 1-1/bijective} \equiv \forall x \in X \quad !\exists y \in Y \text{ such that } f(x)=y$$
73,253,209
I have two dataframes, like below **rows\_df** ``` Id Location Age 0 0 30 1 1 US 20 2 2 ``` **requiredCols\_df** ``` RequiredColumn 0 Location ``` `requiredCols_df` specifies which column is required in `rows_df`. In this example, `Location` is required, `Age` is optional in `rows_df`. I want to filter the `rows_df` based on the `requiredCols_df`. So there will be two resulting dataframes. One contains rows that have the required columns, and the other dataframe contains rows that don't have any required columns. **Expected Result** Rows matched ``` Id Location Age 1 1 US 20 ``` Rows don't match ``` Id Location Age 0 0 30 2 2 ``` Please note that: 1.The `rows_df` contains more than two columns, e.g. 10-30 columns. 2 The `requiredCols_df` contains more than one row. 3 Please note that `Location` contains a ' ' (empty space(s)) in row `0`, and a `null` (empty) in row `2`. ``` rows_df = pd.DataFrame({'Id':['0','1','2'], 'Location': [' ', 'US', None], 'Age':['30','20','']}) ``` column names below specify which column in `rows_df` must be not empty ``` requiredCols_df = pd.DataFrame([['Location']], columns= ['RequiredColumn']) ``` **4 Update:** Both the resulting DataFrame contain the original non-changed values. I can do this with a loop, but I want to see if there is a better solution.
2022/08/05
[ "https://Stackoverflow.com/questions/73253209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665335/" ]
If you correct those to be true nans... ``` req_cols = requiredCols_df.RequiredColumn rows_df[req_cols] = rows_df[req_cols].replace([r'^\s*$', '', None], np.nan, regex=True) Id Location Age 0 0 NaN 30 1 1 US 20 2 2 NaN ``` Then this is simple: ``` matched = rows_df.dropna(subset=req_cols) not_matched = rows_df[~rows_df.eq(matched).all(axis=1)] print(matched) print(not_matched) # Output: Id Location Age 1 1 US 20 Id Location Age 0 0 NaN 30 2 2 NaN ``` --- Generalized: ``` rows_df = rows_df.replace([r'^\s*$', '', None], np.nan, regex=True) matched = rows_df.dropna(subset=requiredCols_df.RequiredColumn) not_matched = rows_df[~rows_df.isin(matched).all(axis=1)] ```
Assuming you don't have a *tremendous* count of columns are there, this seems like a task for a loop ```py df_result = rows_df for column in requiredCols_df["RequiredColumn"]: df_result = df_result[df_result[column].notnull()] ```
6,446,132
Quite simply: I'm using Smarty and the `|capitalize` modifier. It works fine, but when I pass any word with `l` in it, it capitalizes it, even if it's not at the beginning of the word. What why? **EDIT**: Same happens with `p`. Test: ``` {"abcdefghijklmnopqrstuvwxyz"|capitalize} {"aaal aala alaa laaa"|capitalize} {"aaap aapa apaa paaa"|capitalize} ``` Output: ``` AbcdefghijkLmnoPqrstuvwxyz AaaL AaLa ALaa Laaa AaaP AaPa APaa Paaa ```
2011/06/22
[ "https://Stackoverflow.com/questions/6446132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154502/" ]
You could also use PHP's [ucfirst](http://de.php.net/manual/en/function.ucfirst.php) function ``` {"aaal aala alaa laaa"|@ucfirst} ``` This will result in > > Aaal aala alaa laaa > > >
Smarty primarily relies on [`ucfirst()`](http://us2.php.net/manual/en/function.ucfirst.php) which is affected by the current locale set in PHP. I have been unable to find information on exactly how this affects the capitalization functions (ucfirst, strtolower, strtoupper, etc), but you can try setting your locale to `en_US.UTF-8` (what works on my server) and see how that affects the output. view locale: ``` var_dump(setlocale(LC_CTYPE, null)); ``` change locale: ``` setlocale(LC_CTYPE, "en_US.UTF-8"); ``` ### Update Some research leads to a few archives where a customer modifier is written to either pick the local for the modifier or a custom function to set the locale from the template file. [Source 1](http://osdir.com/ml/php.smarty.general/2002-10/msg00153.html) [Source 2](http://smarty.incutio.com/?page=SetLocalePlugin) I haven't been able to reproduce this. Could it be the font you are using (some tail the `l`)? Do you have code examples? With Smarty v2 ``` {assign value="let go" var="go"} {$go|capitalize} <br/> {assign value="allow me" var="me"} {$me|capitalize} ``` Outputs ``` Let Go <br/> Allow me ```
26,290,117
How do I interrupt Socket.Select in c#? In C I used the "self pipe" trick or "signals". In C# I know I could create a socket pair and interrupt the select, but it doesn't seem very clean. Is there anything better I could do to interrupt a select call in c#.
2014/10/10
[ "https://Stackoverflow.com/questions/26290117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263867/" ]
To solve this myself, I am just calling `Socket.Close()` on the sockets I listed in my `Socket.Select()` call. This interrupts the select with an exception. I would use the socket pair trick, but I can’t find the equivalent to `pipe()` in .net. I have a feeling that I read somewhere that the way to do this on Windows is to connect to a loopback via TCP (especially because WSA’s `select()` doesn’t support “normal” file descriptors anyway). But that seems even dirtier and more prone to bad things happening than just closing the listening socket from a different thread and having `Socket.Select()` be interrupted with an exception.
I was having the same problem. The best option is run select on different thread. This helped me get rid of the exception error.
3,158,942
so I'm new to using WPF and can't figure out how to make an easy way to have multiple columns of controls that can be added / subtracted easily and still have it scrollable. So for example (my situation), I have two text boxes and a button that need to be added for however many "items" there are. I would want these together in a 3 column layout and all scroll with the same scroll bar. The best case result would be something like multiple stack panels (in my case 3) filled with an arbitrary amount of controls, that all scroll with the same scroll bar. Since this seems not to work, what do I do instead? Much appreciated, no matter how inane my questions are you guys are always so helpful.
2010/07/01
[ "https://Stackoverflow.com/questions/3158942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241116/" ]
``` <ScrollViewer ...> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <StackPanel Grid.Column="0" ...> ... </StackPanel> <StackPanel Grid.Column="1" ...> ... </StackPanel> <StackPanel Grid.Column="2" ...> ... </StackPanel> </Grid> </ScrollViewer> ```
Have you tried putting all three StackPanels into a `ScrollViewer`?
25,589,113
In my MongoDB, I have a student collection with 10 records having fields `name` and `roll`. One record of this collection is: ``` { "_id" : ObjectId("53d9feff55d6b4dd1171dd9e"), "name" : "Swati", "roll" : "80", } ``` I want to retrieve the field `roll` only for all 10 records in the collection as we would do in traditional database by using: ``` SELECT roll FROM student ``` I went through many blogs but all are resulting in a query which must have `WHERE` clause in it, for example: ``` db.students.find({ "roll": { $gt: 70 }) ``` The query is equivalent to: ``` SELECT * FROM student WHERE roll > 70 ``` My requirement is to find a single key only without any condition. So, what is the query operation for that.
2014/08/31
[ "https://Stackoverflow.com/questions/25589113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2560301/" ]
Try the following query: ``` db.student.find({}, {roll: 1, _id: 0}); ``` And if you are using console you can add pretty() for making it easy to read. ``` db.student.find({}, {roll: 1, _id: 0}).pretty(); ``` Hope this helps!!
Not sure this answers the question but I believe it's worth mentioning here. There is one more way for selecting single field (and not multiple) using `db.collection_name.distinct();` e.g.,`db.student.distinct('roll',{});` Or, 2nd way: Using `db.collection_name.find().forEach();` (multiple fields can be selected here by concatenation) e.g., `db.collection_name.find().forEach(function(c1){print(c1.roll);});`
29,794,897
I am new to angular js. I have two ng-controller in two Html page. I want to share data from one controller into another controller. Here is the service i have created: ``` app.service('sharedProperties', function() { var stringValue = 'test string value'; var objectValue = { data: 'test object value' }; return { getString: function() { return stringValue; }, setString: function(value) { stringValue = value; }, getObject: function() { return objectValue; } } }); ``` Here is controller1: ``` app.controller('FirstCtrl',function($scope,sharedProperties){ sharedProperties.setString("Hi"); }); ``` Here is controller2: ``` app.controller('SeccondCtrl',function($scope,sharedProperties){ window.alert(sharedProperties.getString()); }); ``` Instead of getting alert containing string 'Hi' i am getting 'test string value'. **NB. i am using FirstCtrl and SeccondCtrl in two HTML file. And after setting string from FristCtrl i redirect to the second HTML file .**
2015/04/22
[ "https://Stackoverflow.com/questions/29794897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2040589/" ]
I've created [jsfiddle](https://jsfiddle.net/kiyanov/5tnc8aod/1/) and it works fine. ``` app.controller('FirstCtrl',function($scope,sharedProperties){ $scope.set = function(){ sharedProperties.setString("Hi"); } }); app.controller('SeccondCtrl',function($scope,sharedProperties){ $scope.get = function(){ window.alert(sharedProperties.getString()); } }); ```
**Service have this reference you write your service method as per below** ``` app.service('sharedProperties', function() { var stringValue = 'test string value'; var objectValue = { data: 'test object value' }; this.getString: function() { return stringValue; } this.setString: function(value) { stringValue = value; } this.getObject: function() { return objectValue; } }); ```
20,834,648
Suppose I have a chain of local git branches, like this: ``` master branch1 branch2 | | | o----o----o----A----B----C----D ``` I pull in an upstream change onto the master branch: ``` branch1 branch2 | | A----B----C----D / o----o----o----o | master ``` Now I rebase branch1, giving me this: ``` branch2 | A----B----C----D / o----o----o----o----A'---B' | | master branch1 ``` Note that because of rebasing branch1, commits A and B have been rewritten as A' and B'. Here's my problem: now I want to rebase branch2. The obvious syntax is `git rebase branch1 branch2`, but that definitely does not work. What I want it to do is just reapply C and D on top of branch1, but instead it tries to reconcile A and A' and it considers them conflicting. This does work: ``` git rebase --onto branch1 branch2^^ branch2 ``` This assumes I know that branch2 has exactly 2 commits beyond the previous branch1 ref. Since `git rebase --onto` works, is there a 1-line git command that will rebase branch2 on top of a newly-rebased branch1, in a way that I don't have to know exactly how many commits were part of branch2? (I want to specify some magic ref instead of branch2^^ for the middle argument.) Or is there some other approach I'm overlooking? I would be most interested in a solution that scales well to extreme cases, not just two branches - suppose I've got something more like 5 local branches, all chained on one another, and I want to rebase all of them together.
2013/12/30
[ "https://Stackoverflow.com/questions/20834648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7193/" ]
This question is a subset of [Modify base branch and rebase all children at once](https://stackoverflow.com/questions/42181045/modify-base-branch-and-rebase-all-children-at-once/58864618#58864618) I recently started using [git-chain](https://github.com/Shopify/git-chain) which is a tool to solve this problem. Basically you specify a chain ``` git chain setup -c myfeature master branch1 branch2 ``` Once this chain is set up, you can pull in commits from `master`, then you can run `git chain rebase -c myfeature` and the tool figures out all the refs and rebases everything nicely for you. As an added benefit, it also calculates and handles any amendments or new commits to `branch1` and `branch2`.
Git 2.38 has a new flag `--update-refs` to solve this exact problem. In your example: ``` git rebase --update-refs master ``` Example: ``` $ git checkout branch2 $ git log --decorate --all --oneline --graph * 5b08e54 (master) 4 * 6790fdc 3 | * ee84471 (HEAD -> branch2) branch commit 4 | * 9da7c93 branch commit 3 | * c250fc6 (branch1) branch commit 2 | * bd5f222 branch commit 1 |/ * 2ec36a0 2 * ecce5ff 1 * 8bb07ae (tag: root) root $ git rebase --update-refs master Successfully rebased and updated refs/heads/branch2. Updated the following refs with --update-refs: refs/heads/branch1 $ git log --decorate --all --oneline --graph * b37f0c7 (HEAD -> branch2) branch commit 4 * c20fc6f branch commit 3 * a231606 (branch1) branch commit 2 * 0e81768 branch commit 1 * 5b08e54 (master) 4 * 6790fdc 3 * 2ec36a0 2 * ecce5ff 1 * 8bb07ae (tag: root) root ``` Notice: I only rebased the "last" branch in the chain (branch2) onto the new base (master), and the in-between branches (branch1) got moved along automatically.
5,599,874
How can I check for duplicates before inserting into a table when inserting by select: ``` insert into table1 select col1, col2 from table2 ``` I need to check if table1 already has a row with table1.col1.value = table2.col1.value, and if yes, then exclude that row from the insert.
2011/04/08
[ "https://Stackoverflow.com/questions/5599874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406322/" ]
``` INSERT INTO table1 SELECT t2.col1, t2.col2 FROM table2 t2 LEFT JOIN table1 t1 ON t2.col1 = t1.col1 AND t2.col2 = t1.col2 WHERE t1.col1 IS NULL ``` **Alternative using except** ``` INSERT INTO @table2 SELECT col1, col2 FROM table1 EXCEPT SELECT t1.col1, t1.col2 FROM table1 t1 INNER JOIN table2 t2 ON t1.col1 = t2.col1 AND t1.col2 = t2.col2 ``` **Alternative using Not Exists** ``` INSERT INTO table2 SELECT col1,col2 FROM table1 t1 WHERE NOT EXISTS( SELECT 1 FROM table2 t2 WHERE t1.col1 = t2.col1 AND t1.col2 = t2.col2) ```
You can simply add IGNORE into your insert statement. e.g ``` INSERT IGNORE INTO table1 SELECT col1, col2 FROM table2 ``` This is discussed [here](https://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql)
134,167
While solving the electrostatic field for a dielectric in an electric field, we take the potential at origin to not blow and thus, we eliminate the inverse powers of r in the expression for general potential for azimuthal symmetry. Why is that valid :- we can have bound charge inside the sphere at r = 0 and which can contribute to infinite potential at the origin by the usual electrostatic laws. Does this depend on whether the sphere is homogeneous or inhomogeneous ? There are potentials which we do blow up in our models at the origin, is there any specific constraint in blowing up the potentials inside the materials when we are considering only limited set of ideal conditions and nothing pertaining to ionization or maximum electric field for stability of the system has been mentioned.
2014/09/06
[ "https://physics.stackexchange.com/questions/134167", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/-1/" ]
The validity of setting the electrostatic potential to a certain value at a certain point comes from the fact that the electrostatic potential, like the potential, is defined up to a constant. The numerical value of this constant does not change the physics, but can sometimes make expressions nicer. The potential should usually be finite everywhere, except in some limiting situations. The case of a point charge is one of such, because to have a point (of infinitesimal dimensions by definition) carrying a finite charge would require an infinite charge density, leading to an infinite energy and to an infinite electrostatic potential. You can avoid these pathologies defining the electrostatic potential by its value at infinity (instead that by its value at the origin where the charge is), and considering the resulting expression $-Q/r$ to be valid only outside the point charge, i.e. for $r \neq 0$. In this way we ignore the immediate proximities of the charge, meaning that we are not interested in probing its internal structure. When this is not true, and we care about how the charge is distributed in the body, the point charge model simply is no more suitable and something else should be used.
When you have a uniformly charged dielectric sphere, there is no finite charge at the origin. Instead, you have uniform charge *density*, so the total charge inside of a sphere of radius $r$ is $$q = \frac43 \pi r^3 \rho$$ where $\rho$ is the volumetric charge density, $\rho = \frac{Q}{V}$ where $Q$ is total charge and $V = \frac43\pi R^3$ is total volume. Now you can see that as you approach the origin, the equation does not "blow up" - the force that you would experience goes down linearly to zero, instead of going asymptotically to infinity. As long as you don't treat charge as a finite point charge (where you have a number in the numerator that remains finite, and a denominator that goes to zero) but instead as a charge *density* (which doesn't have to be uniform as long as it doesn't have a delta function anywhere) the above analysis (or a variation) is valid.
49,146
I am asking this question to see if mid-air collisions of drones can be prevented using simple analog sensors. Can an ultrasonic sensor mounted on a drone pick up another drone strongly enough to sense and avoid it? I know that the sensor is range limited so the aircraft cannot be flying towards each other very fast, but to even do any sense and avoiding, can this sensor work? Or does the drone not provide enough of a return? Also, could the range of sensor be increased if both drones emitted ultrasonic energy to be picked up on the sensor more strongly at a distance?
2018/03/03
[ "https://aviation.stackexchange.com/questions/49146", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/11161/" ]
There is no hard-and-fast rule for what to do in an emergency, including a medical emergency involving a passenger. The decision also is not an instantaneous one; while the flight crew evaluates and works on the medical emergency, the plane is constantly getting closer to the destination. I suspect that when 3 hours from help, an extra 10, 20, or 30 minutes is unlikely to definitively change the outcome, and the pilots would likely choose to continue to the destination. If returning is 45 minutes or more closer than continuing, then returning to the origin starts to look pretty good. The facilities available at each destination might factor into the decision as well: If they left Chicago OHare, and are enroute Port-a-Prince, Haiti, then its very likely that there are better medical services at Chicago. Ultimately, its a judgement call dependent on many, many factors.
Just as a supplement to @abelenky's good answer, there are some things to be taken into account that haven't yet been mentioned. First, if you've been flying with a tailwind for 3.0 hours and the winds would be roughly the same, it's going to take you more than 3.0 hours to fly back along the same route, possibly a lot more than 3 hours. Second, technically you can't just reverse course without getting a clearance to do so. You have to contact ATC and negotiate the course reversal. That could take several minutes, possibly a lot more depending on communications. The captain could, of course, decide to reverse immediately and negotiate the clearance later, but he would be risking a possibly dangerous reduction in separation from other traffic, and I doubt whatever the governing authority was would take kindly to risking a couple of plane loads of people for the sake of one individual. Then, there can be special circumstances. For example, if you were flying Indonesian Muslim pilgrims to Mecca on a Hajj charter. I can't speak to current policy as I retired in 1999, but back then the practice was that once you were in the air, you did not turn back or divert for medical emergencies. There was always a doctor on board, and technically he could request a captain to divert to the nearest suitable, but in practice that was never done. It was expected that there would be occasional deaths, and we carried body bags for that contingency.
36,979,259
This is the code: ``` #!/usr/bin/env python #Import the datetime from datetime import datetime import re #Create two datetime object for limit 1 and limit 2 as dt1 and dt2 respectively dt1 = datetime.strptime("01:00:00","%H:%M:%S").time() dt2 = datetime.strptime("04:59:59","%H:%M:%S").time() #Create a compiler for regular expression init_re = re.compile(r'(INIT)') time_re = re.compile(r'(\d+:\d+:\d+)') # read line from test.log file for line in open("test.log", "r"): match = time_re.search(line) #Search time format for each line if match: matchtime = match.group(1) dt_match = datetime.strptime( matchtime, '%H:%M:%S').time() #Time formmat match if dt_match >= dt1 and dt_match <= dt2: match1 = init_re.search(line) #search INIT format if match1: matchinit = match1.group(0) print match.string.strip() ``` Below is a partial part of the log file: > > 2015-12-15 00:51:01,904 INFO restser.py 113 [INIT] [netkv\_restser: peek] [req\_id: f0aa7ab5-6192-4231-93cd-82a53936a072] [request: {u'key\_space': u'martech\_user\_index', u'table\_name': u'nettopic', u'key': 9569}] > > > I want output like this: ``` [Date: ] [Time: ] [INIT] [netkv_restser: ] [req_id: ] ``` Example: ``` [Date:2015-12-15 ] [Time:00:51:01,904 ] [INIT] [netkv_restser:peek ] [req_id:f0aa7ab5-6192-4231-93cd-82a53936a072 ] ``` Note: If you are nice enough to edit the code, be kind enough to provide solutions. I don't wanna sound rude but it irks me. NOTE: I am using Python 2.7.6.
2016/05/02
[ "https://Stackoverflow.com/questions/36979259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6255840/" ]
Sometimes you just have to call it and find a different solution. I couldnt understand why it wouldn't appear, (so indeed, it may have not been in that bootstrap version) so instead, i wrote my own tooltip with a bit of simple css. It's not the solution I wanted, but it solved my problem in the end. Intrested? ``` .tooltip { position: relative; display: inline-block; font-size: 16px; } .tooltip .tooltiptext { visibility: hidden; background-color: black; color: #fff; text-align: center; padding: 5px 0; border-radius: 6px; position: absolute; z-index: 1; width: 120px; top: 100%; left: 50%; margin-left: -60px; font-size: 12px; } .tooltip:hover .tooltiptext { visibility: visible; } ``` And the modified code ``` <a href="tel:<?php echo $phone; ?>" class="tooltip"> <span class="tooltiptext"><?php echo $phone; ?></span> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-phone fa-stack-1x"></i> </span> </a> ```
Try using `data-original-title` instead of `title`
6,489,750
i'm need that mysql auto increment field data is start with alpha charecters and continue.. For ex id starts with 1 means i want to start that AB1, AB2, AB3,
2011/06/27
[ "https://Stackoverflow.com/questions/6489750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/816908/" ]
Yes, you can run PHP on IIS. <http://php.iis.net/>
I put a test application PHP with MS Access database on an ASP.net hosting. i treated it like a classic ASP application, it worked just fine. you just need to add "index.php" as a default document. update (1) i tested it locally on a vm, you may need to disable impersonation and add the following to web.config ``` <configuration> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> </system.webServer> </configuration> ```
74,605,940
For the last week I have been trying to get cx\_oracle installed and working. I started with an Oracle 19 appliance which is on Oracle Linux 7. I used the official oracle site to install cx\_oracle as listed below. The install seems to have worked fine, but when I try to import the module, it is not found. I checked all the env variables, the path, spend countless hours trying to get this work, what am I missing? If anyone could please point me to my mistake, I would really appreciate it. Here are all the steps I have taken so far: Installing cx\_Oracle for Python 3 To install cx\_Oracle for Python 3 on Oracle Linux 7: $ sudo yum -y install oraclelinux-developer-release-el7 $ sudo yum -y install oracle-instantclient-release-el7 $ sudo yum -y install python36-cx\_Oracle <https://yum.oracle.com/oracle-linux-python.html#cx_OraclePython3FromLatest> ``` [oracle@localhost tmp]$ yum list installed |grep cx python36-cx_Oracle.x86_64 8.3.0-1.el7 @ol7_developer [oracle@localhost tmp]$ yum list installed |grep instant oracle-instantclient-basic.x86_64 21.8.0.0.0-1 @ol7_oracle_instantclient21 oracle-instantclient-release-el7.x86_64 [oracle@localhost ~]$ yum search cx_oracle Loaded plugins: langpacks, ulninfo ============================================================= N/S matched: cx_oracle ==============================================================cx_Oracle-12c-py27.x86_64 : Python interface to Oracle cx_Oracle-py27.x86_64 : Python interface to Oracle python-cx_Oracle.x86_64 : Python interface to Oracle python-cx_Oracle-12c.x86_64 : Python interface to Oracle python36-cx_Oracle.x86_64 : Python interface to Oracle Name and summary matches only, use "search all" for everything. [oracle@localhost ~]$ sudo yum install python36-cx_Oracle.x86_64 Loaded plugins: langpacks, ulninfo Package python36-cx_Oracle-8.3.0-1.el7.x86_64 already installed and latest version Nothing to do [oracle@localhost ~]$ python3 Python 3.11.0 (main, Nov 26 2022, 17:15:54) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import cx_oracle Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'cx_oracle' >>> quit() [oracle@localhost ~]$ python Python 2.7.5 (default, Jul 1 2022, 08:35:16) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_oracle Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named cx_oracle >>> quit() [oracle@localhost ~]$ python --version Python 2.7.5 [oracle@localhost ~]$ python3 --version Python 3.11.0 [oracle@localhost ~]$ which python /usr/bin/python [oracle@localhost ~]$ which python3 /usr/local/bin/python3 [oracle@localhost ~]$ echo $PATH /home/oracle/Desktop/Database_Track/coffeeshop:/home/oracle/java/jdk1.8.0_201/bin:/home/oracle/bin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/datamodeler:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/bin:/home/oracle/.local/bin:/home/oracle/bin [oracle@localhost ~]$ echo $ORACLE_BASE /u01/app/oracle [oracle@localhost ~]$ echo $ORACLE_HOME /u01/app/oracle/product/version/db_1 [oracle@localhost ~]$ echo $LD_LIBRARY_PATH /usr/lib/oracle/21/client64/lib/ [oracle@localhost ~]$ echo $LD_LIBRARY_PATH64 /usr/lib/oracle/21/client64/lib/ [oracle@localhost ~]$ env XDG_SESSION_ID=2 HOSTNAME=localhost.localdomain SELINUX_ROLE_REQUESTED= TERM=xterm-256color SHELL=/bin/bash HISTSIZE=1000 SSH_CLIENT=192.168.59.1 65195 22 SELINUX_USE_CURRENT_RANGE= SSH_TTY=/dev/pts/2 USER=oracle LD_LIBRARY_PATH=/usr/lib/oracle/21/client64/lib/ TWO_TASK=ORCL LS_COLORS=rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45: LD_LIBRARY_PATH64=/usr/lib/oracle/21/client64/lib/ GNOME_CHECK=1 ORACLE_BASE=/u01/app/oracle MAIL=/var/spool/mail/oracle PATH=/home/oracle/Desktop/Database_Track/coffeeshop:/home/oracle/java/jdk1.8.0_201/bin:/home/oracle/bin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/datamodeler:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/bin:/home/oracle/.local/bin:/home/oracle/bin PWD=/home/oracle JAVA_HOME=/home/oracle/java/jdk1.8.0_201 LANG=en_US.UTF-8 SELINUX_LEVEL_REQUESTED= HISTCONTROL=ignoredups SHLVL=1 HOME=/home/oracle LOGNAME=oracle JAVAENV=true XDG_DATA_DIRS=/home/oracle/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share SSH_CONNECTION=192.168.59.1 65195 192.168.59.130 22 LESSOPEN=||/usr/bin/lesspipe.sh %s TMZ=GMT XDG_RUNTIME_DIR=/run/user/1000 ORACLE_HOME=/u01/app/oracle/product/version/db_1 _=/usr/bin/env ```
2022/11/28
[ "https://Stackoverflow.com/questions/74605940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233309/" ]
You now seem to have multiple cx\_Oracle packages installed, which isn't helping untangle your problems (and not something I want to replicate). To start from scratch with a clean OL7 image, follow the "Installing Python 3 from the Oracle Linux 7 Latest Repository" section of <https://yum.oracle.com/oracle-linux-python.html>: ``` $ sudo yum -y install python3 ``` and then the "Installing cx\_Oracle for Python 3" section: ``` $ sudo yum -y install oraclelinux-developer-release-el7 $ sudo yum -y install oracle-instantclient-release-el7 $ sudo yum -y install python36-cx_Oracle ``` You can then use the driver: ``` cjones@localhost:~$ python3 Python 3.6.8 (default, Nov 18 2021, 10:07:16) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle >>> cx_Oracle.version '8.3.0' ``` Update: as commented on by Anthony in another answer, make sure you use the correct case for `import cx_Oracle`. If you install a version of Python or cx\_Oracle that is not listed on the page, you will need to install cx\_Oracle using 'pip' packages from PyPI instead of RPMs. Note that cx\_Oracle on PyPI currently has prebuilt packages up to Python 3.10. Some other notes: * You are setting ORACLE\_HOME and LD\_LIBRARY\_PATH. You should never set ORACLE\_HOME with Instant Client. And you don't need to set LD\_LIBRARY\_PATH when using Instant Client 19 (or later) RPM packages. * cx\_Oracle 8 is only available for Python 3 **The latest version of cx\_Oracle is now called python-oracledb**, see the [release announcement](https://cjones-oracle.medium.com/open-source-python-thin-driver-for-oracle-database-e82aac7ecf5a). To install python-oracledb on a clean OL7 machine: ``` sudo yum -y install python3 sudo yum -y install oraclelinux-developer-release-el7 sudo yum -y install python3-oracledb ``` You can then use it immediately in the new Thin mode without needing Oracle Instant Client: ``` cjones@localhost:~$ python3 Python 3.6.8 (default, Nov 18 2021, 10:07:16) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import oracledb >>> oracledb.version '1.1.1' ``` (There are no casing or underscore issues with this new name!!) To use python-oracledb in Thick mode, install Instant Client manually: ``` sudo yum -y install oracle-instantclient-release-el7 sudo yum -y install oracle-instantclient-basic ``` The python-oracledb RPMs are currently only available for the basic Python 3 version. If you have other versions, then install python-oracledb with pip, see [the python-oracledb instructions Installing python-oracledb on Linux](https://python-oracledb.readthedocs.io/en/latest/user_guide/installation.html#installing-python-oracledb-on-linux).
The name of the module is `cx_Oracle`, not `cx_oracle`. Note the case!
33,015,751
I use the following line to generate Poisson random numbers: ``` Application.Run("Random", "", 1, 100, 5, , 34) ``` this produces 100 random numbers with Lambda (34) in an excel sheet. I would like to save the output into a variable instead of sheet. I tried ``` X=Application.Run("Random", "", 1, NSim, 5, , 34) ``` I don't get any error but nothing is saved in "X". Could you please help me how I can save the result in a variable. Thanks
2015/10/08
[ "https://Stackoverflow.com/questions/33015751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5423086/" ]
What actually seems to happen is the real [stack overflow](https://en.wikipedia.org/wiki/Stack_overflow). You have a recursive function and it goes into infinite recursion, so at some time moment it runs out of stack.
The better question is *what do you expect to happen with this code?* You've got an infinitely recursive function that continually adds to the standard output stream. Of course you're getting an error- you're continually allocating "WORK" strings onto your stack, which is going to overflow. I'm not sure that happens when you push too much data into the standard output stream, but that can't be healthy either.
10,385,278
Hello I have this code to conditionally render components in my page: ``` <h:commandButton action="#{Bean.method()}" value="Submit"> <f:ajax execute="something" render="one two" /> </h:commandButton> <p><h:outputFormat rendered="#{Bean.answer=='one'}" id="one" value="#{messages.one}"/></p> <p><h:outputFormat rendered="#{Bean.answer=='two'}" id="two" value="#{messages.two}"/></p> ``` It gets the answer and renders the component but in order to see it on my page, I need to refresh the page. How can I fix this problem? Any suggestions?
2012/04/30
[ "https://Stackoverflow.com/questions/10385278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272859/" ]
The JSF component's `rendered` attribute is a server-side setting which controls whether JSF should generate the desired HTML or not. The `<f:ajax>` tag's `render` attribute should point to a (relative) client ID of the JSF-generated HTML element which JavaScript can grab by `document.getElementById()` from HTML DOM tree in order to replace its contents on complete of the ajax request. However, since you're specifying the client ID of a HTML element which is never rendered by JSF (due to `rendered` being `false`), JavaScript can't find it in the HTML DOM tree. You need to wrap it in a container component which is *always* rendered and thus *always* available in the HTML DOM tree. ``` <h:commandButton action="#{Bean.method()}" value="Submit"> <f:ajax execute="something" render="messages" /> </h:commandButton> <p> <h:panelGroup id="messages"> <h:outputFormat rendered="#{Bean.answer=='one'}" value="#{messages.one}"/> <h:outputFormat rendered="#{Bean.answer=='two'}" value="#{messages.two}"/> </h:panelGroup> </p> ``` --- **Unrelated** to the concrete problem, you've there a possible design mistake. Why would you not just create a `#{Bean.message}` property which you set with the desired message in the action method instead, so that you can just use: ``` <h:commandButton action="#{Bean.method()}" value="Submit"> <f:ajax execute="something" render="message" /> </h:commandButton> <p> <h:outputFormat id="message" value="#{Bean.message}" /> </p> ```
``` style="visibility: #{questionchoose.show==false ? 'hidden' : 'visible'}" ```
25,950,620
i get error "$digest already in progress" when set the restrict attribut to 'E'. here the directive code: ``` mainApp.directive('scoreDisplay',[ function() { return { scope: { goal_1: 0, goal_2: 0, goal_3: 0, goal_4: 0, goal_5: 0, goal_6: 0, goal_7: 0 }, restrict: 'E', templateUrl:'templates/directive-score-display-template.html', link: function(scope,element,attrs){} }; } ``` ]); here the tag: ``` <score-display></score-display> ``` here the directive template: ``` <table> <tr> <td ng-model='goal_1'>1</td> <td ng-model='goal_2'>2</td> <td ng-model='goal_3'>3</td> <td ng-model='goal_4'>4</td> <td ng-model='goal_5'>5</td> <td ng-model='goal_6'>6</td> <td ng-model='goal_7'>7</td> </tr> </table> ```
2014/09/20
[ "https://Stackoverflow.com/questions/25950620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055724/" ]
This portion will throw an error: ``` scope: { goal_1: 0, goal_2: 0, goal_3: 0, goal_4: 0, goal_5: 0, goal_6: 0, goal_7: 0 }, ``` The `scope` property of the directive is meant to declare how attributes on the element should bind to its scope. This should use `=`, `&`, or `@` depending on how/what you want to bind. It looks like you tried to bind in default values. This should be done in the `link` function instead, or just use `ng-init` in the template. Next issue: Why use `ng-model` on `td`? That is meant for elements where you can enter or change data. I'm not sure what you're trying to do there. Just a note: I would use `ng-repeat` to make that template more DRY. ``` <td ng-repeat="item in '1234567'>{{$index+1}}</td> <!-- or --> <td ng-repeat="item in '1234567'>{{item}}</td> ``` [**Here's a working live demo**](http://jsbin.com/zuquqi/1/edit) that might be close to what you're trying to do. ``` <table> <tr ng-init="goals=[1,2,3,4,5,6,7]"> <td ng-repeat="item in goals track by $index"> <p>{{goals[$index]}}</p> <input ng-model="goals[$index]"> </td> </tr> </table> ``` If you still have an issue after making these changes, then the problem exists elsewhere in your code.
The `scope` property of the directive can only accept `@`,`=`and `&` like @m59 said. You can't set the values there as the scope doesnt exist yet. ``` mainApp.directive('scoreDisplay', function() { return { scope: {}, restrict: 'E', templateUrl:'templates/directive-score-display-template.html', link: function(scope,element,attrs){ scope.goal_1 = 0; scope.goal_2 = 0; scope.goal_3 = 0; } } }) ``` You can only set scope variables/properties once a the directive has been picked up and `linked` to a function
385,293
I am using UBuntu 12.04 LTS and I am using SAKIS 3G script to connect to my 3g wireless modem, i want to use google DNS by default , i don't know, how to use google DNS in sakis3g script. In native Network manager,there is a box to change these values. Tell me, how to configure this in sakis 3g script. If this can be done via `/etc/sakis3g.conf` then what need to be entered in this file. Thanks in advance.
2013/12/03
[ "https://askubuntu.com/questions/385293", "https://askubuntu.com", "https://askubuntu.com/users/175850/" ]
`Ctrl`+`Shift`+`f` worked for me.
I run Ubuntu on VirtualBox and tried the above tricks and it didn't worked out on windows 8.1. What I did to exit command line full screen was : 1. **Right click** on the terminal 2. select **Leave Full Screen** And I got the normal screen again.
65,213,388
I have a folder where I will take text files (200-500mb -not very big, but its big text file) and I want to process this file in parallel. the file will have ``` "ComnanyTestIsert", "Firs Comment", "LA 132", "222-33-22", 1 "ComnanyTestIsert1", "Seconds Comment", "LA 132", "222-33-22", 1 ``` for example, I use 2 such files. I don't quite understand when to use BufferedStream with parallel loop how to set the number of parallel operations? and how to make an insert correctly ``` static void Main(string[] args) { //Basic usage to help you get started: ProcessFileTaskItem( new string[] { "\\Insert.txt" , "\\Insert1.txt" } , "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" , "test"); } /// This will read an array of input files, process the lines in parallel, and upload /// everything into the database. public static void ProcessFileTaskItem(string[] SourceFiles, string DatabaseConnectionString, string DestinationTable) { //Make sure there's files to read if (SourceFiles != null && SourceFiles.Length > 0) { //Loop through the file array Parallel.For(0, SourceFiles.Length, x => //for (int x = 0; x < SourceFiles.Length; x++) { //Make sure the file exists and if so open it for reading. if (File.Exists(SourceFiles[x])) { using (SqlConnection connectionDest = new SqlConnection(DatabaseConnectionString)) { connectionDest.Open(); //Configure everything to upload to the database via bulk copy. using (SqlBulkCopy sbc = new SqlBulkCopy(connectionDest, SqlBulkCopyOptions.TableLock, null)) { //Configure the bulk copy settings sbc.DestinationTableName = DestinationTable; sbc.BulkCopyTimeout = 28800; //8 hours //Now read and process the file ProcessAllLinesInInputFile(SourceFiles[x], connectionDest, sbc); } connectionDest.Close(); } } } //for ); //End Parallel reading of files //Explicitly clean up before exiting Array.Clear(SourceFiles, 0, SourceFiles.Length); } } /// Processes every line in the source input file. private static void ProcessAllLinesInInputFile(string SourceFiles, SqlConnection connectionDest, SqlBulkCopy sbc) { //Create a local data table. Should be the same name as the table //in the database you'll be uploading everything to. DataTable CurrentRecords = new DataTable("test"); //The column names. They should match what's in the database table. string[] ColumnNames = new string[] { "Name", "Comment", "Address", "Phone", "IsActive" }; using (FileStream fs = File.Open(SourceFiles, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string s; while ((s = sr.ReadLine()) != null) { } } //Create the datatable with the column names. for (int x = 0; x < ColumnNames.Length; x++) CurrentRecords.Columns.Add(ColumnNames[x], typeof(string)); //Now process each line in parallel. Parallel.For(0, SourceFiles, x => { List<object> values = null; //so each thread gets its own copy. } } ```
2020/12/09
[ "https://Stackoverflow.com/questions/65213388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12947311/" ]
Parallel.For automatically adjusts the number of threads used but it can be specified in the [parallelOptions](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.paralleloptions?view=net-5.0) Parameter. Do you have any reason to believe that doing this in parallel would improve performance? Multithreading will not magically make everything go faster. IO operations like this would typically benefit little, any from multithreading. Especially if you have spinning media where concurrent IO can drastically **reduce** the throughput, and even SSDs usually suffer from non sequential IO. Also, if you are concerned by performance, you should have measurements in place, so you can tell if you are actually improving things. Unless otherwise specified, non-static framework methods are not threadsafe. So you should not try to read from the same stream from multiple threads. You could use multiple streams, but If you have sufficient memory I would suggest using `File.ReadAllLines` rather than `ReadLine`, I suspect that would be faster since it can read everything sequentially.
The slow part of your process is the reading of the data in the file. Regularly your program would have to wait idly for the "hard disk" to provide a chunk of data. Instead of waiting idly, your program could already do some processing of the already fetched items. Whenever you have a program where your process has to wait for some external process, like writing to a disk, querying data from a database management system, or fetching information from the internet, it is wise to consider to use async-await. If you use async-await, then, whenever your process has to wait for some other process to finish, it won't wait idly, but will look around to see if it can do something else instead. In your case, you could call an async function that async reads one file and async writes the read data to the database. If you start several of these Tasks, then whenever one of these Tasks has to await for the result from either the file reading or the database writing, it can look around to see if it can do anything for the other Tasks. So while it is waiting for a chunk of data from reading file X in Task A, it could already start writing data to the database in Task B. As we are processing the file line by line, we need a function that returns an `IEnumerable<string>`, or the async equivalent: `IAsyncEnumable<string>`. See [iterating with AsyncEnumerable](https://learn.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8) ``` public async IAsyncEnumerable<string> ReadLines(string fileName) { using (StreamReader reader = File.OpenText(fileName) { while(!reader.EndOfStream) { yield return await reader.ReadLineAsync().ConfigureAwait(false); } } } ``` > > File.OpenText sadly only allows synchronous I/O; the async APIs are implemented poorly in that scenario. To open a true asynchronous file, you'd need to use one of the [overloads of the FileStream constructors](https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=net-5.0) that have a Boolean parameter isAsync or FileOptions.Asynchronous. > > > Usage: ``` async Task DisplayFileContentsAsync(string fileName) { await foreach(string line in ReadFileAsync(fileName)) { Console.WriteLine(line); } } ``` We also need a method that writes the read data to the database. I do it here line by line, if you want, you could change it such that is writes several lines at once. ``` async Task SaveInDbAsync(string line, string dbConnectionString) { using (SqlConnection dbConnection = new SqlConnection(dbConnectionString)) { // prepare the SQL command (consider using other methods) const string sqlCommandText = @"Insert into ..."; var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = sqlCommandText; dbCommand.Parameters.Add(...) // async execute the dbCommand await dbConnection.OpenAsync(); await dbCommand.ExecuteNonQueryAsync(); // TODO: consider to use the return value to detect problems } } ``` Put it all together: read one file and save the lines in the database: ``` async Task SaveFileInDbAsync(string fileName, string dbConnectionString) { await foreach(string line in ReadFileAsync(fileName)) { await SaveInDbAsync(line, dbConnectionString); } } ``` To save all your files: ``` async Task SaveFilesInDbAsync(IEnumerable<string> fileNames, string dbConnectionString) { // start all Tasks, do not await yet: List<Task> tasks = new List<Task>(); foreach (string fileName in fileNames) { Task task = SaveFileInDbAsync(fileName, dbConnectionString); tasks.Add(task); } // now that all Tasks are started and happily reading files // and writing the read lines to the database // await until all Tasks are finished. await Task.WhenAll(tasks); } ``` Or if you need a synchronous version: ``` void SaveFilesInDb(IEnumerable<string> fileNames, string dbConnectionString) { // start all Tasks, do not await yet: List<Task> tasks = new List<Task>(); foreach (string fileName in fileNames) { Task task = SaveFileInDbAsync(fileName, dbConnectionString); tasks.Add(task); } // Wait until all Tasks are finished. Task.WaitAll(tasks); } ```
234,788
I am building a project which requires a very fine servo resolution (<=.1 degree). I understand there is a lot that goes into servo resolution like digital v analog, dead-band, # of poles, etcetera. However, all other things being equal, is there any reason to think that a micro servo would not be as precise as a standard-size servo? Edit: Let's assume I have two servos of different sizes. Both are digital, 5 pole, geared servos and I have programmatically set the dead-band to 0. Are there factors I am not considering, like the electronics or manufacturing process, that would make the larger one more accurate than the smaller (or vice-versa)? Edit2: I am building a drawing robot as a hobby project so I'm interested in model servos (ideally < $100) and my question is specifically for that market. I am more interested in resolution (making very short lines) than accuracy (the absolute positioning of the pen on the page) as long as the accuracy is fairly consistent for the whole drawing
2016/05/17
[ "https://electronics.stackexchange.com/questions/234788", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/82974/" ]
You can do this with an IC multiplier, however it will not be cheap. Also, note the bipolar supplies. [![enter image description here](https://i.stack.imgur.com/YcZwp.png)](https://i.stack.imgur.com/YcZwp.png) I suggest reducing the input resistor (to get gain on \$E\$) and using another op-amp (maybe half of a dual) to amplify \$E\_X\$ so the input signals are reasonably high. Alternatively, you could use an external ADC that has multiple simultaneously sampled channels. If memory serves, there are even a few microcontrollers that have that built in, for such applications as 3-\$\phi\$ energy metering.
Use subtractor circuit to get voltage across AB and use a micro-controller like pic with internal ADC to monitor the voltage internally, and since you can operate a pic at about 20MHz, you can keep close watch on the parameter. Just an idea.
61,179,062
I don't understand what is the actual need of having FabricTLSCA if we have PKI in place for secure communication. My assumption is that TLSCA is required for secure communication between different components. For example cert for my domain \*.abc.com can be used using PKI than why Fabric TLSCA is required to give certificates.
2020/04/12
[ "https://Stackoverflow.com/questions/61179062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6839994/" ]
The schema is case sensitive. If you wish to fix: Goto: ./node\_modules/@angular/cli/lib/config/schema.json At around line 27 you should find: ``` "projects": { "type": "object", "patternProperties": { "^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$": { "$ref": "#/definitions/project" } }, ``` Change the regex pattern to allow Uppercase project names: ``` "^(?:@[a-zA-Z0-9-~][a-zA-Z0-9-._~]*\/)?[a-zA-Z0-9-~][a-zA-Z0-9-._~]*$" ```
There are 2 solutions which works for me 100% to overcome from the problem of "Property not allowed" in angular.json file. 1. Use the command in VS code cmd Ctrl+C choose option Y or 2. Restart the VS code after editing in angular.json file Hope it will helpful.
74,577,836
I want to update a series if it is missing a key, but my code is generating an error. This is my code: ``` for item in list: if item not in my_series.keys(): my_series = my_series[item] = 0 ``` Where my\_series is a series of dtype int64. It's actually a value count. My code above is generating the following error ``` 'int' object does not support item assignment ```
2022/11/25
[ "https://Stackoverflow.com/questions/74577836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2738545/" ]
You can multiply by a logical vector to get a conditional sum: ``` library(dplyr) df %>% group_by(subs_id) %>% summarize( ttl_amount = sum(amount), amount = sum(amount * (flag == "taker")) ) ``` ``` # A tibble: 3 × 3 subs_id ttl_amount amount <dbl> <dbl> <dbl> 1 1 25 10 2 2 30 0 3 3 30 20 ```
Here's how I would do it: ``` library(dplyr) subs_id <- c(1, 1, 2, 3, 3) amount <- c(15, 10, 30, 20, 10) flag <- c("target", "taker", "target", "taker", "target") data <- data.frame(subs_id, amount, flag) data_new <- data %>% group_by(subs_id) %>% mutate(column_summary = sum(amount)) data_new$column_id <- ifelse(data_new$flag == "taker", data_new$amount, 0) ```
29,994,123
Hey guys I have two simple JavaScript page. One holds the function that returns the object. The other read the returned object. Unfortunately I am unable to read the returned object. main.js ``` var userObj = getUserInfo('2'); console.log(userObj); //undefined console.log(userObj.name); //undefined ``` globals.js ``` function getUserInfo(mapID){ var jqxhr = $.ajax({ url: user_url, type: "GET", cache: true, dataType: "json", statusCode: { 404: function () { handleError404("Error 404 at getUserInfo();") }, 500: function () { handleError500("Error 500 at getUserInfo();") }, }, success: function (data) { console.log(data); var obj = { name: data.name, age: data.age, weight: data.weight } console.log(obj); //{name:"Kanye West", age:23, weight:"450lbs"} return obj; } }); } ``` As you can see, If I was to output the object in the function itself, I see the result. But not if I call it from the main.js page. Any help would be greatly appreciated!
2015/05/01
[ "https://Stackoverflow.com/questions/29994123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522768/" ]
You don't return anything from `getUserInfo` so you shouldn't expect anything from it. You are only returning something in the success callback function. That is is run asynchronously. It doesn't return anything for `getUserInfo`. If you want to make your ajax call a separate function you can make it return a promise from `$.ajax` instead of using a `success` callback. ``` function getUserInfo(mapID){ return $.ajax({ url: user_url, type: "GET", cache: true, dataType: "json", statusCode: { 404: function () { handleError404("Error 404 at getUserInfo();") }, 500: function () { handleError500("Error 500 at getUserInfo();") }, } }); } ``` then in main.js ``` var promise = getUserInfo('2'); promise.done(function(userObj) { console.log(userObj); console.log(userObj.name); }); ```
You are not returning anything. The `success` callback function in the `$.ajax()` call is invoked asynchronously, meaning it is executed after the HTTP request is done. Also, it is a different `function` than `getUserInfo`. At this point you are just **returning a value for the `success` function**. I will suggest using another function that will process whatever you receive in the success call. SO in your successs call you get to add a line like `handleObject(obj)`
2,917,898
I'm trying to compute clusters on a set of points in Python, using GeoDjango. The problem: Given a set of points, output a set of clusters of those points. (i'm fine specifying # of clusters/cluster size/distance in advance to simplify) There are a few [solutions](http://www.quanative.com/2010/01/01/server-side-marker-clustering-for-google-maps-with-python/) on the web to do clustering, so it's a well known problem. I thought that GeoDjango would handle these types of problems out of the box, but it's not clear how - I've searched the GeoDjango documentation, Google, and a few other places, but couldn't find anything. Before I roll my own clustering solution, I thought I'd ask to see if there's a straightforward way to do this using GEOS or another package within GeoDjango.
2010/05/27
[ "https://Stackoverflow.com/questions/2917898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200578/" ]
GeoDjango does not have any built in clustering support; this operation is not typically provided by any existing Open Source GIS application that you would be using with GeoDjango that I'm aware of. Several sites running Django/GeoDjango (like everyblock.com) have published what their method is for clustering, but this support is not built into GeoDjango. In general, the functionality provided by these applications is based on the underlying database support. GEOS, the library underneath PostGIS, and the general 'state of the art' (at least in the non-Java world), does not have any kind of clustering API or behavior.
As Christopher Schmidt mentioned, there doesn't seem to be any out of the box support for clustering in GeoDjango. However, if someone else runs into this issue, here's what I did: * Installed mlpy and numpy * Used the HCluster hierarchical clustering algorithm * Wrote a wrapper function to convert the GEOS Point objects into a matrix that mlpy could understand Documentation at: <https://mlpy.fbk.eu/data/doc/clustering.html>
4,149,976
I have seen this reasoning elsewhere and I am not sure wether it is correct. I think the reasoning behind it should be as follows: Suppose that T is inconsistent. Then $T\_2$ is inconsistent with $T\_1$ and so there is $\phi \in T\_2$ such that $T\_1 \nvDash \phi$. But I can't find a proof of why it is the case that $T\_2$ is inconsistent with $T\_1$, as I only know that they both should be inconsistent by compactness. Also, we need to know that $T\_1$ is complete to deduce to know that $T\_1 \models \neg \phi$. What is missing in this argument?
2021/05/24
[ "https://math.stackexchange.com/questions/4149976", "https://math.stackexchange.com", "https://math.stackexchange.com/users/867078/" ]
Not necessarily. Let $T\_1=\emptyset$ and $T\_2=\{\phi,\lnot\phi\}$ where neither $\phi$ nor $\lnot \phi$ is valid. ${}{}{}{}$
Suppose that $T=T\_1 \cup T\_2$ is inconsistent, and $T, T\_1, T\_2 \neq \emptyset$ then by compactness, it is not the case that every finite subset of T is consistent. As $T\_1, T\_2 \subseteq T$, w.l.o.g suppose that there is M such that $M \models T\_1$, then $M \nvDash T\_2$ so there is some $\phi \in T\_2$ such that $T\_1 \nvDash \phi$. If additionally $T\_1$ is complete: $T\_1 \models \neg \phi$.
45,780,145
I have a class Foo, which is a base class for a lot other classes such as Bar and Baz, and I want to do some calculation within Foo using the static members in Bar and Baz, as shown below: ``` public class Foo{ public result1 { get{ return field1; } } } public class Bar : Foo{ public const int field1 = 5; } public class Baz : Foo{ public const int field1 = 10; } ``` The only solution I can think of is wrap all the fields in a container, add an extra identifier for each object, and use a function to return the fields, like so ``` Bar : Foo{ public readonly int id = 0; public static Wrapper wrapper; } public Wrapper GetWrapper(int id){ switch(id){ case 0: return Bar.wrapper; } } ``` However, as you can see, I need to maintain one additional class and function, and I'd rather not to fragment my code. Is there any alternative?
2017/08/20
[ "https://Stackoverflow.com/questions/45780145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3908301/" ]
**Edit** What you are asking for, i.e. accessing a `static` or `const` value in a subclass from a base class is technically possible, but doing so will violate the principals of good [SOLID OO](https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) design. Also, since you will need an instance of a specific subclass in order to be able to 'reason over' the type of the subclass in order to obtain the appropriate `field1`, there's little point approaching this problem statically. Instead, the common, cleaner, approach here is to use [subtype polymorphicism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) which will allow a calling method in the base class, or a method in an external class altogether, to access the appropriate value for 'field1' based on the subclass. This allows control over the value returned to remain inside the appropriate subclasses (i.e. as per your words, the code won't become "fragmented"). **Alternative solution using subclass polymorphicism (recommended)** A subclass polymorphic approach (i.e. with the `virtual/abstract` and `override` keywords) will allow you to encapsulate the retrieval of a value (or object) which is customizable for each subclass. Here, the abstraction remains conceptually at "give me an integer value", and then the sub-class-specific implementations of 'how' to return the value can be abstracted (hidden) from the caller. Also, by marking the base property as `abstract`, you will force all subclasses to implement the property, so that the requirement to provide a value isn't forgotten about. i.e. I would recommend a polymorphic approach like this: ``` public abstract class Foo { public abstract int Result { get; } } public class Bar : Foo { // This is implementation specific. Hide it. private const int field1 = 5; public override int Result { get { return field1; } } } public class Baz : Foo { public override int Result { // No need for this implementation to be a constant ... get { return TheResultOfAReallyComplexCalculationHere(); } } } ``` If there are no other reusable concrete methods on the base class `Foo`, then you could also model the abstraction as an interface, with the same effect: ``` public interface IFoo { int Result { get; } } ``` **Approaching this problem without polymorphicism (Not recommended)** Any compile-time attempt to access static fields on subclasses will typically require code somewhere to switch (or map) on the actually type of the subclass instance, e.g.: ``` public class Foo { public int result1 { get { switch(this.GetType().Name) { case "Bar": return Bar.field1; case "Baz": return Baz.field1; default: return 0; } } } public void MethodRequiringValueFromSubclass() { Console.WriteLine(result1); } } public class Bar : Foo { public const int field1 = 5; } public class Baz : Foo { public const int field1 = 10; } ``` The problem here is that the [Open and Closed principal](https://en.wikipedia.org/wiki/Open/closed_principle) is violated, as each time a new sub class is added, the `result1` method would need to be changed to accomodate the new class.
You either add constructor parameter to your `Foo` class which can be passed from inheritors, thus you don't need extra classes also you'll have less coupling ``` public class Foo { private readonly int _field1; public Foo(int field1) { _field1 = field1; } } ``` or you can use it exactly from inheritors type as static/const members are members of class type ``` public class Foo { public result1 { get { return Bar.field1; } } } ``` but this gives your code less flexibility and more coupling. Also you have an option by using virtual properties which you can implement in derrived classes and use in base: ``` public class Foo { public virtual int Field { get { return 0; } } } ```
7,447,927
If I have the following variable in javascript ``` var myString = "Test3"; ``` what is the fastest way to parse out the "3" from this string **that works in all browsers (back to IE6**)
2011/09/16
[ "https://Stackoverflow.com/questions/7447927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Since in Javascript a string is a char array, you can access the last character by the length of the string. ``` var lastChar = myString[myString.length -1]; ```
Use the `charAt` method. This function accepts one argument: The index of the character. ``` var lastCHar = myString.charAt(myString.length-1); ```
3,886,484
I have SQL Server stored procedures which have several inputs. I want to save time from manually creating C# ADO.NET sqlParameter arrays as in ``` sqlParameter[] sqlParameters = { new SqlParameter("customerID", SqlDbType.Int, 4, ParameterDirection.Input, false, 0, 0, string.Empty, DataRowVersion.Default, custID) ....... ``` Any code generator which can this and a template which can do this? If you mention a code generator, please mention which template. Like which one for [CodeSmith](http://www.codesmithtools.com/product/generator).
2010/10/07
[ "https://Stackoverflow.com/questions/3886484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129001/" ]
``` #!/bin/bash echo show databases\; | mysql -u root | (while read x; do echo "$x" y="$x" done echo "$y" ) ```
``` local count=$(mysql -u root --disable-column-names --batch --execute "SELECT COUNT(*) FROM mysql.user WHERE user = '$DstDbName'") if [[ "$count" > 0 ]] then fi ``` --batch - do clear output w/o borders --disable-column-names - prints only row with value no creasy AWK used :)
28,063,866
Hello friends i want to add 10% of shipping price in magento shipping method during checkout :- i follow this tutorial but it's not work for me :- <http://www.blog.magepsycho.com/change-shipping-price-handling-fee-fly-magento/> and my code is here :- Config.xml :- ``` <?xml version="1.0"?> <config> <modules> <Ab_Extrashipcost> <version>0.1.0</version> </Ab_Extrashipcost> </modules> <global> <models> <extrashipcost> <class>Ab_Extrashipcost_Model</class> </extrashipcost> </models> <events> <sales_quote_collect_totals_after> <observers> <ab_extrashipcost> <type>singleton</type> <class>extrashipcost/observer</class> <method>salesQuoteCollectTotalsBefore</method> </ab_extrashipcost> </observers> </sales_quote_collect_totals_after> </events> </global> </config> ``` Observer file:- ``` <?php class Ab_Extrashipcost_Model_Observer { public function salesQuoteCollectTotalsBefore(Varien_Event_Observer $observer) { /** @var Mage_Sales_Model_Quote $quote */ $quote = $observer->getQuote(); $someConditions = true; //this can be any condition based on your requirements $newHandlingFee = 15; $store = Mage::app()->getStore($quote->getStoreId()); $carriers = Mage::getStoreConfig('carriers', $store); foreach ($carriers as $carrierCode => $carrierConfig) { if($carrierCode == 'flatrate_flatrate'){ if($someConditions){ Mage::log('Handling Fee(Before):' . $store->getConfig("carriers/{$carrierCode}/handling_fee"), null, 'shipping-price.log'); $store->setConfig("carriers/{$carrierCode}/handling_type", 'F'); #F - Fixed, P - Percentage $store->setConfig("carriers/{$carrierCode}/handling_fee", $newHandlingFee); ###If you want to set the price instead of handling fee you can simply use as: #$store->setConfig("carriers/{$carrierCode}/price", $newPrice); Mage::log('Handling Fee(After):' . $store->getConfig("carriers/{$carrierCode}/handling_fee"), null, 'shipping-price.log'); } } } } } ?> ```
2015/01/21
[ "https://Stackoverflow.com/questions/28063866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4469145/" ]
Make sure that you put module configuration file under app/etc/modules folder.
Your config.xml code should be :- ``` <?xml version="1.0"?> <config> <modules> <Ab_Extrashipcost> <version>0.1.0</version> </Ab_Extrashipcost> </modules> <global> <models> <extrashipcost> <class>Ab_Extrashipcost_Model</class> </extrashipcost> </models> </global> <frontend> <events> <sales_quote_collect_totals_before> <observers> <ab_extrashipcost> <type>singleton</type> <class>extrashipcost/observer</class> <method>salesQuoteCollectTotalsBefore</method> </ab_extrashipcost> </observers> </sales_quote_collect_totals_before> </events> </frontend> </config> ``` And Observer.php code should be :- ``` <?php class Ab_Extrashipcost_Model_Observer { public function salesQuoteCollectTotalsBefore(Varien_Event_Observer $observer) { /** @var Mage_Sales_Model_Quote $quote */ $quote = $observer->getQuote(); $someConditions = true; //this can be any condition based on your requirements $newHandlingFee = 15; $store = Mage::app()->getStore($quote->getStoreId()); $carriers = Mage::getStoreConfig('carriers', $store); foreach ($carriers as $carrierCode => $carrierConfig) { if($carrierCode == 'flatrate'){ if($someConditions){ Mage::log('Handling Fee(Before):' . $store->getConfig("carriers/{$carrierCode}/handling_fee"), null, 'shipping-price.log'); $store->setConfig("carriers/{$carrierCode}/handling_type", 'F'); #F - Fixed, P - Percentage $store->setConfig("carriers/{$carrierCode}/handling_fee", $newHandlingFee); ###If you want to set the price instead of handling fee you can simply use as: #$store->setConfig("carriers/{$carrierCode}/price", $newPrice); Mage::log('Handling Fee(After):' . $store->getConfig("carriers/{$carrierCode}/handling_fee"), null, 'shipping-price.log'); } } } } } ?> ```
1,066,589
What's the best way to iterate over the items in a [`HashMap`](https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html)?
2009/06/30
[ "https://Stackoverflow.com/questions/1066589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84916/" ]
Extracted from the reference *[How to Iterate Over a Map in Java](http://www.sergiy.ca/how-to-iterate-over-a-map-in-java)*: There are several ways of iterating over a `Map` in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (`HashMap`, `TreeMap`, `LinkedHashMap`, `Hashtable`, etc.) **Method #1**: Iterating over entries using a For-Each loop. This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop. ``` Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } ``` Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw `NullPointerException` if you try to iterate over a map that is null, so before iterating you should always check for null references. **Method #2**: Iterating over keys or values using a For-Each loop. If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet. ``` Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // Iterating over keys only for (Integer key : map.keySet()) { System.out.println("Key = " + key); } // Iterating over values only for (Integer value : map.values()) { System.out.println("Value = " + value); } ``` This method gives a slight performance advantage over `entrySet` iteration (about 10% faster) and is more clean. **Method #3**: Iterating using Iterator. Using Generics: ``` Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } ``` Without Generics: ``` Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); System.out.println("Key = " + key + ", Value = " + value); } ``` You can also use same technique to iterate over `keySet` or values. This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling `iterator.remove()`. If you try to do this during For-Each iteration you will get "unpredictable results" according to [Javadoc](https://en.wikipedia.org/wiki/Javadoc). From a performance point of view this method is equal to a For-Each iteration. **Method #4**: Iterating over keys and searching for values (inefficient). ``` Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value); } ``` This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided. **Conclusion:** If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.
You can iterate through the entries in a [`Map`](http://java.sun.com/javase/6/docs/api/java/util/Map.html) in several ways. Get each key and value like this: ``` Map<?,?> map = new HashMap<Object, Object>(); for(Entry<?, ?> e: map.entrySet()){ System.out.println("Key " + e.getKey()); System.out.println("Value " + e.getValue()); } ``` Or you can get the list of keys with ``` Collection<?> keys = map.keySet(); for(Object key: keys){ System.out.println("Key " + key); System.out.println("Value " + map.get(key)); } ``` If you just want to get all of the values and aren't concerned with the keys, you can use: ``` Collection<?> values = map.values(); ```
36,771,685
I am working on my final project in my final grade. I'm currently working on a site linked with mysql for a dance school. I want to check if a checkbox returns a value or not. It gives a "undefined index"-error at the "if($\_POST['dansstijl'.$i.''])" and I don't know what i'm doing wrong. Sorry if there are parts in dutch! Here's a big part of the code: ``` $sql1="INSERT INTO tblinschrijvingen(llnID) VALUES('".$lln_id."')"; if(!$result1=$mysqli-> query($sql1)) {trigger_error('Fout bij query: '.$mysqli->error);} else { $sql2="SELECT inschrijvingsID FROM tblinschrijvingen ORDER BY inschrijvingsID DESC LIMIT 1"; if(!$result2=$mysqli-> query($sql2)) {trigger_error('Fout bij query: '.$mysqli->error);} else { for($i=1;$i<=11;$i++) { if($_POST['dansstijl'.$i.'']) { $row=$result2->fetch_assoc(); $inschrijvingsID=$row['inschrijvingsID']; $sql3="SELECT DansID, vestiging, Dansstijl FROM tbldanslessen WHERE vestiging='".$vestiging."' AND Dansstijl='".$_POST['dansstijl'.$i.'']."'"; echo($sql3); if(!$result3=$mysqli-> query($sql3)) {trigger_error('Fout bij query: '.$mysqli->error);} else { $row=$result3->fetch_assoc(); $dansID=$row['DansID']; $sql4="INSERT INTO tblinschrijvingenperdansles(inschrijvingsID, dansID) VALUES ('".$inschrijvingsID."', '".$dansID."')"; if(!$result4=$mysqli-> query($sql4)) {trigger_error('Fout bij query: '.$mysqli->error);} else { } } } } } ``` Here are my checkboxes: ``` <table border="0"> <tbody> <tr> <td width="199"><label> <input type="checkbox" name="dansstijl1" value="Peuterballet" id="dansstijl1"> Peuterballet</label></td> <td width="162"><label> <input type="checkbox" name="dansstijl2" value="Preballet" id="dansstijl2"> Preballet</label></td> </tr> <tr> <td><label> <input type="checkbox" name="dansstijl3" value="Preprimary" id="dansstijl3"> Preprimary</label></td> <td><label> <input type="checkbox" name="dansstijl4" value="Primary" id="dansstijl4"> Primary</label></td> </tr> <tr> <td><label> <input type="checkbox" name="dansstijl5" value="Klassiek" id="dansstijl5"> Klassiek</label></td> <td><label> <input type="checkbox" name="dansstijl6" value="Modern Jazz" id="dansstijl6"> Modern Jazz</label></td> </tr> <tr> <td><label> <input type="checkbox" name="dansstijl7" value="Hedendaags" id="dansstijl7"> Hedendaags</label></td> <td><label> <input type="checkbox" name="dansstijl8" value="Musical" id="dansstijl8"> Musical</label></td> </tr> <tr> <td><label> <input type="checkbox" name="dansstijl9" value="Pointes" id="dansstijl9"> Pointes</label></td> <td>&nbsp;</td> </tr> <tr> <td><label> <input type="checkbox" name="dansstijl10" value="Hiphop - Breakdance" id="dansstijl10"> Hiphop - Breakdance</label></td> <td><label> <input type="checkbox" name="dansstijl11" value="Hiphow - Crew" id="dansstijl11"> Hiphow - Crew</label></td> </tr> </tbody> </table> ``` Thank you on forehand! Jules
2016/04/21
[ "https://Stackoverflow.com/questions/36771685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6236013/" ]
This is expected behavior. Parent project (your phoenix app) is not using configuration from deps. If dependencies require configuration you need to specify it in the parent app, so you would need to copy: ``` config :wikix, http_client: Wikix.HTTPClient config :wikix, user_agent: [{"User-agent", "tugorez tugorez@gmail.com"}] ``` to your Phoenix app. It is often a good idea to provide a default, so for example in `Wikix` app you can have something like this: ``` defmodule Wikix.SomeModule do @httpclient Wikix.HTTPClient call(first_arg, second_arg, httpclient \\ @httclient) do ... ``` You can now read the configuration and pass the client as last argument just as in the article about mocks. But also you can make sure that your Phoenix app doesn't have to configure anything and it will use the default client when calling the function without specifying last argument. Your Phoenix app probably shouldn't even know about `Wikix` "in memory client", so it makes sense to make such defaults.
I can't completely decipher your question but I think the answer to [this question](https://stackoverflow.com/questions/23897199/how-to-read-config-files-on-elixir-mix-project) might be what you're looking for. Specifically this part: > > You can read keyword lists stored in a \*.exs file, using > Mix.Config.read(path). > > >
18,628,074
I have found this crazy javascript code. Can someone elaborate the exact steps this code is going through and why? ``` (function a(a){ return a; }) (function b(b){ return b; }) (function c(c){ return c; }) (true); ```
2013/09/05
[ "https://Stackoverflow.com/questions/18628074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692528/" ]
* This will self-invoke `a` which is given `function` `b` as argument (since `a` is defined as a *variable* inside `a`'s local scope that will take presence over the *function* `a` which is declared in parent scope.). * Then it will self-invoke `b` which is given `c` as as argument. * Finally function `c` is self-invoked which returns `true` as that is given as argument. You can look at it as a chain doing this: ``` a(var a) // function b given as arg. When a returns b() will be invoked b(var b) // function c given as arg. When b returns c() will be invoked c(true) ``` `a` when inside the function (local scope) is a variable because `function foo(bar){}` is the same as `function(){var bar = arguments[0]}`. The function `a` could be written like this and do the same exact thing: ``` function a(foo){ return foo; } ``` You can verify by doing this: ``` console.log('start'); (function a(a){ console.log('a', typeof a); return a; }) (function b(b){ console.log('b', typeof b); return b; }) (function c(c){ console.log('c', typeof c); return c; }) (true); console.log('end'); ``` **[ONLINE FIDDLE HERE](http://jsfiddle.net/AbdiasSoftware/NM2MN/)** Console output (updated to show in FF as well use Chrome to see the function definition output): ``` > start > a function > b function > c boolean > end ```
I'll take a stab at it. ``` (function a(a){ return a; }) (function b(b){ return b; }) (function c(c){ return c; }) (true); ``` These are all self-invoking functions. But the last one: ``` (function c(c){ return c; }) (true); ``` Gets the value true passed in. So, when it returns "c" - you get true. For the others, it just moves up as anonymous functions get passed in the value return by the function. So, a visual. ``` (function a(a){ <-- the return of b, gets passed in here return a; })(function b(b){return b;}) <-- the return of c, gets passed in here (function c(c){return c;})(true); <--- true gets passed into c. ```
14,632,178
First of all, please be patient, because I don't speak english very well and I don't know if I will manage to explain the solution very well. So... I have this HTML ``` <div id='container'> <div class='picture'> <img src='...'> </div> <div class='description'> <div id='attrb1' class='clearfix'>...</div> <div id='attrb2' class='clearfix'>...</div> <div id='attrb3' class='clearfix'>...</div> <div id='attrb4' class='clearfix'>...</div> </div> </div> ``` The clearfix class is implemented as explained [here](http://www.webtoolkit.info/css-clearfix.html) I want the .picture div to stay on the left and the .description div to stay on the right. So I wrote this CSS ``` .picture { float: left; width: 100px; } .picture img { width: 100px; height: auto; } .description { float: right; width: 815px; } ``` Till now, everything is ok. But sometimes, **no picture is present**. In this case I want that .description div extends for all the .container div width. So I tried to remove the width of both divs: ``` .picture { float: left; } .picture img { width: 100px; height: auto; } .description { float: right; } ``` But the .description div flows below the .picture div (if the picture is present) Here is a screenshot: ![two .container divs: the first with .picture div and the second without](https://i.stack.imgur.com/Zv55O.jpg)
2013/01/31
[ "https://Stackoverflow.com/questions/14632178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162049/" ]
<http://jsfiddle.net/UQngw/> When I disable css ``` .clearfix { #display: inline-block; } ``` Look like `display: line-block;` let the div as width as it can. **UPDATE** Well, I just find that my code have some problem when the text so long... <http://jsfiddle.net/HbCaK/3/> I have disabled the following css in this try, but I am not sure if this is suitable in your case: ``` .description { #float: right; } .clearfix:after { content:"."; #display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clearfix { #display: inline-block; } ```
Use min-width for .picture instead: ``` .picture { float: left; min-width: 100px; } .picture img { width: auto height: auto; } .description { float: right; width: 815px; } ``` When the img tag is removed from the picture div the layout should collapse like what I think you are asking for.
2,164,558
Let $N\_t$ be a Poisson process of rate $\lambda$. 1)What is $P(N\_s = 1|N\_t =1)$ for $0<s<t$? 2) Find the distribution of the time of the first point of the process, conditional on the event that exactly one point occurs in the interval [0,t]? I know $P(N\_t = 1)=e^{-\lambda t}(\lambda t)$. I was wondering based on the memoryless property for Poisson processes whether $P(N\_s = 1|N\_t =1)=e^{-\lambda t}(\lambda t)$ as well since the distribution of $(N\_t,t>t\_0)$ conditional on the process $(N\_t,t\ge t\_0)$ depends only on the value of $N\_{t\_0}$ Additionally, I am not sure about part 2), would this also be a Poisson process of rate $\lambda$?
2017/02/27
[ "https://math.stackexchange.com/questions/2164558", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Those steps are correct, but there's one final step required: 6. When $x=1$, the left-hand side is $2$ and the right-hand side is $2$; when $x=6$, the left-hand side is $3$ and the right-hand side is $-3$. So only the first "solution" is a solution. (Er. When I did this the first time, I wrongly thought that the RHS in the $x=6$ case was $3$.) --- To explain step 5: we want to find $x$, given that $(x-1)(x-6) = 0$. Let $a=x-1$ and $b=x-6$; then since $ab=0$, we have $a=0$ or $b=0$. So $x-1=0$ or $x-6=0$; so $x=1$ or $x=6$. Why is it the case that if $ab=0$ then $a=0$ or $b=0$? This is precisely the statement that the product of nonzero quantities is nonzero (by taking the contrapositive), which you might find more intuitive; but I see there is another answer which gives algebraic manipulations to prove it.
It's only **valid** to square the equation when both sides are **positive**. In your second line you **need** to have a condition $3-x\geq 0 $ which simplifies to $x\leq 3$.Also you must have your square root defined i.e $x+3\geq 0$ or $x\geq -3$. Now that we've done that we can see that $x=6$ is *not* a solution to the equation,this can be easily verified by plugging $x=6$ or differently $\sqrt{6+3}\neq 3-6$
233,042
[In this question](https://softwareengineering.stackexchange.com/questions/232969/how-much-effort-should-i-invest-in-creating-loosely-coupled-designs) I asked: Is the cost of designing more levels of abstraction to allow loose coupling worth the benefits, or not? People said that it's often worth the cost, but one should sense whether his/her application will actually be using this underlying design later on, or if it's just going to be a waste of time. My new question is: Should one create the infrastructure to allow flexibility and maintainability **in advance** - thus making the development 'cleaner' and more 'organized', as things are developed on existing infrastructure and abstraction levels? With this approach, you desing the underlying infrastructure while not having much knowledge on how things will actually be implemented later. Thus, you might be coding things that might not be used later, and waste your time. But, the development will be cleaner and more organized. Or should one create infrastructure to increase flexibility and make things more loosely coupled, **during** the implementation of something - thus wasting less time on things that might not actually be used later? This approach prevents you from coding things that won't be used, but forces you to design underlying abstraction levels and designs **for existing code**, thus modifying existing code, instead of coding the underlying designs **before** coding the code that uses these designs. **Example for approach 1:** "Okay, now we start making this relatively large part of the application. This part will generally have to do with reacting to a couple of GUIs. Let's make an underlying level of abstraction for this part of the program, to later use when we implement it." **Example for approach 2:** "Okay, I'm in the middle of designing this part of the program. While working on it, I see this part better be loosely coupled. Let's make another level of abstraction to allow it, and modify this code to use that level of abstraction". Which approach makes more sense, or is more common?
2014/03/20
[ "https://softwareengineering.stackexchange.com/questions/233042", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/121368/" ]
I'd advise against approach 1. Writing code is a process of discovery - just like no plan survives contact with the enemy, every design will have flaws that are only caught once you start implementing it. Besides, you can abstract anything in an arbitrary number of directions and levels. If you design for too many "what-ifs", your architecture won't be aligned with your needs; if taken far enough, you end up with ridiculous things like [Greenspun's Tenth Rule](http://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule) or the [Inner-Platform Effect](http://en.wikipedia.org/wiki/Inner-platform_effect) (think about it - if everything is customizable, what you'll have left is a programming language.) On top of that, you're chasing a moving target (changing requirements). Even if you miraculously get the design correct *now*, there's no guarantee it'll still be relevant later, as you said. In short, it's a slipperly slope. It doesn't deliver immediate value and there's a good chance it'll steer you in the wrong direction.
The Python community has this wonderful artifact: "Guido's Time Machine". That is, many marvel at Guido Van Rossum's foresight in setting up syntax and mechanisms in Python that just proved to work very cleanly and intuitively over time. Not everyone has a time machine, though, and anticipating requirements can be tricky. In agile, the rule is "program close to the requirements". In TDD it's "the simplest solution that works." However, there's a balance between brute force implementation, and abstracting to anticipate future requirements. IMHO it's important to a) keep an eye out for nice abstractions to provide for clean, flexible, extendible code, and b) watch out for turning your project into a swamp of over-generalized infrastructure that doesn't actually *do* anything. A lot of time, I'll work on the broad-minded stuff in my spare time in my side projects. But I still wince in meetings when an engineer, at any level of experience, gets excited about some mechanism that's going to Solve the World's Problems. At the end of the day, make sure you're putting functionality in front of customers. But keep your powers of abstraction sharp with targeted application.
12,197,191
Is there a way to avoid merge conflicts in version tag in `pom.xml` when merging master into a branch? I have quite a few pom files, 80, and all of them have same version which is different from one in master. It's laborious and time-consuming to execute `git mergetool` for 80 pom files just for a version tag.
2012/08/30
[ "https://Stackoverflow.com/questions/12197191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411709/" ]
You could also use a custom merge driver, as in [pom-merge-driver](https://github.com/agusmba/pom-merge-driver). Depending on your workflow you might want to merge pom as a normal file, except treating the project version differently: always take the merging branch version, or make an exception when merging to the develop branch...
I had the same problem and all solutions that i found didn't do it, imo, correct. Finally i wrote a merge driver which only takes care of the project/parent version and only them. No dependency version is changed nor the format of the xml file. I released it a few minutes ago @ <https://github.com/cecom/pomutils>. If you have any questions, let me know.
1,253,430
I'm writing a custom log4j appender, and I want to rely on another configured appender as a fallback, in case my (Database) appender fails. How can I guarantee order of construction of the appenders? My appender's `activateOptions()` method tries to access another appender and fails because it's not constructed/registered yet.
2009/08/10
[ "https://Stackoverflow.com/questions/1253430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I suggest to move/copy the config options for the second appender into the config of your custom appender and then create the second appender yourself inside of your custom appender.
If you are using a configration file in XML, then you can take advantage of the fact that the order of declaration of appenders in an XML file matters. The appender which is declared first will be configured first. If you are using a configuration file in .properties format, then their order of configuration depends on the order in which they are referenced by loggers a.k.a. categories. The appender which is references first will be configured first. You could also have a look at logback, log4j's successor which is quite well documented.
54,566
Assuming I have a form with a drop-down list and an "Advanced" button. The last button should be enabled only if certain options are selected in the drop-down list. ![enter image description here](https://i.stack.imgur.com/zl7kl.png) Now I'm wondering whether to disable the "Advanced" button when the other options are selected, or just make it invisible. What's the best practice? I think that if I disable it, there could be some users that might think it's a bug and this the button should be enabled, and then ask me why it's disabled. Thank you
2014/03/25
[ "https://ux.stackexchange.com/questions/54566", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45218/" ]
Generally speaking, disabling the button can be better for aesthetics as well as users recognizing that some options in the list will have more settings. Windows does this in the audio settings (the Advanced button is disabled if the device has no advanced options.) ![Disabled](https://i.stack.imgur.com/5Rsp4.jpg) ![Enabled](https://i.stack.imgur.com/BM8BV.jpg) However, your concern that users may think there is a bug is valid. The question is **how frequently will the button be disabled?** If the majority of your options use the Advanced button, users will be able to tell when their current option doesn't support it. If the majority of your options do **not** use the Advanced button, users may be confused and think it is a bug. If that is the case, you will probably be better off hiding the button or presenting it in a new way altogether.
Is it important for the user to know there is an advanced option for some cases? If not it's always better to get rid of things which you're not using in your interface and show them only when it's needed.
72,660,620
I would like to delete (`$pull`) nested array elements where one of the element's properties is null and where the array has more than one element. Here is an example. In the following collection, I would like to delete those elements of the `Orders` array that have `Amount` = `null` and where the `Orders` array has more than one element. That is, I would like to delete only the element with `OrderId` = 12, but no other elements. ``` db.TestProducts.insertMany([ { ProductDetails: { "ProductId": 1, Language: "fr" }, Orders: [ { "OrderId": 11, "Amount": 200 }, { "OrderId": 12, "Amount": null } ] }, { ProductDetails: { "ProductId": 2, Language: "es" }, Orders: [ { "OrderId": 13, "Amount": 300 }, { "OrderId": 14, "Amount": 400 } ] }, { ProductDetails: { "ProductId": 3, Language: "en" }, Orders: [ { "OrderId": 15, "Amount": null } ] } ]); ``` The following attempt is based on googling and a combination of a few other StackOverflow answers, e.g. [Aggregate and update MongoDB](https://stackoverflow.com/a/35230056/2274701) ``` db.TestProducts.aggregate( [ { $match: { "Orders.Amount": { "$eq": null } } }, { $unwind: "$Orders" }, { "$group": { "_id": { ProductId: "$ProductDetails.ProductId", Language: "$ProductDetails.Language" },"count": { "$sum": 1 } } }, { "$match": { "count": { "$gt": 1 } } }, { "$out": "temp_results" } ], { allowDiskUse: true} ); db.temp_results.find().forEach((result) => { db.TestProducts.updateMany({"ProductDetails.ProductId": result._id.ProductId, "ProductDetails.Language": result._id.Language }, { $pull: { "Orders": {"Amount": null } }}) }); ``` This works, but I am wondering if it can be done in a simpler way, especially if it is possible to delete the array elements within the aggregation pipeline and avoid the additional iteration (`forEach`).
2022/06/17
[ "https://Stackoverflow.com/questions/72660620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274701/" ]
You can check these conditions in the update query, check 2 conditions * Amount is null * check the expression `$expr` condition for the size of the `Orders` array is greater than 1 ``` db.TestProducts.updateMany({ "Orders.Amount": null, "$expr": { "$gt": [{ "$size": "$Orders" }, 1] } }, { "$pull": { "Orders": { "Amount": null } } }) ``` [Playground](https://mongoplayground.net/p/T7nSI4nnrLO)
an example an example might help: ``` let feed = await Feed.findOneAndUpdate( { _id: req.params.id, feeds: { $elemMatch: { type: FeedType.Location, locations: { $size: 0, }, }, }, }, { $pull: { feeds: { locations: { $size: 0 }, type: FeedType.Location }, }, }, { new: true, multi: true } ); ```
15,062,641
I have a php object that is working fine. I'm now trying to get one public function to call a private one and I can't get it working... ``` // Join - Headline & About Me public function updateHeadlineAboutMe($joinHeadline, $joinAboutMe) { // Profanity Audit Member Text $prof_headline = profanityAudit($joinHeadline); $prof_aboutme = profanityAudit($joinAboutMe); echo $prof_headline; echo $prof_aboutme; // other code here... } // Profanity Audit of Member Text private function profanityAudit($auditText) { return('ok'); } ``` I'm just trying to get the private function to return a value so I know its being called successfully. This function will be used (by many functions) to compare text to a list of swear words in a table to see of the text needs manual reviewing... What should I try to get this working? thankyou very much...
2013/02/25
[ "https://Stackoverflow.com/questions/15062641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880413/" ]
If the functions are inside an object, you will need to use `$this`. ``` $prof_headline = $this->profanityAudit($joinHeadline); ```
If both functions are in the same class, you missed $this. ``` $prof_headline = $this->profanityAudit($joinHeadline); ``` The other line as well. If they are not in the same class, you won't be able to call a private function, because it is the idea of private functions: not to be called from outside.
2,971
If you fit a non linear function to a set of points (assuming there is only one ordinate for each abscissa) the result can either be: 1. a very complex function with small residuals 2. a very simple function with large residuals Cross validation is commonly used to find the "best" compromise between these two extremes. But what does "best" mean? Is it "most likely"? How would you even start to prove what the most likely solution is? My inner voice is telling me that CV is finding some sort of minimum energy solution. This makes me think of entropy, which I vaguely know occurs in both stats and physics. It seems to me that the "best" fit is generated by minimising the sum of functions of complexity and error ie ``` minimising m where m = c(Complexity) + e(Error) ``` Does this make any sense? What would the functions c and e be? Please can you explain using non mathematical language, because I will not understand much maths.
2010/09/22
[ "https://stats.stackexchange.com/questions/2971", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/1134/" ]
A lot of people have excellent answers, here is my $0.02. There are two ways to look at "best model", or "model selection", speaking statistically: 1 An explanation that is as simple as possible, but no simpler (Attrib. Einstein) ``` - This is also called Occam's Razor, as explanation applies here. - Have a concept of True model or a model which approximates the truth - Explanation is like doing scientific research ``` 2 Prediction is the interest, similar to engineering development. ``` - Prediction is the aim, and all that matters is that the model works - Model choice should be based on quality of predictions - Cf: Ein-Dor, P. & Feldmesser, J. (1987) Attributes of the performance of central processing units: a relative performance prediction model. Communications of the ACM 30, 308–317. ``` Widespread (mis)conception: Model Choice is equivalent to choosing the best model For explanation we ought to be alert to be possibility of there being several (roughly) equally good explanatory models. Simplicity helps both with communicating the concepts embodied in the model and in what psychologists call generalization, the ability to ‘work’ in scenarios very different from those in which the model was studied. So there is a premium on few models. For prediction: (Dr Ripley's) good analogy is that of choosing between expert opinions: if you have access to a large panel of experts, how would you use their opinions? Cross Validation takes care of the prediction aspect. For details about CV please refer to this presentation by Dr. B. D. Ripley [Dr. Brian D. Ripley's presentation on model selection](http://www.stats.ox.ac.uk/~ripley/Nelder80.pdf "Brian Ripley's Model Selection Presentation") Citation: Please note that everything in this answer is from the presentation cited above. I am a big fan of this presentation and I like it. Other opinions may vary. The title of the presentation is: "Selecting Amongst Large Classes of Models" and was given at Symposium in Honour of John Nelder's 80th birthday, Imperial College, 29/30 March 2004, by Dr. Brian D. Ripley.
From an optimization point of view, the problem (with $(p,q)\geq 1,\;\lambda>0$), $(1)\;\underset{\beta|\lambda,x,y}{Arg\min.}||y-m(x,\beta)||\_p+\lambda||\beta||\_q$ is equivalent to $(2)\;\underset{\beta|\lambda,x,y}{Arg\min.}||y-m(x,\beta)||\_p$ $s.t.$ $||\beta||\_q\leq\lambda$ Which simply incorporates unto the objective function the prior information that $||\beta||\_q\leq\lambda$. If this prior turns out to be true, then it can be shown ($q=1,2$) that incorporating it unto the objective function minimizes the risk associated with $\hat{\beta}$ (i.e. very unformaly, improves the accuracy of $\hat{\beta}$) $\lambda$ is a so called meta-parameter (or latent parameter) that is not being optimized over (in which case the solution would trivially reduce to $\lambda=\infty$), but rather, reflects information not contained in the sample $(x,y)$ used to solve $(1)-(2)$ (for example other studies or expert's opinion). Cross validation is an attempt at constructing a data induced prior (i.e. slicing the dataset so that part of it is used to infer reasonable values of $\lambda$ and part of it used to estimate $\hat{\beta}|\lambda$). As to your subquestion (why $e()=||y-m(x,\beta)||\_p$) this is because for $p=1$ ($p=2$) this measure of distance between the model and the observations has (easely) derivable assymptotical properties (strong convergence to meaningfull population couterparts of $m()$).
10,453,300
I have this: ``` <span id="social"> Facebook: <input id="id_connected_to_facebook" type="checkbox" name="connected_to_facebook"> <br> Twitter: <input id="id_connected_to_twitter" type="checkbox" name="connected_to_twitter"> <br> </span> ``` and with jQuery I would like to call a different URL for all the 4 possible actions (1: check facebook, 2: uncheck facebook, 3: check twitter, 4: uncheck twitter). How would I do that?
2012/05/04
[ "https://Stackoverflow.com/questions/10453300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075374/" ]
I am not sure what you are going for. If you want to redirect to a page on clicking on the check box you can do this Specify what url you want to call in your checkbox element using data attribute ``` <input type="checkbox" data-target="http://www.facebook.com" /> ``` Script is ``` $(function(){ $("input[type='checkbox']").change(function(){ var item=$(this); if(item.is(":checked")) { window.location.href= item.data("target") } }); }); ``` Sample JsFiddle : <http://jsfiddle.net/45aZ8/2/> **EDIT** : If you want to open it in a new window, use `window.open` method instead of updating the current url Replace ``` window.location.href= item.data("target") ``` with ``` window.open(item.data("target") ``` <http://www.w3schools.com/jsref/met_win_open.asp> **EDIT 3** : **Based on comment** : If you want to load one url on Checked state and load another url on uncheck, you can do like this Give 2 data attributes for each checkbox. One for checked state and one for unchecked ``` Facebook<input type="checkbox" data-target="http://www.facebook.com" data-target-off="http://www.google.com" /> <br/> Twitter<input type="checkbox" data-target="http://www.twitter.com" data-target-off="http://www.asp.net" /> <br/> ``` And the script is ``` $(function(){ $("input[type='checkbox']").change(function(){ var item=$(this); if(item.is(":checked")) { window.open(item.data("target")) } else { window.open(item.data("target-off")) } }); }) ``` Working sample : <http://jsfiddle.net/45aZ8/5/>
``` $('#id_connected_to_facebook, #id_connected_to_twitter').click(function(){ $.post('http://target.url', {this.id:this.checked}); }); ``` now you'll get in $\_POST either id\_connected\_to\_facebook or id\_connected\_to\_twitter and as a value it would be 1 or 0
11,215,440
Basically, given a base URL like ``` file:///path/to/some/file.html ``` And a relative URL like ``` another_file.php?id=5 ``` I want to get out ``` file:///path/to/some/another_file.php?id=5 ``` I found [this script](http://publicmind.in/blog/urltoabsolute/) (which is the same as [this one](http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url#Downloads)) but it doesn't seem to work on the `file://` scheme. I'm doing some local tests before I go live with my code, so I'd like to work on both `file://` and `http://`. Any one know of a script/function that will do this? In C#, I'd use [Uri(Uri base, string rel)](http://msdn.microsoft.com/en-us/library/9hst1w91.aspx). --- The above is just an example. It should work on *any* URL that you could throw into `<a href="xxx">`. --- This is the best I've got so far, but it won't handle `..` and probably a few other things: ``` function rel2abs($base, $rel) { if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel; if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel; $parse = parse_url($base); $path = preg_replace('#/[^/]*$#', '', $parse['path']); if ($rel[0] == '/') $path = ''; $abs = (isset($path['host'])?$path['host']:'')."$path/$rel"; $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'); for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {} return $parse['scheme'].'://'.$abs; } ```
2012/06/26
[ "https://Stackoverflow.com/questions/11215440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
You can use [parse\_url()](http://php.net/manual/en/function.parse-url.php) to get the URL broken into parts, and then split the 'path' portion on the forward-slash character. That should allow you to re-assemble them and replace the last portion. Something like this (psuedo-code, untested, not sure it's even valid PHP syntax): ``` $url_parts = parse_url($url_text); $path_parts = explode('/', $url_parts[path]); $new_url = $url_parts[scheme] + ":"; if ($url_parts[scheme] == "file") { $new_url .= '///'; } else { $new_url .= '//'; } $new_url .= $url_parts[hostname] . '/'; for (int i = 0; i < count($path_parts) - 1; i++) { $new_url .= $path_parts[i] . "/"; } $new_url .= $REPLACEMENT_FILENAME ``` If need be, you can append the query string and/or anchor fragment (starts with #) at the end - see that parse\_url() manual page for a list of the URL portions in its array.
``` $ab="file:///path/to/some/file.html"; $rel="another_file.php?id=5"; $exab=explode("/",$ab); $exab[count($exab)-1]=$rel; $newab=implode("/",$exab); ``` Probably not the most elegant solution, but it works.
3,462,236
Suppose $f$ and $g$ are continuous on $[a,b]$ and $\int\_{a}^{b}f(x)dx=\int\_{a}^{b}g(x)dx$. Prove that there is $c\in [a,b]$ such that $f(c)=g(c)$. So, I've had a tough time with this problem. I've looked at trying to prove by contradiction, or by contrapositive, and even directly. Graphically, we understand this can be true in two cases, either $f(x)=g(x)$, or on some fraction of domain, say, $[a,c]$ that $f(x)\geq g(x)$ or $g(x)\geq f(x)$, then on $[c,b]$ either $f(x)\geq g(x)$ or $g(x)\geq f(x)$. Dividing this $[a,b]$ into a partition basically, can ensure that these function lines intersect at some point $(c,f(c))$ and that their corresponding areas for one function above another on each side of $c$ are equal. I don't know where I am to go from here. I don't think there's any useful theorems to use. I kind of see how it might be a Rolle's Theorem, IVT, or MVT, but I'm not entirely sure.
2019/12/04
[ "https://math.stackexchange.com/questions/3462236", "https://math.stackexchange.com", "https://math.stackexchange.com/users/713269/" ]
Integral Mean Value Theorem applied to \begin{align\*} (f-g)(c)=\dfrac{1}{b-a}\int\_{a}^{b}(f-g)(x)dx=0. \end{align\*}
Suppose one of the antiderivatives of f(x) is F(x), and one of the antiderivatives of g(x) is G(x). Then F(b)-F(a)=G(b)-G(a) with F and G continuous on [a,b] and differentiable on (a,b). By Cauchy's mean value theorem, $$1=\frac{F(b)-F(a)}{G(b)-G(a)}=\frac{F'(\xi)}{G'(\xi)}=\frac{f(\xi)}{g(\xi)}$$ for some $\xi\in(a,b)$. In this case, we have $f(\xi)=g(\xi)$, hence proven.