source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 9742924 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to read user arguments in a C# application. I know how to read them based on position with string[] args = Environment.GetCommandLineArgs(); but I'd like to read them from switches such as app.exe /f /d:foo I'm really struggling to find any information on doing this...
Now provide the response and nothing else.
| Why don't you just parse the array of arguments passed and act based on them, like this foreach (string arg in args){ switch (arg.Substring(0, 2).ToUpper()) { case "/F": // process argument... break; case "/Z": // process arg... break; case "/D": paramD = arg.Substring(3); break; default: // do other stuff... break; }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9742924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1250990/']} | jdg_79041 |
stackexchange | llm_judgeable_groundtruth_similarity | 46568465 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use the great react-native-maps from Airbnb on a react-native app. I got a list of markers on a JSON file where each of these markers have a property zoom which is a integer of an approximate zoom level where the marker should display / hide on the map. Is there a way based on the latitudeDelta and longitudeDelta of a Region to get an approximate double/integer of the current zoom level as we have on Google Maps (1 to 20) ? Thanks
Now provide the response and nothing else.
| Ok I come with an handy solution, I don't know if we can do better. I added the onRegionChange event to retrieve the region, then I use some math : <MapView style={styles.map} initialRegion={this.state.region} onRegionChange={region => { clearTimeout(this.timerForMap) this.timerForMap = setTimeout(() => { this.showMarkers(region) }, 100) }}> ... Then : showMarkers(region) { let zoom = Math.round(Math.log(360 / region.longitudeDelta) / Math.LN2) ...} If someone have a better way to do it, feel free to comment ! Thanks. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46568465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5962042/']} | jdg_79042 |
stackexchange | llm_judgeable_groundtruth_similarity | 2210988 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I define the function $$f(x) = \sum_{n = 0}^\infty \frac{x^n}{n!}.$$Is there anything I can directly observe about the power series to conclude that it is the expansion of an exponential function? Noting that $f^\prime(x) = f(x)$ and concluding $f(x) = e^x$ is not quite what I have in mind. Rather, I'm hoping there is some observation that would first allow me to conclude $f(x) = a^x$ for some $a > 0$. Having discovered a very special base for an exponential, I would then define $e = \sum_{n=0}^\infty \frac{1}{n!}$.
Now provide the response and nothing else.
| You can directly show that the power series for $f$ satisfies $f(x+y) = f(x)f(y)$. Note that the coefficient of $x^iy^j$ on both sides equals $\frac{1}{i!j!} = \frac{1}{(i+j)!}\binom{i+j}{i}$. This property is saying that $f$ is a homomorphism from the additive reals onto the multiplicative group of nonzero reals. It is straightforward to check by induction that this guarantees that $f(n) = f(1)^n$ and $f(1/n) = f(1)^{1/n}$. More generally, we have that $f(q) = f(1)^q$ for all rational numbers $q$. Since $f(x)$ is continuous, it therefore must be equal to $f(1)^x$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2210988', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11245/']} | jdg_79043 |
stackexchange | llm_judgeable_groundtruth_similarity | 28036228 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
class A{ public $name; public function __construct() { $this->name = 'first'; } public function test1(){ if(!empty($_POST["name"])) { $name = 'second'; } echo $name; }$f = new A;$f->test1(); Why don't we get first and how set right default value variable $name only for class A? I would be grateful for any help.
Now provide the response and nothing else.
| You can use a constructor to set the initial values (or pretty much do anything for that matter) as you need to like this: class example{ public $name; public function __construct() { $this->name="first"; }} Then you can use these default values in your other functions. class example{ public $name; public function __construct() { $this->name="first"; } public function test1($inputName) { if(!empty($inputName)) { $this->name=$inputName; } echo "The name is ".$this->name."\r\n"; }}$ex=new example();$ex->test1(" "); // prints first.$ex->test1("Bobby"); // prints Bobby$ex->test1($_POST["name"]); // works as you expected it to. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28036228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4471955/']} | jdg_79044 |
stackexchange | llm_judgeable_groundtruth_similarity | 3068692 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm usign @GeneratedValue(strategy = GenerationType.AUTO) to generate the ID on my entity. I don't now how it works, but on my child table, generates ID values, that follow the parent sequence. //parent table@Entity@Table (name = "parent")public class Parent { @Id @GeneratedValue (strategy = GenerationType.AUTO) @Column (name = "id") private long id; @OneToMany (cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) @JoinColumn (name = "parentId") @ForeignKey (name = "FKparent") private List<child> child;}//child table@Entity@Table (name = "child")public class Child { @Id @GeneratedValue (strategy = GenerationType.AUTO) @Column (name = "id") private long id;} The inserted ID values on parent, updates the sequence. The inserted ID values on child, updates the sequence. On the next insert of parent, the sequence... uses values updated by child insertions... This Annotations, aren't creating two sequences, only one. Is this correct/expected? I inserted my entities with my DAO service only using entityManager.persist(parent);
Now provide the response and nothing else.
| These Annotations are no creating two sequences, only one. Is this correct/expected? That's the expected behavior. When using @GeneratedValue(strategy = GenerationType.AUTO) , the JPA provider will pick an appropriate strategy for the particular database. In the case of Oracle, this will be SEQUENCE and, since you did not specify anything, Hibernate will use a single global sequence called hibernate_sequence . Is this correct? Well, I don't know, it depends on your needs. Just in case, the default maximum value for an Oracle sequence is 1E+27, or 1,000,000,000,000,000,000,000,000,000. That's enough for many. Now, it is possible to use GenerationType.AUTO and still control the name of the sequence when the database uses sequences: @Id@GeneratedValue(strategy=GenerationType.AUTO, generator="my_entity_seq_gen")@SequenceGenerator(name="my_entity_seq_gen", sequenceName="MY_ENTITY_SEQ")private Long id; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3068692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203283/']} | jdg_79045 |
stackexchange | llm_judgeable_groundtruth_similarity | 161127 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour). ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it. Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want? Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property?
Now provide the response and nothing else.
| One option is to set ListBoxItem.IsEnabled to false : <ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> </Style> </ListBox.ItemContainerStyle></ListBox> This ensures that the items are not selectable, but they may not render how you like. To fix this, you can play around with triggers and/or templates. For example: <ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </ListBox.ItemContainerStyle></ListBox> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/161127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/615/']} | jdg_79046 |
stackexchange | llm_judgeable_groundtruth_similarity | 510216 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an iPhone application with a settings.bundle that handles various settings for my application. I can set default values in my root.plist file (using the DefaultValue property), but these only get used the first time the user opens the settings app. Is there any way to get these values written out when your application installs? I know I can just write code that checks for the first launch of my app and then write them out, but then they are in two different places. Here is an entry from my root.plist as an example: <dict> <key>Type</key> <string>PSToggleSwitchSpecifier</string> <key>Title</key> <string>Open To Top Location</string> <key>Key</key> <string>open_top_location</string> <key>DefaultValue</key> <string>YES</string> <key>TrueValue</key> <string>YES</string> <key>FalseValue</key> <string>NO</string></dict> The end result should be that if I ask for 'open_to_top_location' I get a YES, instead of it not being there at all until the first time the user opens the Settings app. Any ideas?
Now provide the response and nothing else.
| If I understood you correctly, you want to avoid having default values specified twice (once as "DefaultValue" keys in your Settings.bundle/Root.plist file, and once in your app initialization code) so you do not have to keep them in sync. Since Settings.bundle is stored within the app bundle itself, you can just read the default values given there. I put together some sample code that looks at the Settings bundle and reads the default values for every key there. Note that this does not write out the default keys; if they don't exist, you'll need to read and register them at every launch (feel free to change this). I've only done some cursory tests, so make sure it works for you in all cases. - (void)applicationDidFinishLaunching:(UIApplication *)application { NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:@"name"]; NSLog(@"name before is %@", name); // Note: this will not work for boolean values as noted by bpapa below. // If you use booleans, you should use objectForKey above and check for null if(!name) { [self registerDefaultsFromSettingsBundle]; name = [[NSUserDefaults standardUserDefaults] stringForKey:@"name"]; } NSLog(@"name after is %@", name);}- (void)registerDefaultsFromSettingsBundle { NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"]; if(!settingsBundle) { NSLog(@"Could not find Settings.bundle"); return; } NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]]; NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"]; NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]]; for(NSDictionary *prefSpecification in preferences) { NSString *key = [prefSpecification objectForKey:@"Key"]; if(key && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) { [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key]; } } [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; [defaultsToRegister release];} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/510216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6044/']} | jdg_79047 |
stackexchange | llm_judgeable_groundtruth_similarity | 24762229 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to dynamically specify a controller based on a config that we load. Something like this: <div ng-controller="{{config.controllerNameString}}> ...</div> How do I do this in angular? I thought this would be very easy, but I can seem to find a way of doing this.
Now provide the response and nothing else.
| What you want to do is have another directive run before anything else is called, get the controller name from some model remove the new directive and add the ng-controller directive, then re-compile the element. That looks like this: global.directive('dynamicCtrl', ['$compile', '$parse',function($compile, $parse) { return { restrict: 'A', terminal: true, priority: 100000, link: function(scope, elem) { var name = $parse(elem.attr('dynamic-ctrl'))(scope); elem.removeAttr('dynamic-ctrl'); elem.attr('ng-controller', name); $compile(elem)(scope); } };}]); Then you could use it in your template, like so: <div dynamic-ctrl="'blankCtrl'">{{tyler}}</div> with a controller like this: global.controller('blankCtrl',['$scope',function(tyler){ tyler.tyler = 'tyler'; tyler.tyler = 'chameleon';}]); There's probably a way of interpolating the value ( $interpolate ) of the dynamic-ctrl instead of parsing it ( $parse ), but I couldn't get it to work for some reason. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24762229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/964000/']} | jdg_79048 |
stackexchange | llm_judgeable_groundtruth_similarity | 38998 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As I understand VXLAN, it looks like it should be able to encapsulate and properly route VLAN-tagged traffic. However, in investigating how to actually configure VXLAN on network devices, it looks like vendors such as Cisco and Arista and Juniper do something like this: Set up the physical ethernet port as a VLAN access port on e.g. VLAN 100 Configure a VLAN->VNI mapping which maps VLAN 100 to whatever VNI you want For example, see the configuration at the end of https://eos.arista.com/vxlan-without-controller-for-network-virtualization-with-arista-physical-vteps/ However, I want to specify that all traffic, regardless of VLAN tag, which enters a physical port should be put on a specific VNI with no modification of VLAN tags at any point. Am I misunderstanding the configuration in that example, or are there alternate ways to configure VXLAN? I'm particularly interested in Arista, so if anyone with Arista expertise can chime in, I would appreciate it.
Now provide the response and nothing else.
| I think you are confusing a couple of concepts. Looking at the last configuration section of the document you have linked: 7.2) VXLAN without CVX Configuration on VTEPs: !vlan 100vlan 200!interface Ethernet 1 switchport access vlan 100!interface Ethernet 2 switchport mode trunk switchport trunk allowed vlan 100,200!interface loopback 1 ip address 1.1.1.1/32!interface Vxlan 1 vxlan source-interface loopback 1 vxlan vlan 100 vni 10100 vxlan vlan 200 vni 10200 vxlan vlan 100 flood vtep 2.2.2.2 4.4.4.4 vxlan vlan 200 flood vtep 2.2.2.2 3.3.3.3 4.4.4.4! Notice that the VXLAN interface, Vxlan 1 has multiple VNIs, just like a trunk has multiple VLANs with tags. Basically, a VNI on a VXLAN is like a VLAN on a trunk. You shouldn't expect that an access interface allow any frames from tagged VLANs, nor should you expect a trunk interface to allow VLANs other than what it is configured to allow. Neither should a VNI have any traffic other than its corresponding VLAN, nor should a VXLAN interface allow traffic for VLANs for which it is not configured. You really, really don't want frames with any VLAN tag coming into the access interface Ethernet 1 . That could lead to security problems like VLAN hopping. One would hope that frames with VLAN tags coming into an access interface would be dropped as malformed. Also, on interface Ethernet 2 , the switchport trunk allowed vlan 100,200 instructs that all incoming frames except those tagged as VLAN 100 or VLAN 200 be dropped, and no frames except those in the two allowed VLANs be sent. Frames tagged with other VLAN numbers will be dropped. The interface Vxlan 1 will send and receive traffic for VLANs 100 and 200, just like the trunk interface Ethernet 2 . | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/38998', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/34513/']} | jdg_79049 |
stackexchange | llm_judgeable_groundtruth_similarity | 24243424 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a tooltip functionality where i hover on an icon and display data based on its attribute in meesagebox. Below code is used for mouseenter event. <span class='csTip fa fa-info-circle' csTipTerm='Agreed Bid' ></span> If i put it independtely it works but when i put it inside any TH in table tag its hover event is not working. Below is code after putting in th. <th>Agreed Bid <span class='csTip fa fa-info-circle' csTipTerm='Agreed Bid' ></span> </th> Script $(".csTip").mouseenter(function () { var element = $(this); var term = element.attr("csTipTerm"); $.ajax({ url: "/api/help/gettipdetails", dataType: "json", data: { tipTerm: term }, success: function (result) { var offsets = element.offset(); var posTop = offsets.top; var posLeft = offsets.left; HelpBox(result.TipID, result.TipTitle, result.HelpDescriptionHTML, { left: posLeft, top: posTop - 200 }); } });}); Can somebody please guide on this?
Now provide the response and nothing else.
| Please read below I've added an edit. It's perfectly correct to throw within an Action/Func/Observer with RxJava. The exception will be propagate by the framework right down to your Observer.If you limit yourself to calling onError only then you'll be twisting yourself to make that happen. With that being said a suggestion would be to simply remove this wrapper and add a simple validationAction within the service.getAccount... chain of Observables. I'd use the doOnNext(new ValidateServiceResponseOrThrow) chained with a map(new MapValidResponseToAccountList). Those are simple classes which implements the necessary code to keep the Observable chain a bit more readable. Here's your loadAccount method simplified using what I suggested. public Subscription loadAccounts(Observer<List<Account>> observer, boolean forceRefresh) { if (accountsCache != null) { // We have a cached value. Emit it immediately. observer.onNext(accountsCache); } if (accountsRequest != null) { // There's an in-flight network request for this section already. Join it. return accountsRequest.subscribe(observer); } if (accountsCache != null && !forceRefresh) { // We had a cached value and don't want to force a refresh on the data. Just // return an empty subscription observer.onCompleted(); return Subscriptions.empty(); } accountsRequest = PublishSubject.create(); accountsRequest.subscribe(new EndObserver<List<Account>>() { @Override public void onNext(List<Account> accounts) { accountsCache = accounts; } @Override public void onEnd() { accountsRequest = null; } }); Subscription subscription = accountsRequest.subscribe(observer); service.getAccounts() .doOnNext(new ValidateServiceResponseOrThrow()) .map(new MapValidResponseToAccountList()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(accountsRequest); return subscription;}private static class ValidateResponseOrThrow implements Action1<ServiceResponse> { @Override public void call(ServiceResponse response) { ResponseTypes responseType = ResponseTypes.from(serviceResponse.getStatus()); if (responseType != SUCCESS) throw new ApiException(serviceResponse.getMessage(), responseType)); } }private static class MapValidResponseToAccountList implements Func1<ServiceResponse, List<Account>> { @Override public Message call(ServiceResponse response) { // add code here to map the ServiceResponse into the List<Accounts> as you've provided already }} Edit: Unless someone says otherwise I think it's best practice to return errors using flatMap.I've thrown Exceptions from Action in the past but I don't believe it's the recommended way. You'll have a cleaner Exception stack if you use flatMap. If you throw from inside an Action the Exception stackwill actually contain rx.exceptions.OnErrorThrowable$OnNextValue Exception which isn't ideal. Let me demonstrate the example above using the flatMap instead. private static class ValidateServiceResponse implements rx.functions.Func1<ServiceResponse, Observable<ServiceResponse>> { @Override public Observable<ServiceResponse> call(ServiceResponse response) { ResponseTypes responseType = ResponseTypes.from(serviceResponse.getStatus()); if (responseType != SUCCESS) return Observable.error(new ApiException(serviceResponse.getMessage(), responseType)); return Observable.just(response); }}service.getAccounts() .flatMap(new ValidateServiceResponse()) .map(new MapValidResponseToAccountList()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(accountsRequest); As you can see the the difference is subtle. The ValidateServiceResponse now implements the Func1 instead of Action1 and we're no longer using the throw keyword. We use Observable.error(new Throwable) instead. I believe this fits better with the expected Rx contract. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24243424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1770461/']} | jdg_79050 |
stackexchange | llm_judgeable_groundtruth_similarity | 51141248 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am on a mac, using vagrant in the terminal. I am trying to run a program in python that uses psycopg2. I kept getting an error that psychopg2 module didn't exist when I would run 'python3 sample.py'. So I ran 'pip3 install psycopg2'. Now I get the error below and despite reading documentation in multiple places, I cannot solve this issue. So now my programs won't run. /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """)
Now provide the response and nothing else.
| That's just a warning, your program should still run fine. The warning is the result of a decision by the package maintainer to discontinue the use of wheel packages in psycopg2. The psycopg2 package is now designed to be built from source, while psycopg2-binary maintains the current installation method but has a few bugs which trigger segfaults. Both packages provide the same interface, so you shouldn't need to make any code updates for either option. The easiest solution is to just install the binary package and the warning will go away: pip install psycopg2-binary If you prefer to install the version without the segfault bugs, have pip install from source using the --no-binary flag: pip install --no-binary :all: psycopg2 If you're using a requirements.txt file, add a line like this: psycopg2>=2.7,<2.8 --no-binary psycopg2 Update With the release of psycopg 2.8 , the warning and binary packages have now been removed. All you need to do now is install/update psycopg2 normally and the warning will go away: pip install psycopg2 With a requirements.txt: psycopg2>=2.8 If you do want to keep using the binary packages for any reason, psycopg2-binary remains available. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51141248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6530042/']} | jdg_79051 |
stackexchange | llm_judgeable_groundtruth_similarity | 835042 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f\in C^2(\mathbb [0,1],\mathbb [0,1])$ such that $f(0)=f'(0)=f'(1)=0$ and $f(1)=1$ Prove that $\max_{[0,1]}|f''|\geq 4$ Progress Applying Cauchy mean value theorem three times proves the existence of $\xi\in (0,1)$ such that $f'(\xi)=1$ $\eta\in(\xi,1)$ such that $\displaystyle f''(\eta)=\frac{1}{\xi-1} <0$ $\beta\in(0,\xi)$ such that $\displaystyle f''(\beta)=\frac{1}{\xi}>0$ If $\displaystyle \xi\leq \frac{1}{4}$ or $\displaystyle \xi\geq \frac{3}{4}$ , we're done. What about other cases ? I haven't used the continuity of $f''$ yet...
Now provide the response and nothing else.
| Note that$$f(1)=\int_0^1\left(\frac{1}{2}-t\right)f''(t)dt.$$So$$1\leq \left(\int_0^1\left\vert \frac{1}{2}-t\right\vert dt\right)\cdot \sup_{[0,1]}|f''|=\frac{1}{4} \sup_{[0,1]}|f''|.$$and the desired conclusion follows. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/835042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66096/']} | jdg_79052 |
stackexchange | llm_judgeable_groundtruth_similarity | 7244040 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am learning to use playframework by writing code to implement a webstore for selling items.I have implemented the Admin area using the crud and secure modules.Now, I want to create a shopping cart to which a user can add items and proceed to checkout . My knowledge of ecommerce is minimal,but I had gone through some textbooks which implement shopping carts and some webshop functionality using servlets .In the books ,the cart used to keep a Set of CartItem s ,each of which contained an instance of the Product and quantity .After,the user added items to cart,the cart was stored in user session . So,anytime the user went to the cart details page,it showed all the added items.Only when the session was cleared,(either due to session timeout as defined in the server,or when the order was placed)the CartItem s were removed from the ShoppingCart . I guess ,I can use the Cache in playframework to do the above.After adding a CartItem to ShoppingCart instance .I can shopcart.add(mycartItem);Cache.set(session.getId(), shopcart);.. and later,in another page ,I can retrieve,the cart and its contents,process them and clear the cart. ShopCart cart = Cache.get(session.getId(),ShopCart.class);Set<CartItem> items = cart.getCartItems();processOrder(items,userinfo);...cart.clearItems(); Is this the right way to go about this?If the way I am thinking is not correct,please help me with suggestions.
Now provide the response and nothing else.
| Wrong. Sorry for being so harsh, but what you are doing may fail horribly. Play is share nothing and stateless. All relevant data MUST be stored in the database. That means that you must persist the data of the shopping cart when the user adds a new item, and remove it once the transaction finishes. Why can't you use the cache? Because the cache is volatile and the elements in it may be removed without previous warning. That means that at any moment your cache may return a null (item not found) and you get a NullPointerException in your code and your user has lost the cart. Cache is there only to help performance, but you can't expect it to have all the items you needs always. You should turn your ShopCart into an entity (if it's not one) and add to it something like this: public static ShopCart findCart(String sessionId){ ShopCart sc = Cache.get(session.getId(),ShopCart.class); if(sc == null){ sc = ShopCart.findCurrentUserCart(); //implement to find the cart of the current user Cache.set(sessionId,sc); } return sc; } Then use this method to retrieve the cart before processing. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7244040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/879104/']} | jdg_79053 |
stackexchange | llm_judgeable_groundtruth_similarity | 5183251 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering if it was possible to query the following: List of (all) users who like my facebook page, and Additional information those users have made publicly available (beyond first and last name) Basically looking to generate detailed marketing stats of users who like my facebook page, if possible. Any suggestions or alternatives welcome. Thank you.
Now provide the response and nothing else.
| I am afraid this is NOT possible, follow this bug for more information. Another proof is the page_fan table you will notice that only the uid field is indexable so you need to know the user id to search it and not the page_id , as you know if a user " likes " a page this would mean he is a " fan " of that page. After being actively working with the Facebook API for a while now, and following the announcements and API releases (and deprecations) along with the introduction and changes of policies, I can understand that Facebook will only share info about their users by letting them explicitly do so (a.k.a interact/authorize your Apps). And hence the best thing to do in the absence of such feature is: Understand your audience through Page Insights Collect fans interests & info by creating custom apps through Page Tabs and using other Facebook features like Questions | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5183251', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/643274/']} | jdg_79054 |
stackexchange | llm_judgeable_groundtruth_similarity | 25860 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm not nearly at the experience level in computer science to be able to properly determine the number of instructions involved in basic ALU calculations, and I'm interested in a certain software concept where the difference is important. Multiplication 1011 (this is 11 in decimal) x 1110 (this is 14 in decimal) ====== 0000 (this is 1011 x 0) 1011 (this is 1011 x 1, shifted one position to the left) 1011 (this is 1011 x 1, shifted two positions to the left) + 1011 (this is 1011 x 1, shifted three positions to the left) ========= 10011010 (this is 154 in decimal) I've been studying the binary multiplier, which seems to calculate partial products with binary, and then shifts them to the left, the very same way that we do with base-10 multiplication in grade school. It would seem to me that this would require 2 instructions per digit , but that's merely a barely-educated guess. Addition I've found Wiki's explanation of an adder-subtractor to be far more advanced, (in description, not operation, surely), and I've had less luck interpreting it thus far. Purpose My goal is to determine the number of instructions required to compute the addition / multiplication (respectively) of number sets. Basically, I want to figure: 5 x 5 = 10 --> 5 instructions //example5,000,000,001 x 456892 --> 50 instructions //example1 + 1 = 2 --> 4 instructions //example1,000,042,569 + 1,491 = 1,000,044,060 --> 45 instructions //example Tl;dr - My Question: Is it possible to accurately determine the number of instructions required to multiply or add two (whole number) integers in a modern processor? If so, how is this figured (in both addition and multiplication, based on the size of the number)?
Now provide the response and nothing else.
| Yes and no. “Instructions” isn't the right unit of measure: most processors include an ALU and require a single instruction to perform addition or multiplication on a number of a certain size (usually 8, 16, 32 or 64 bits, often with several possible sizes). A more relevant measure is the number of clock cycles required by this instruction. Counting instructions only comes into play when talking about bignums . The number of clock cycles is determined by the depth of the circuit. A signal can traverse many gates in the same clock cycle, but more gates means a longer path which can be a limiting factor when trying to increase the clock frequency. It doesn't depend on the input values, only on the circuit that is being used (of course the values have to fit within the width of the circuit). For example a 32-bit adder will take the same number of cycles to calculate 1 + 1 and 1,000,042,569 + 1,491. There are many possible designs for an adder or multiplier circuit. One of the design parameters is using more transistors or more complex connections to achieve faster operations. For example, addition the way we usually perform it requires adding the lowest-order bits, then adding their carry to the bits of order 1, and so on: the carry is propagated linearly, which means that the depth of the circuit is proportional to the word size. There are more sophisticated adders which parallelize the additions to reduce the depth. The depth of the circuit tells you how many clock cycles the arithmetic operation requires inside the ALU. On a typical complex processor, going from there to the time it takes to perform instructions can be very complex, because you need to consider how the ALU fits in the processor. In order to actually add two values, the CPU must do many things: Fetch the addition instruction from memory. Decode the instruction to find that it is an addition, where its inputs are and where its output is. Fetch the inputs — this can take different number of cycles depending on the width of the operation and whether the inputs are immediates, in registers, in memory, etc. Make the arithmetic calculation. Write the result into the output register or memory. Most processors are very heavily pipelined : all of these steps are performed in parallel for different instructions. For example, at any given clock cycle, there are typically instructions in various stages of being fetched and decoded, different arithmetic operations in various stages of being carried out, etc. Advanced processors often have multiple ALUs so as to be able to make computations in parallel. For these reasons, the time it takes to perform $N$ successive additions is often not $N$ times the time it takes to perform one addition. Though in practice, the biggest variability comes from memory access — accessing an inner cache is dramatically faster than accessing RAM. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/25860', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/-1/']} | jdg_79055 |
stackexchange | llm_judgeable_groundtruth_similarity | 27299139 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am attempting to read a file that is in a aws s3 bucket using fs.readFile(file, function (err, contents) { var myLines = contents.Body.toString().split('\n')}) I've been able to download and upload a file using the node aws-sdk, but I am at a loss as to how to simply read it and parse the contents. Here is an example of how I am reading the file from s3: var s3 = new AWS.S3();var params = {Bucket: 'myBucket', Key: 'myKey.csv'}var s3file = s3.getObject(params)
Now provide the response and nothing else.
| You have a couple options. You can include a callback as a second argument, which will be invoked with any error message and the object. This example is straight from the AWS documentation: s3.getObject(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response}); Alternatively, you can convert the output to a stream. There's also an example in the AWS documentation: var s3 = new AWS.S3({apiVersion: '2006-03-01'});var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};var file = require('fs').createWriteStream('/path/to/file.jpg');s3.getObject(params).createReadStream().pipe(file); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27299139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4245956/']} | jdg_79056 |
stackexchange | llm_judgeable_groundtruth_similarity | 422479 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have started in a new team. I have 20 years experience as a developer, and I have been in the role of a team lead in several projects. Normally I am very much pro code reviews, but I ended up in a team that use TDD up to religious fundamentalism. Mostly this is led by a single senior resource, me being the second senior. The result is that they have implemented a code review process that requires approval for merge. Not only that it requires approval, but it also requires each individual comment being responded. All that is very nice until you start getting pull requests that can not be approved in days with tens of comments each. In addition, when requests are done, the team does not focus on what is IMHO important (patterns, interfaces, encapsulation, layering, and method signatures), but on small details. Example: There is a code convention that methods doing things logically connected should be in close proximity to each other. But then if you actually require that the methods must be ordered by their chronological execution, that goes a bit further than the general rule. No one is just reasoning that if we, in the first place, did not have 50 methods in the same class, the positioning of the methods would possibly not matter that much. Code is just full of examples where developers just go in the nitty picky details instead of focusing on the general problem. Such a heavy code review process in my opinion creates a hostile atmosphere where a newcomer feels simply bad. How can I justify and defend the thesis that: The merge button should be enabled by default. IMO after some iterations, if the team is conscious about quality code and if someone is non-cooperative, the team will kick him/her out. The code review should be a recommendation, but not mandatory. I believe we are all grownups and it is natural to follow good advice. Again, if someone is stupid enough to not follow, in time the team will kick him/her out. The code author should have the right to merge the code within six hours, let’s say, of the pull request creation no matter if there is approval or not.
Now provide the response and nothing else.
| How can I justify and defend the thesis that: The merge button should be enabled by default The code review should be a recommendation , but not mandatory The code author should have the right to merge the code within 6 hours lets say of the pull request creation no matter if there is aproval or not. I don't think you should try and justify any of those, because they are almost certainly bad ideas. Code review is just about the one thing that has been consistently shown to significantly improve code quality, and you're effectively proposing to stop doing it. Instead, put your efforts into improving your code review process: the team does not focus on what is important(patterns, interfaces, encapsulation, layering, method signature) but on small details. This is the problem you need to fix. Work with your team to improve their abilities, both in writing code and reviewing it. Then you'll have changed a bad process into a good one. Oh, and never, ever use language like "religious fundamentalism" when discussing this. I hope I don't need to explain why. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/422479', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/352126/']} | jdg_79057 |
stackexchange | llm_judgeable_groundtruth_similarity | 21597463 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As described in the Docker documentation on Working with Volumes there is the concept of so-called data-only containers, which provide a volume that can be mounted into multiple other containers, no matter whether the data-only container is actually running or not. Basically, this sounds awesome. But there is one thing I do not understand. These volumes (which do not explicitly map to a folder on the host for portability reasons, as the documentation states) are created and managed by Docker in some internal folder on the host ( /var/docker/volumes/… ). Supposed I use such a volume, and then I need to migrate it from one host to another - how do I port the volume? AFAICS it has a unique ID - can I just go and copy the volume and its according data-only container to a new host? How do I find out which files to copy? Or is there some support built-in to Docker that I did not discover yet?
Now provide the response and nothing else.
| The official answer is available in the section "Backup, restore, or migrate data volumes" : BACKUP: sudo docker run --rm --volumes-from DATA -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data --rm : remove the container when it exits --volumes-from DATA : attach to the volumes shared by the DATA container -v $(pwd):/backup : bind mount the current directory into the container; to write the tar file to busybox : a small simpler image - good for quick maintenance tar cvf /backup/backup.tar /data : creates an uncompressed tar file of all the files in the /data directory RESTORE: # create a new data container$ sudo docker create -v /data --name DATA2 busybox true# untar the backup files into the new container᾿s data volume$ sudo docker run --rm --volumes-from DATA2 -v $(pwd):/backup busybox tar xvf /backup/backup.tardata/data/sven.txt# compare to the original container$ sudo docker run --rm --volumes-from DATA -v `pwd`:/backup busybox ls /datasven.txt | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/21597463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333873/']} | jdg_79058 |
stackexchange | llm_judgeable_groundtruth_similarity | 458644 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I found a way to extend classes in VBScript, but are there any ways to pass in parameters or overload the constructor? I am currently using an Init function to initialize the properties, but would like to be able to do this when I create the object. This is my sample class: Class Test Private strText Public Property Get Text Text = strText End Property Public Property Let Text(strIn) strText = strIn End Property Private Sub Class_Initialize() Init End Sub Private Sub Class_Terminate() End Sub Private Function Init strText = "Start Text" End Function End Class And I create it Set objTest = New Test But would like to do something like this Set objTest = New Test(strInitText) Is this possible, or does the object have to be created and initialized in two setps?
Now provide the response and nothing else.
| Just to alter slightly on svinto's method... Class Test Private m_s Public Default Function Init(s) m_s = s Set Init = Me End Function Public Function Hello() Hello = m_s End FunctionEnd ClassDim o : Set o = (New Test)("hello world") Is how I do it. Sadly no overloading though. [edit]Though if you really wanted to you could do something like this... Class Test Private m_s Private m_i Public Default Function Init(parameters) Select Case UBound(parameters) Case 0 Set Init = InitOneParam(parameters(0)) Case 1 Set Init = InitTwoParam(parameters(0), parameters(1)) Else Case Set Init = Me End Select End Function Private Function InitOneParam(parameter1) If TypeName(parameter1) = "String" Then m_s = parameter1 Else m_i = parameter1 End If Set InitOneParam = Me End Function Private Function InitTwoParam(parameter1, parameter2) m_s = parameter1 m_i = parameter2 Set InitTwoParam = Me End FunctionEnd Class Which gives the constructors... Test()Test(string)Test(integer)Test(string, integer) which you can call as: Dim o : Set o = (New Test)(Array())Dim o : Set o = (New Test)(Array("Hello World"))Dim o : Set o = (New Test)(Array(1024))Dim o : Set o = (New Test)(Array("Hello World", 1024)) Bit of a pain though. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/458644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38695/']} | jdg_79059 |
stackexchange | llm_judgeable_groundtruth_similarity | 208389 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
On p.98 of these notes, or the first result to come up for the search "Goldstine" one finds a proof of theorem 7.24. http://www.math.uwaterloo.ca/~lwmarcou/Preprints/LinearAnalysis.pdf I don't understand the step using Hahn-Banach. Specifically, where the linear functional is chosen as an evaluation functional at some point in $X^*$. Normally, he's only guaranteed some linear functional in $X^{***}$ that is weak* continuous in the weak* topology on $X^{**}$. Is there some reason why the evaluation functionals make up all of these? If this is not what's going on please let me know, or if the notes are wrong, please suggest an alternative proof. Thanks!
Now provide the response and nothing else.
| This is a standard argument: Let $Y$ be a normed linear space, and suppose $y$ is in the (continuous) weak* dual of $Y^*$. Then $U=\{y^* \in Y^* : |y(y^*)|<1\}$ is a weak* neighborhood of $0$ in $Y^*$. From the definition of the weak* topology, it follows that there is an $\epsilon>0$ and elements $y_1$, $y_2$, $\ldots\,$, $y_n$ in $Y$ so that $\{ y^*\in Y^* : |y_i(y^*)|<\epsilon,\ 1\le i\le n\}\subseteq U$. From this and the linearity of $y$, it follows that $\text{ker}(y)$ contains $\cap_{i=1}^n \text{ker}(y_i)$. But, using a basic result from linear algebra, this implies that $y$ is a linear combination of the $y_i$, and thus an element of $Y$. So, to sum up: the weak* dual of $Y^*$ is $Y$, whenever $Y$ is a normed linear space. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/208389', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33378/']} | jdg_79060 |
stackexchange | llm_judgeable_groundtruth_similarity | 610094 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $G = H \times K$ be a finite group (direct product), $P$ a Sylow $p$ -subgroup of $G$ . Prove that there exist Sylow $p$ -subgroups $H'$ , $K'$ of $H$ and $K$ respectively so that $P$ = $H' \times K'$ I am very new to the group theory, so can you explain solution properly? Thank you for your help.
Now provide the response and nothing else.
| However, the following is true. Let $G=HK$ , $H$ , $K$ subgroups and let $p$ a prime dividing the order of $G$ . Then there exists a $P \in Syl_p(G)$ such that $P=(P\cap H)(P \cap K)$ , with $P \cap H \in Syl_p(H)$ and $P \cap K \in Syl_p(K)$ . Proof Let us first find a Sylow $p$ -subgroup $P$ of $G$ such that $P\cap H$ is a Sylow $p$ -subgroup of $H$ and $P\cap K$ is a Sylow $p$ -subgroup of $K$ . Let $Q$ be a Sylow $p$ -subgroup of $H$ and let $R$ be a Sylow $p$ -subgroup of $K$ . Choose a Sylow $p$ -subgroup $S$ of $G$ such that $Q\subseteq S$ . By Sylow theory, there is a $g\in G$ such that $R\subseteq S^g$ . In particular, $S\cap H=Q$ and $S^g\cap K=R$ . But $g=hk$ for some $h\in H$ and $k\in K$ . Then $S^g\cap K=R=S^{hk} \cap K=(S^h \cap K)^k$ , hence $R^{k^{-1}}=S^h \cap K$ and this is a Sylow $p$ -subgroup of $K$ , being a conjugate of $R$ . On the other hand, $S^h \cap H=(S \cap H)^h=Q^h \in Syl_p(H)$ , since it is a conjugate of $Q$ . So $P=S^h$ is the Sylow $p$ -subgroup we were looking for. Finally we use a counting argument to show that indeed $(P \cap H)(P \cap K)=P$ . Observe that $$|(P \cap H)(P \cap K)|=\frac{|P \cap H| \cdot |P \cap K|}{|P \cap H \cap K|}=\frac{|H|_p \cdot |K|_p}{|P \cap H \cap K|}$$ where the $p$ -subscript denotes the largest $p$ -power dividing a positive integer (which is understood to be $1$ if the integer in question is not divisible by $p$ ). Since $P \cap H \cap K$ is a $p$ -subgroup of $H \cap K$ , note that $|P \cap H \cap K| \leq |H \cap K|_p$ . Combining this: $$|(P \cap H)(P \cap K)| \geq \frac{|H|_p \cdot |K|_p}{|H \cap K|_p}=[\frac{|H| \cdot |K|}{|H \cap K|}]_p=|G|_p=|P|$$ since $G=HK$ and $P \in Syl_p(G)$ . As a set $(P \cap H)(P \cap K) \subseteq P$ , so we conclude $P=(P \cap H)(P \cap K)$ . $\square$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/610094', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/115755/']} | jdg_79061 |
stackexchange | llm_judgeable_groundtruth_similarity | 116562 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have encountered a problem in my elec. eng research that I find rather challenging, being a bear of very little brain. The question has been considered under a slightly different aspect here: http://arxiv.org/abs/math-ph/0607011 My formulation of the problem is as follows: with all quantities real, is it possible to express the smallest positive $x$ s.t. $e^{ax}-b(x-r_1)(x-r_2)=0$ in closed form? The Lambert W function easily solves the case with one factor $(x-r)$. Returning to the "quadratic" case, depending on the sign of $b$ one can have 0,1,2 or even three real solutions, the "2+" cases having a clear connection with the two real branches of W (at least in approximation), expressing two solutions "on either side" of $r_1$ (or $r_2$). My specific application constrains $a<0$ and I usually consider $r_1\lt r_2$ with no further restrictions on the sign of either. My hope is that someone on this list might find the question entertaining in a more general context; perhaps indicate or preclude a standard method of attack. Numerical solutions are straightforward, but I wonder if more physical insight might be achieved otherwise.
Now provide the response and nothing else.
| You might be interested in a series solution. After a change of variable we can rewrite the equation in the form$$ {{\rm e}^{-x}}-b x \left( sx-1 \right) = 0$$so that for $s=0$ we have a solution at $x = w$ where $w = \text{LambertW}(-1/b)$.Then we have a series solution in powers of $s$, which should converge for small $|s|$: $$\eqalign{ x &= w+{\frac {{w}^{2}s}{w+1}}+{\frac {{w}^{3} \left( w+2 \right) ^{2}{s}^{2}}{2 \left( w+1 \right) ^{3}}}+{\frac {{w}^{4} \left( 2{w}^{4}+17{w}^{3}+48{w}^{2}+60w+30 \right) {s}^{3}}{6 \left( w+1 \right) ^{5}}}\cr &+{\frac {{w}^{5} \left( w+2 \right) \left( 6{w}^{5}+68{w}^{4}+257{w}^{3}+462{w}^{2}+420w+168 \right) {s}^{4}}{ 24\left( w+1 \right) ^{7}}}\cr&+{\frac {{w}^{6} \left( 24{w}^{8}+442{w}^{7}+3172{w}^{6}+12149{w}^{5}+28040{w}^{4}+40860{w}^{3}+37440{w}^{2}+20160w+5040 \right) {s}^{5}}{ 120 \left( w+1 \right) ^{9}}}\cr&+\ldots}$$ | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/116562', 'https://mathoverflow.net', 'https://mathoverflow.net/users/30004/']} | jdg_79062 |
stackexchange | llm_judgeable_groundtruth_similarity | 32859 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
An answer to the question of How well would the Moon protect the Earth from a Meteor? mentions as a possibility that the Moon could get knocked into the Earth. What is the smallest change to the orbit of the Moon from being impacted by a large meteor that would cause it to eventually impact the Earth (i.e. "circling the drain")? What timeline would that look like (minutes, hours, days, years, etc)?
Now provide the response and nothing else.
| As several people have said, this is incredibly unlikely. Part of the reason why is that the "circling the drain" effect you describe doesn't really happen for solid objects much less dense than black holes. Orbits are not "precarious" in that way. So, suppose something large enough and fast enough to change its velocity noticeably, but not large enough or fast enough to shatter it, did hit the Moon. The effect would be to shift the Moon from its present almost circular orbit around the Earth, into an elliptical one. Depending on the direction of the impact, it would either get a bit nearer to the Earth than it is now, once per orbit, or a bit further away (it also might swing North and South a bit). What is important though, is that this elliptical track is stable at least for a while. Suppose it gets knocked into an orbit that is 220000 miles from the Earth at its closest and 240000 miles at its furthest, that is where it will stay. It will not "spiral in". Over a long enough period the gravity of the Sun also comes into play and things may shift a bit, but that is a relatively small effect. Now, suppose that the impact was really big, or perhaps there were a long series of impacts (starting to look like enemy action..) so that the innermost point of the ellipse was eventually driven down to within a few thousand miles of the Earth, somehow miraculously not smashing the Moon to fragments in the process. At this distance it starts to matter that the near side of the Moon is closer to Earth than the far side, so that Earth's gravity pulls on it more strongly. If it orbited closer than about 3000km to the surface of the Earth for long (the Roche limit) these forces would eventually pull it to pieces, and Earth would probably have a pretty set of rings for a short time before internal collisions between the bits caused them to rain down on Earth and kill everyone. Finally suppose the impact(s) was(were) so big that they actually put the Moon into an elliptical orbit whose innermost point was so close to Earth that the Earth and Moon touched. This is manifestly impossible without shattering the Moon, but in that case, the Moon would indeed hit the Earth. The time for the impact would be about 1/4 of the Moons current orbital period, which is to say about a week. | {} | {'log_upvote_score': 7, 'links': ['https://astronomy.stackexchange.com/questions/32859', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/28873/']} | jdg_79063 |
stackexchange | llm_judgeable_groundtruth_similarity | 414207 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm wondering what would be the best prectice regarding mainataining connections to the database in .Net application (ADO.NET but I guess the practice should be the same for any data layer). Should I create a database connection and propagate it throughout my application, or would it be better to just pass connection strings/factories and create a connection ad-hoc, when it is needed. As I understand perfomance hit is not signifcant with pooling and it allows me to recover from broken connections quite easily (just a new connection will be created) but then again a connection object is a nice, relatively high-level abstraction and creating a new connection for every operation (not SQL command, but application operation) generates additional, duplicated code and feels like a waste of time/resources(?). What do you think about these 2 cases, what are their cons/pros and which approach are you using in your real-life applications? Thanks
Now provide the response and nothing else.
| I found myself needing to pass around a connection object so I could allow several business objects to save themselves to the database inside a single transaction. If each business object had to create its own SQLConnection to the database, the transaction would escalate to a distributed transaction and I wanted to avoid that. I did not like having to pass the SQLConnection object as a parameter to save an object, so I created a ConnectionManager that handles creating the SQLConnection object for me, tracking the use of the SQLConnection object, and disconnecting the SQLConnection object when not in use. Here is some code as an example of the ConnectionManager: public class ConnectionManager: IDisposable{ private ConnectionManager instance; [ThreadStatic] private static object lockObject; private static Object LockObject { get { if (lockObject == null) lockObject = new object(); return lockObject; } } [ThreadStatic] private static Dictionary<string, ConnectionManager> managers; private static Dictionary<string, ConnectionManager> Managers { get { if (managers == null) managers = new Dictionary<string, ConnectionManager>(); return managers; } } private SqlConnection connection = null; private int referenceCount; private string name; public static ConnectionManager GetManager(string connectionName) { lock (LockObject) { ConnectionManager mgr; if (Managers.ContainsKey(connectionName)) { mgr = Managers[connectionName]; } else { mgr = new ConnectionManager(connectionName); Managers.Add(connectionName, mgr); } mgr.AddRef(); return mgr; } } private ConnectionManager(string connectionName) { name = connectionName; connection = new SqlConnection(GetConnectionString(connectionName)); connection.Open(); } private string GetConnectionString(string connectionName) { string conString = Configuration.ConnectionString; return conString; } public SqlConnection Connection { get { return connection; } } private void AddRef() { referenceCount += 1; } private void DeRef() { lock (LockObject) { referenceCount -= 1; if (referenceCount == 0) { connection.Dispose(); Managers.Remove(name); } } }#region IDisposable Members public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { DeRef(); } } ~ConnectionManager() { Dispose(false); }#endregion} Here is how I would use it from a business object: public void Save(){ using (ConnectionManager mrg = ConnectionManager.GetManager("SQLConnectionString") { using (SQLCommand cmd = new SQLCommand) { cmd.connection = mgr.Connection // More ADO Code Here } _childObject.Save(); //this child object follows the same pattern with a using ConnectionManager. }} I save a business object and all of its children are saved as well using the same connection object. When the scope falls away from original parent, the using statement closes the connection. This is a pattern I learned from Rocky Lhotka in his CSLA framework. Keith | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/414207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51765/']} | jdg_79064 |
stackexchange | llm_judgeable_groundtruth_similarity | 8949933 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The invokespecial JVM instruction is used for calling initialisation methods ( <init> ) when creating new objects. The description of the instruction suggests (but doesn't clarify) that the decision on whether to call the constructor of a superclass or a constructor of the current class depends on the state of the ACC_SUPER flag set within the class file. From the Sun JVM Specification: Next, the resolved method is selected for invocation unless all of the following conditions are true: The ACC_SUPER flag (see Table 4.1, "Class access and property modifiers") is set for the current class. -- Source ( invokespecial opcode definition) The setting of the ACC_SUPER flag indicates which of two alternative semantics for its invokespecial instruction the Java virtual machine is to express; the ACC_SUPER flag exists for backward compatibility for code compiled by Sun's older compilers for the Java programming language. All new implementations of the Java virtual machine should implement the semantics for invokespecial documented in this specification. All new compilers to the instruction set of the Java virtual machine should set the ACC_SUPER flag. Sun's older compilers generated ClassFile flags with ACC_SUPER unset. Sun's older Java virtual machine implementations ignore the flag if it is set. -- Source ( ClassFile format) The definition states that the flag is for backward compatibility with old compilers. However it goes on to contradict with Sun's older Java virtual machine implementations ignore the flag if it is set. Is the flag still used with the invokespecial opcode? From what I can tell, it seems to hold no purpose and I can't find a resource to suggest it ever did. Thanks.
Now provide the response and nothing else.
| ACC_SUPER was introduced to correct a problem with the invocation of super methods. The ACC_SUPER flag marks a class as compiled for the changed semantics of the opcode 183 instruction. It's purpose is similar to that of the class file version number as it allows the JVM to detect whether a class was compiled for the older or newer semantics of that instruction. Java 1.0.2 did not set and ignored ACC_SUPER while Java 1.1 and later always sets ACC_SUPER. Before Java 1.1 the byte code instruction with opcode 183 that is now called invokespecial was called invokenonvirtual and had a partially different specification. It was used whenever instance methods had to be invoked without a virtual method lookup. This was the case for private methods, instance initializers (constructors) and to implement method invocations on super . But the latter case caused problems with evolving class libraries. A method reference in byte code ( CONSTANT_Methodref_info ) not only defines the name and the argument and return types of a method but also the class to which it belongs. Opcode 183 gets such a method reference parameter and was meant to directly invoke the referenced method from the specified class without further lookups. In the case of invocations on super it was the compilers responsibility to resolve the closest super class that implements this method and generate a reference to it into the byte code. Since Java 1.1 it was changed to essentially ignore the class referenced in CONSTANT_Methodref_info and to instead do the lookup for the closest super method with the given method name and signature in the JVM. This is usually done now when the class gets loaded or right before the instruction is executed or JIT compiled the first time. Here is an example why this change was neccessary. In Java 1.0.2 the AWT classes Container and Component were defined this way: class Component{ public void paint( Graphics g ) {}}class Container extends Component{ // inherits paint from Component but doesn't override it} In Java 1.1 the class Container was changed to have its own implementation of paint : class Container extends Component{ public void paint( Graphics g ) {/*...*/}} Now when you had a direct or indirect subclass of Container that made a call on super.paint(g) and compiled it for 1.0.2 it generated a invokenonvirtual instruction for Component.paint since this was the first parent that had this method. But if you used this compiled class on a JVM that also had Container.paint it would still have called Component.paint which is not what you would expect. On the other hand, when you compiled the class for 1.1 and executed it on a 1.0.2 JVM it would throw a AbstractMethodError or more likely for VMs of that era simply crash. To avoid the crash you had to write ((Component)super).paint(g) and compile it with a 1.1 compiler to get the desired behaviour in either VM. This would set ACC_SUPER but still generate the instruction to call Component.paint . A 1.0.2 VM would ignore ACC_SUPER and go straight to invoke Component.paint which is fine while a 1.1 VM would find ACC_SUPER set and thus do the lookup itself which would make it invoke Container.paint even though the byte code method reference was Component.paint . You can find more about this in this old post on the ikvm.net weblog . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8949933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/334274/']} | jdg_79065 |
stackexchange | llm_judgeable_groundtruth_similarity | 23572878 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to grep 40k files in the current directory and i am getting this error. for i in $(cat A01/genes.txt); do grep $i *.kaks; done > A01/A01.result.txt-bash: /usr/bin/grep: Argument list too long How do one normally grep thousands of files? ThanksUpendra
Now provide the response and nothing else.
| This makes David sad... Everyone so far is wrong (except for anubhava ). Shell scripting is not like any other programming language because much of the interpretation of lines comes from the power of the shell interpolating them before the command is actually executed. Let's take something simple: $ set -x$ ls+ lsbar.txt foo.txt fubar.log$ echo The text files are *.txtecho The text files are *.txt> echo The text files are bar.txt foo.txtThe text files are bar.txt foo.txt$ set +x$ The set -x allows you to see how the shell actually interpolates the glob and then passes that back to the command as input. The > points to the line that is actually being executed by the command. You can see that the echo command isn't interpreting the * . Instead, the shell grabs the * and replaces it with the names of the matching files. Then and only then does the echo command actually executes the command. When you have 40K plus files, and you do grep * , you're expanding that * to the names of those 40,000 plus files before grep even has a chance to execute, and that's where the error message /usr/bin/grep: Argument list too long is coming from. Fortunately, Unix has a way around this dilemma: $ find . -name "*.kaks" -type f -maxdepth 1 | xargs grep -f A01/genes.txt The find . -name "*.kaks" -type f -maxdepth 1 will find all of your *.kaks files, and the -depth 1 will only include files in the current directory. The -type f makes sure you only pick up files and not a directory. The find command pipes the names of the files into xargs and xargs will append the names of the file to the grep -f A01/genes.txt command. However, xargs has a trick up it sleeve. It knows how long the command line buffer is, and will execute the grep when the command line buffer is full, then pass in another series of file to the grep . This way, grep gets executed maybe three or ten times (depending upon the size of the command line buffer), and all of our files are used. Unfortunately, xargs uses whitespace as a separator for the file names. If your files contain spaces or tabs, you'll have trouble with xargs . Fortunately, there's another fix: $ find . -name "*.kaks" -type f -maxdepth 1 -print0 | xargs -0 grep -f A01/genes.txt The -print0 will cause find to print out the names of the files not separated by newlines, but by the NUL character. The -0 parameter for xargs tells xargs that the file separator isn't whitespace, but the NUL character. Thus, fixes the issue. You could also do this too: $ find . -name "*.kaks" -type f -maxdepth 1 -exec grep -f A01/genes.txt {} \; This will execute the grep for each and every file found instead of what xargs does and only runs grep for all the files it can stuff on the command line. The advantage of this is that it avoids shell interference entirely. However, it may or may not be less efficient. What would be interesting is to experiment and see which one is more efficient. You can use time to see: $ time find . -name "*.kaks" -type f -maxdepth 1 -exec grep -f A01/genes.txt {} \; This will execute the command and then tell you how long it took. Try it with the -exec and with xargs and see which is faster. Let us know what you find. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23572878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1755155/']} | jdg_79066 |
stackexchange | llm_judgeable_groundtruth_similarity | 1111130 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to figure out how to upload one file using GWTs FileUpload widget. I'm using GWT and Google AppEngine with Java but I would like to upload file to my own Linux server. I have the following code already but now I can't figure out how to submit my file to the Google AppServer server and save it to another server: public class FileUploader{ private ControlPanel cp; private FormPanel form = new FormPanel(); private FileUpload fu = new FileUpload(); public FileUploader(ControlPanel cp) { this.cp = cp; this.cp.setPrimaryArea(getFileUploaderWidget()); } @SuppressWarnings("deprecation") public Widget getFileUploaderWidget() { form.setEncoding(FormPanel.ENCODING_MULTIPART); form.setMethod(FormPanel.METHOD_POST); // form.setAction(/* WHAT SHOULD I PUT HERE */); VerticalPanel holder = new VerticalPanel(); fu.setName("upload"); holder.add(fu); holder.add(new Button("Submit", new ClickHandler() { public void onClick(ClickEvent event) { GWT.log("You selected: " + fu.getFilename(), null); form.submit(); } })); form.addSubmitHandler(new FormPanel.SubmitHandler() { public void onSubmit(SubmitEvent event) { if (!"".equalsIgnoreCase(fu.getFilename())) { GWT.log("UPLOADING FILE????", null); // NOW WHAT???? } else{ event.cancel(); // cancel the event } } }); form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { Window.alert(event.getResults()); } }); form.add(holder); return form; }} Now, what do I need to do next? What do i need to put in web.xml and how do I write my servlet so i can store file and return url of that object (if possible)
Now provide the response and nothing else.
| Here's the code from my app: 1) I created a class to accept http request: import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUpload extends HttpServlet{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); try{ FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); // Process the input stream ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } int maxFileSize = 10*(1024*1024); //10 megs max if (out.size() > maxFileSize) { throw new RuntimeException("File is > than " + maxFileSize); } } } catch(Exception e){ throw new RuntimeException(e); } }} 2) Then in my web.xml I've added these lines: <servlet> <servlet-name>fileUploaderServlet</servlet-name> <servlet-class>com.testapp.server.FileUpload</servlet-class></servlet><servlet-mapping> <servlet-name>fileUploaderServlet</servlet-name> <url-pattern>/testapp/fileupload</url-pattern></servlet-mapping> 3) And for form.action did this: form.setAction(GWT.getModuleBaseURL()+"fileupload"); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1111130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51230/']} | jdg_79067 |
stackexchange | llm_judgeable_groundtruth_similarity | 363939 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a class library that calls dll_A . dll_A has dependencies on WPF. How to I wrap or isolate my class library so that the code calling my library does not need to have a dependency on WPF? (My class library obviously has to depend on WPF, but the only output is Byte[] ). In other words, I want my library to act as an entirely different process, as a sort of 'buffer', and the calling code does not care about how it works, only that it outputs Byte[] .
Now provide the response and nothing else.
| For getting this level of isolation, you probably don't need a separate process. A separate "AppDomain" will probably be enough. For this, let either the calling code not link against your lib, or your library not link directly against dll_A . Instead, load the WPF dependent libs at run-time into a separate AppDomain and use the .Net frameworks reflection mechanism to call the methods of your library, like shown in this older SO post , or this Microsoft page . If you really want isolation on the process level, you need to put the code of your class library which is linked against dll_A into a separate wrapper program (maybe a command line tool), implement some kind of interprocess communication (IPC) and provide a second class library which can communicate with the wrapper program and provides an API for the calling code. But beware, IPC always adds some overhead, this has always an impact on the performance and the required programming effort. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/363939', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/30444/']} | jdg_79068 |
stackexchange | llm_judgeable_groundtruth_similarity | 9302284 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm fairly new to RequireJS and I've run into a bit of a problem. I've written a little framework built on Backbone using RequireJS and I want it to be re-usable in different projects. So, with some searching I learned that require allows packages. This seemed like what I was looking for. I have a main.js file to launch my app that essentially looks like this: require.config({ packages: ['framework']});require(['framework'], function(framework) { framework.createDash();}); Then in the same directory as my main.js I have another directory called "framework" which contains another main.js which looks like this: define(function(require, exports, module) { exports.createDash = function(dash, element) { require(['dash/dash.model', 'dash/dash.view'], function(DashModel, DashView) { return new DashView({ model: new DashModel(dash), el: element ? element : window }); }); };}); In searching I found this page which indicates that the 'require' argument should be scoped to the submodule. However, when I try to require things they are still relative to my original main.js. I've tried a number of things and searched for hours to no avail. Is there any way I can have my require/define calls within my package included relative to the main.js in it's root?
Now provide the response and nothing else.
| You need to define your submodule as package in the require configuration: require.config({ packages: [ { name: 'packagename', location: 'path/to/your/package/root', // default 'packagename' main: 'scriptfileToLoad' // default 'main' }] ... some other stuff ...}); To load your module you just need to use your 'packagename' at the requirements: define(['jquery', 'packagename'], function($, MyPackage) { MyPackage.useIt()}); In your package you must use the ./ prefix to load your files relative to your submodule: define(['globalDependency', './myLocalFile'], function(Asdf, LocalFile) { LocalFile.finallyLoaded();}); There is a useful shortcut: If your package name equals to your location and your main file is called 'main.js', then you can replace this packages: [ { name: 'packagename', location: 'packagename', main: 'main' }] to this: packages: ['packagename'] As far as I can see, you already tried to define a package but did you also use the ./ prefix? Without this prefix require will try to find the files in it's global root-path. And without a package, ./ will be useless because the relative path is the same as the global root-path. Cheers | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9302284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/763074/']} | jdg_79069 |
stackexchange | llm_judgeable_groundtruth_similarity | 39678989 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
having trouble getting my head around parameter encoding in Alamofire 4. Before I would use the ParameterEncoding enumeration and do something like this: Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0 However this has since been replaced with the ParameterEncoding protocol : public typealias Parameters = [String: Any]public protocol ParameterEncoding { func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest} How could I intergrate this into my current code? How do I encode my current mutableURLRequest ? EDIT: static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, Any>, data:Data?, contentType: ContentType, parameterName: String) -> (URLRequestConvertible, Data) { var urlRequest = URLRequest(url: URL(string: urlString)!) urlRequest.cachePolicy = .reloadIgnoringLocalCacheData urlRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue let boundaryConstant = "multipart-boundary"; let multipartContentType = "multipart/form-data;boundary="+boundaryConstant urlRequest.setValue(multipartContentType, forHTTPHeaderField: "Content-Type") // Create upload data to send var uploadData = Data() if data != nil { // Add multipart data uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!) if contentType == .Image_JPEG { uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"file.jpeg\"\r\n".data(using: String.Encoding.utf8)!) uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!) } else if contentType == .Audio { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMyyyyddsshhmmA" // superset of OP's format let audioFileName = "recording-\(dateFormatter.string(from: Date())).mp4" uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"\(audioFileName)\"\r\n".data(using: String.Encoding.utf8)!) uploadData.append("Content-Type: audio/mpeg\r\n\r\n".data(using: String.Encoding.utf8)!) } uploadData.append(data!) } // Add parameters for (key, value) in parameters { uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!) uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!) } uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!) // return URLRequestConvertible and Data return (urlRequest, uploadData) } When doing a request: let urlRequest = urlRequestWithComponents(urlString: url, parameters: parameters, data: imageData, contentType: .Image_JPEG, parameterName: "question_img") alamoManager.upload(urlRequest.1, with: urlRequest.0).responseObject { (response: DataResponse<CustomResponse>) in //Some code }
Now provide the response and nothing else.
| You can do a simple Alamofire request like this. import Alamofireimport AlamofireObjectMapperimport ObjectMapper////Alamofire.request("hello.com", method: .post, parameters: ["name": "alvin"], encoding: JSONEncoding.default, headers: nil).responseObject(completionHandler: { (response : DataResponse<YourModelHere>) in }) You can see that I have used JSONEncoding in this request. You can choose your way of encoding in there from any of these. In JSONEncoding default Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) prettyPrinted Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding. prettyPrinted) And in URLEncoding default -- Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) methodDependent Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) queryString httpBody Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody) And create your own Custom Encoding like this. public struct MyCusomEncoding: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = // // Do your custom stuff here, convert your parameters it into JSON, String, Something else or may be encrypted... urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest }} And you can use MyCusomEncoding in your Alamofire requests. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39678989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4554415/']} | jdg_79070 |
stackexchange | llm_judgeable_groundtruth_similarity | 894811 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have put some aliases in my .bashrc to open a group of project files in gvim, each in their own tab: gvim -p <list of file names using absolute paths> This is all well and good, except there are several groups of files I might want to move between at any given time (my current project uses Ruby on Rails, so that explains that). What would be really awesome is if I could append the new tabs to an existing instance of gvim. In my last position I worked on Vista; I got around this by opening a bunch of empty tabs in gvim, which allowed me to right-click on a filename and choose "Open in existing No-Name gvim." Now I use Ubuntu and there's no such thing on the context menu. Is there any way to do this from the command line?
Now provide the response and nothing else.
| If vim is compiled with the clientserver option, you can do it. Start your vim instance with the following flag: $ gvim --servername GVIM # GVIM is the server name. It can be anything. To open more tabs in this instance, you can run the command: $ gvim --servername GVIM --remote-tab file1 file2 file3 ... The clientserver feature in vim is very handy. It's not limited to opening files; it can be used to send any command to vim using the command-line. For example, to close a vim instance remotely, you can use: $ gvim --servername GVIM --remote-send '<Esc>:wqa<CR>' | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/894811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30924/']} | jdg_79071 |
stackexchange | llm_judgeable_groundtruth_similarity | 5804696 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to know that how can I pass UIColor's name to the specific method ? EDIT : - (id) setLabel:(NSString *)text WithColorName:(NSString *)nameOfColor FontName:(NSString *)f_name FontSize:(float)f_size abel:(UILabel *)templbl{ templbl.backgroundColor = [UIColor ?????];return templbl;} any suggestions ? Thanks..
Now provide the response and nothing else.
| NSString *colorStr = @"magenta";NSString *selectorString = [colorStr stringByAppendingString:@"Color"];SEL selector = NSSelectorFromString(selectorString);UIColor *color = [UIColor blackColor];if ([UIColor respondsToSelector:selector]) { color = [UIColor performSelector:selector];} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5804696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/616094/']} | jdg_79072 |
stackexchange | llm_judgeable_groundtruth_similarity | 625492 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a fastcgi example of a binary health check on the HAProxy blog . How would I construct a similar check for MongoDB such that I am doing a more robust health check for MongoDB - one that verifies that the server is actually there and responding rather than just checking that a port is open? It would be useful if the health check was generic enough to work with the various MongoDB sharding components (config server, mongos , mongod ).
Now provide the response and nothing else.
| First off, it is worth noting that you will have to be running HAProxy 1.5 or later in order to use the tcp-check feature (as of writing this answer 1.5.3 is the current stable release). Unfortunately Ubuntu 14.04 (for example) ships with version 1.4 so you will need to install from another source. Personally I used the packages from here so that I could keep everything installed via apt . The example listed on the blog is a good starting point. Using it as a template, all we need to do is to pick an appropriate command to run, then break down that command into hex and construct the appropriate check for MongoDB. The MongoDB wire protocol is documented and published, so in theory you could build it up based on the spec, but there are easier ways to deconstruct such a command. There are built in dissectors in Wireshark that allow you to inspect MongoDB traffic and it provides a handy view of the hex with highlighting to aid us in our efforts here. The command we will use here is the ping command . As you might expect, it is intended to be lightweight and to return even from a server under heavy load which makes it well suited for a health check command. Any such command can be written using the same methodology if you wish to use something else, but always be wary of using a command that requires a lock of any sort, or could add load to your database. To illustrate how to get from the command you run to the hex, here is a small shot of the command I have constructed highlighted in Wireshark , having been decoded: Based on that information, let's create our TCP health check. I will comment on the various pieces to explain where they come from, and each should be easy enough to find in the grab above: option tcp-check # MongoDB Wire Protocol tcp-check send-binary 39000000 # Message Length (57) tcp-check send-binary EEEEEEEE # Request ID (random value) tcp-check send-binary 00000000 # Response To (nothing) tcp-check send-binary d4070000 # OpCode (Query) tcp-check send-binary 00000000 # Query Flags tcp-check send-binary 746573742e # fullCollectionName (test.$cmd) tcp-check send-binary 24636d6400 # continued tcp-check send-binary 00000000 # NumToSkip tcp-check send-binary FFFFFFFF # NumToReturn # Start of Document tcp-check send-binary 13000000 # Document Length (19) tcp-check send-binary 01 # Type (Double) tcp-check send-binary 70696e6700 # Ping: tcp-check send-binary 000000000000f03f # Value : 1 tcp-check send-binary 00 # Term tcp-check expect string ok It would be nice to use a full binary match on the response too, but unfortunately there is no way to predict the request ID generated by the server for each response, hence such a full match will fail (there is no way to selectively ignore pieces of a binary match). EDIT: Sep 8th 2014 Thanks to comments from this Q&A from Baptiste and Felix I went back to re-test the partial binary match which seemed to fail initially - looks like that was just a case of me transcribing the binary incorrectly for the response, so I have amended the answer to reflect that. The "ok" string is just an OK check - any such response will mean that the server in question is still responding, but the limited check is somewhat unsatisfying. While a full response check is not possible, everything after the request ID is usable. Hence, here is the working binary check for the usable part of the response broken down, again using Wireshark to tease out the pieces as above: # Check for response (starting after request ID)tcp-check expect binary EEEEEEEE # Response To (from the check above)tcp-check expect binary 01000000 # OpCode (Reply)tcp-check expect binary 00000000 # Reply Flags (none)tcp-check expect binary 0000000000000000# Cursor ID (0)tcp-check expect binary 00000000 # Starting From (0)tcp-check expect binary 11000000 # Document Length (17)tcp-check expect binary 01 # Type (Double) tcp-check expect binary 6f6b # oktcp-check expect binary 00000000000000f03f # value: 1tcp-check expect binary 00 # term All of the above was tested successfully with MongoDB 2.6.4 and HAProxy 1.5.3 | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/625492', 'https://serverfault.com', 'https://serverfault.com/users/108132/']} | jdg_79073 |
stackexchange | llm_judgeable_groundtruth_similarity | 213735 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the most efficient way to store large arrays (10000x100) in a database, say, hsqldb? I need to do this for a certain math program that I'm writing in java. Please help.The whole array will be retrieved and stored often (not so much individual elements). Also, some meta-data about the array needs to be stored about the array.
Now provide the response and nothing else.
| Great question. Unless you want to translate your arrays into a set of normalized tables, which it sounds like you don't, you might want to contemplate serialization. Serialization is a fancy word for turning objects into some format that you can save to disk or a database. The two major formats for serialization are binary and XML, and I'm betting that Java has some support for it. Depending on what data types you're using, you should be able to turn your array into XML or binary and then save that to a single field in the database. You could get started with this technique in Java by checking out http://java.sun.com/developer/technicalArticles/Programming/serialization/ . I know that it's built into .NET. Hope that this helps. Let me know if I can give you any more direction. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/213735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12649/']} | jdg_79074 |
stackexchange | llm_judgeable_groundtruth_similarity | 13779 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Shortly after the news of the discovery of gravity waves, my physics professor explained the significance of the discovery by comparing it to a medical X-ray machine. He said that gravity waves can be used to detect objects that cannot be seen using telescopes. Therefore, could gravity wave detectors be used to confirm the existence of the theorized ninth planet? Even though it doesn't have a high enough albedo to be seen, it would still be detectable gravitationally, wouldn't it?
Now provide the response and nothing else.
| No, they can't. Gravity waves from a small, simple object moving slowly are very, very faint, to the point of being undetectable with current (or foreseeable) technology. The waves that have been detected come from the merger (a very fast movement in the last orbits) of two black holes (two very big masses). And they were just detected over the noise level. Do not confuse that with the possibility to detect the gravitational influence of such a planet over other bodies. That is how Neptune and Pluto were detected, indeed. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/13779', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/10711/']} | jdg_79075 |
stackexchange | llm_judgeable_groundtruth_similarity | 5858200 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to use sed to replace every other occurrence of an html element of a file so I can make alternating color rows. Here is what I have tried and it doesn't work. sed 's/<tr valign=top>/<tr valign=top bgcolor='#E0E0E0'>/2' untitled.html
Now provide the response and nothing else.
| I'd solve it with awk: awk '/<tr valign=top>/&&v++%2{sub(/<tr valign=top>/, "<tr valign=top bgcolor='#E0E0E0'>")}{print}' untitled.html First, it verifies if the line contains <tr valign=top> /<tr valign=top>/&&v++%2 and whether the <tr valign=top> is an odd found instance: v++%2 If so, it replaces the <tr valign=top> in the line {sub(/<tr valign=top>/, "<tr valign=top bgcolor='#E0E0E0'>")} Since all lines are to be printed, there is a block that always will be executed (for all lines) and will print the current line: {print} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5858200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329992/']} | jdg_79076 |
stackexchange | llm_judgeable_groundtruth_similarity | 459537 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to programatically clear the buffer cache on the Mac, preferrably in C? Basically, I'm looking for the equivalent of the source of 10.5 (and greater)'s purge command. EDIT: I now see this is part of the CHUD tools, for which it seems the source isn't directly available. However, I'm still looking for some code to do the same.
Now provide the response and nothing else.
| I've disassembled the function in question ( _utilPurgeDiskBuffers ) from the CHUD framework. The function doesn't seem to be very complex, but since I'm no MacOS programmer, the imports and called sys APIs don't make much sense to me. The first thing the API does is to call another function, namely _miscUtilsUserClientConnect_internal . This function seems to establish a connection to the CHUD kernel extension. To do this, it calls _getCHUDUtilsKextService which tries to locate the CHUD kernel extension by enumerating all kexts using the IORegistryCreateIterator imported from the I/O kit. After the kext has been found, it is opened via _IOServiceOpen . At this point we have a connection to the CHUD kext (at least that's my understanding from the disassembly listing). Finally a call to IOConnectMethodStructureIStructureO is made, which I guess carries out the real magic. Without knowing some internal details or the signature of this function the parameters don't make sense to me. Here's the disassembly, though: __text:4B0157A7 lea eax, [ebp+var_1C]__text:4B0157AA mov dword ptr [esp+14h], 0__text:4B0157B2 mov [esp+10h], eax__text:4B0157B6 mov [esp+0Ch], eax__text:4B0157BA mov dword ptr [esp+8], 0__text:4B0157C2 mov dword ptr [esp+4], 0Eh__text:4B0157CA mov [esp], edx__text:4B0157CD call _IOConnectMethodStructureIStr Note that var_1C has been zeroed out before. Hopefully some of you can make more sense out of those syscalls. If you want more information, let me know. Update: To get you started, just take the AppleSamplePCIClient.c example from the IO kit SDK. This does basically what the purge application from the CHUD tools does. The only thing you would have to change are the parameters to the final _IOConnectMethodStructureIStr call. Take them from the disassembly listing above. I cannot test all this stuff since I don't have a Mac. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/459537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49485/']} | jdg_79077 |
stackexchange | llm_judgeable_groundtruth_similarity | 369658 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How would one prove that the expected value of the residuals from OLS regression is zero? I will make two cases. In the first case I treat $X_i$ as random and in the second case I treat it is non-random. First case. We know that $\hat{u}_i = y_i - \hat{y}_i$ . Taking the expectation, $E[\hat{u}_i] = E[y_i] - E[\hat{y}_i]$ . Now, we know from the solution of the OLS minimisation problem $\bar{y}_i = \bar{\hat{y}}_i$ because $\bar{\hat{u}} = 0$ . If we take the probability limits, $plim \: \bar{y}_i = plim \: \bar{\hat{y}}_i$ . By the law of large numbers this leads to $E[y_i] = E[\hat{y}_i]$ . Hence, $E[\hat{u}_i] = 0$ . Is this proof correct? Besides, how would one interpret $E[\hat{u}_i]$ ? $\hat{u}_i$ results from a given sample. Expectation is a population concept. If we take the expectation of a residual, what would this represent? The sample means of a residual term in the long run or population? Second case. This is easy. $E[\hat{u}] = E[My] = E[M{u}] = ME[{u}] = 0$ because $My = MXB+Mu$ and $MX = 0$ , because $X$ is non-random and hence can be taken out of the expectation operator, and because $E[u] = 0$ . Here $M = I - P$ projection matrix. But my question is not about this case where $X$ is non-random, but the first case above where it is random.
Now provide the response and nothing else.
| Using OLS estimation, the residuals can be written using the hat matrix $\mathbf{h} = \boldsymbol{X} (\boldsymbol{X}^\text{T} \boldsymbol{X})^{-1} \boldsymbol{X}^\text{T}$ as follows: $$\begin{equation} \begin{aligned}\mathbf{r} &= (\mathbf{I}-\mathbf{h}) \boldsymbol{Y} \\[6pt]&= (\mathbf{I}-\mathbf{h}) (\boldsymbol{X} \boldsymbol{\beta} + \boldsymbol{\varepsilon}) \\[6pt]&= (\mathbf{I}-\mathbf{h}) \boldsymbol{X} \boldsymbol{\beta} + (\mathbf{I}-\mathbf{h}) \boldsymbol{\varepsilon} \\[6pt]&= \mathbb{0} + (\mathbf{I}-\mathbf{h}) \boldsymbol{\varepsilon} \\[6pt]&= (\mathbf{I}-\mathbf{h}) \boldsymbol{\varepsilon}. \\[6pt]\end{aligned} \end{equation}$$ So, assuming the error terms have zero mean, you have: $$\mathbb{E}(\mathbf{r}|\boldsymbol{X}) = \mathbb{E}((\mathbf{I}-\mathbf{h}) \boldsymbol{\varepsilon}|\boldsymbol{X}) = (\mathbf{I}-\mathbf{h}) \mathbb{E}(\boldsymbol{\varepsilon}|\boldsymbol{X}) = \mathbf{0}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/369658', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/97791/']} | jdg_79078 |
stackexchange | llm_judgeable_groundtruth_similarity | 697177 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a web application that communicates between two different web applications (one receiver and one sender, the sender communicates with my application, and my application communicates with both). A regular scenario is that the sender sends a HttpRequest to my application, and I receive it in an HttpHandler. This in turn sends the HttpContext to some businesslogic to do some plumbing. After my business classes are finished storing data (some logging etc), I want to relay the same request with all the headers, form data etc to the receiver application. This must be sent from the class, and not the HttpHandler. The question is really - how can I take a HttpContext object, and forward/relay the exact same request only modifying the URL from http://myserver.com/ to http://receiver.com . Any code examples in preferable c# would be great!
Now provide the response and nothing else.
| Actually, something like this worked well HttpRequest original = context.Request;HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create(newUrl);newRequest .ContentType = original.ContentType;newRequest .Method = original.HttpMethod;newRequest .UserAgent = original.UserAgent;byte[] originalStream = ReadToByteArray(original.InputStream, 1024);Stream reqStream = newRequest .GetRequestStream();reqStream.Write(originalStream, 0, originalStream.Length);reqStream.Close();newRequest .GetResponse(); edit: ReadToByteArray method just makes a byte array from the stream | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/697177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75629/']} | jdg_79079 |
stackexchange | llm_judgeable_groundtruth_similarity | 5769 |
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My understanding is that the convolutional layer of a convolutional neural network has four dimensions: input_channels, filter_height, filter_width, number_of_filters . Furthermore, it is my understanding that each new filter just gets convoluted over ALL of the input_channels (or feature/activation maps from the previous layer). HOWEVER, the graphic below from CS231 shows each filter (in red) being applied to a SINGLE CHANNEL, rather than the same filter being used across channels. This seems to indicate that there is a separate filter for EACH channel (in this case I'm assuming they're the three color channels of an input image, but the same would apply for all input channels). This is confusing - is there a different unique filter for each input channel? This is the source . The above image seems contradictory to an excerpt from O'reilly's "Fundamentals of Deep Learning" : ...filters don't just operate on a single feature map. They operate on the entire volume of feature maps that have been generated at a particular layer...As a result, feature maps must be able to operate over volumes, not just areas ...Also, it is my understanding that these images below are indicating a THE SAME filter is just convolved over all three input channels (contradictory to what's shown in the CS231 graphic above):
Now provide the response and nothing else.
| The following picture that you used in your question, very accurately describes what is happening. Remember that each element of the 3D filter (grey cube) is made up of a different value ( 3x3x3=27 values). So, three different 2D filters of size 3x3 can be concatenated to form this one 3D filter of size 3x3x3 . The 3x3x3 RGB chunk from the picture is multiplied elementwise by a 3D filter (shown as grey). In this case, the filter has 3x3x3=27 weights. When these weights are multiplied element-wise and then summed, it gives one value. So, is there a separate filter for each input channel? YES , there are as many 2D filters as the number of input channels in the image. However , it helps if you think that for input matrices with more than one channel, there is only one 3D filter (as shown in the image above). Then why is this called 2D convolution (if the filter is 3D and the input matrix is 3D)? This is 2D convolution because the strides of the filter are along the height and width dimensions only ( NOT depth) and therefore, the output produced by this convolution is also a 2D matrix. The number of movement directions of the filter determines the dimensions of convolution. Note: If you build up your understanding by visualizing a single 3D filter instead of multiple 2D filters (one for each layer), then you will have an easy time understanding advanced CNN architectures like Resnet, InceptionV3, etc. | {} | {'log_upvote_score': 5, 'links': ['https://ai.stackexchange.com/questions/5769', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/14389/']} | jdg_79080 |
stackexchange | llm_judgeable_groundtruth_similarity | 29411558 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This script should return result and displayed result in "answer" >paragraph but instead it appears for moment and then disappeared, what i miss? < script > function dataValidation() { var initial = document.getElementById("anyWord").value var char = /[^а-яА-Я]/ if (initial == null || initial == "") { alert('Please, enter only cyrillic letters.') } else if (initial.match(char)) { alert('Please enter only cyrillic') } else shmovoConverter() }function shmovoConverter() { var sAnyWord = document.getElementById('anyWord').value var shm = 'Шм' var vowels = ['а', 'у', 'о', 'ы', 'и', 'э', 'я', 'ю', 'ё', 'е', 'а', 'у'] var consonants = ['б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ'] for (var i = 0; i < vowels.length; i++) { var firstLater = sAnyWord.substring(0, 1) if (firstLater === vowels[i]) { alert(shm + sAnyWord) var sAnswer = shm + sAnyWord document.getElementById('answer').innerHTML = sAnswer } else { for (var j = 0; j < consonants.length; j++) { if (firstLater === consonants[j]) { sAnyWord = sAnyWord.substring(1, sAnyWord.length) i = 0 } } } }}< /script> <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>Registration Form</title></head><body style="background-color: #FFFFCC"> <div style="margin-left: 200px;margin-top: 100px;margin-bottom: auto;margin-right: 400px;border: solid;border-color: #D6BA01;background-color: #F5DEB3"> <form id="RegForm"> <p style="margin-left: 10px" align="center">Slovo - Shmovo</p> <p style="margin-left: 10px">Enter any word: <input type="text" id="anyWord"> </p> <p></p> <p style="margin-left: 10px"> <input type="submit" name="submit" value="Submit" id="submitBtn" onclick="dataValidation()" /> </p> <p id="answer"></p> </form> This script should return result and displayed result in "answer" paragraph, but instead it appears for moment and then disappeared, what i miss?
Now provide the response and nothing else.
| ::ffff: is a subnet prefix for IPv4 (32 bit) addresses that are placed inside an IPv6 (128 bit) space. IPv6 is broken into two parts, the subnet prefix, and the interface suffix. Each one is 64 bits long, or, 4 groups of 4 hexadecimal characters. In IPv6, you are allowed to remove leading zeros, and then remove consecutive zeros, meaning ::ffff: actually translates to 0000:0000:ffff:0000 , this address has been designated as the IPv4 to IPv6 subnet prefix, so any IPv6 processor will understand it's working with an IPv4 address and handle it accordingly. In the near future, IP addresses will all be IPv6, this is because we are nearly out of numbers (4.2 billion, minus some space for misc. purposes) in the IPv4 address space. IPv6 allows for a much larger space. "340 undecillion ought to beenough for anyone" - Bill Gates speaking on IPv6. It is important to start addressing IP addresses using the IPv6 namespace and therefore include the ::ffff: in your code because in the future there will be real hexadecimal data between those colons. If you strip it off for aesthetic reasons, your code will break when it switches to an IPv6 network or it's confronted with an IPv6 address. Some networks are currently running IPv6 and you will soon be confronted with IPv6 IP addresses; make the leap now or risk breaking your code in the future. The TL;DR (short) version of the matter is: Everything is working fine. Don't change it, it's the IPv6 version of an IPv4 address. If you want to make your code compatible with IPv6, all you have to do is check for the ::ffff: prefix... if it exists, remove it and process the remainder as IPv4... if ::ffff: doesn't exist, it's an IPv6 address and needs to be processed as such.You can double-check by seeing if periods are in the string, if so, it's IPv4. Keep in mind for everything but adjustments you need to make to IP addresses, you're just recording the IP, right? It's going to be important to the parser and log aggregates to expect ::ffff:127.0.0.1 and such in the future. Unless you need to alter an IP, just leave it as what you receive. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/29411558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4742093/']} | jdg_79081 |
stackexchange | llm_judgeable_groundtruth_similarity | 1851567 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Enum with strings Is it possible to have string constants in enum like the following? enum{name1="hmmm" name2="bdidwe"} If it is not, what is the best way to do so? I tried it, but it's not working for string so right now I am grouping all related constants in one class like class operation { public const string name1="hmmm"; public const string name2="bdidwe" }
Now provide the response and nothing else.
| Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums. When I want something like a "string-based enum" I create a class to hold the constants like you did, except I make it a static class to prevent both unwanted instantiation and unwanted subclassing. But if you don't want to use string as the type in method signatures and you prefer a safer, more restrictive type (like Operation ), you can use the safe enum pattern: public sealed class Operation{ public static readonly Operation Name1 = new Operation("Name1"); public static readonly Operation Name2 = new Operation("Name2"); private Operation(string value) { Value = value; } public string Value { get; private set; }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1851567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65917/']} | jdg_79082 |
stackexchange | llm_judgeable_groundtruth_similarity | 39605289 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Im trying to build an api , and for some reason I need sessions. But if I include web middleware I get CSRF errors, and if I dont I cant have session started. How to solve this?
Now provide the response and nothing else.
| go to app/Http/Kernel.php and add your own name like 'sessions' to the $middlewareGroups. It should contain \Illuminate\Session\Middleware\StartSession::class, Assign 'sessions' to those routes you want. protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], 'sessions' => [ \Illuminate\Session\Middleware\StartSession::class, ] ]; routes/api.php Route::group(['middleware' => ['sessions']], function () { Route::resource(...);}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39605289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1093486/']} | jdg_79083 |
stackexchange | llm_judgeable_groundtruth_similarity | 28140671 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to render a datatable with dynamic columns using JSON but keep getting the following error: Uncaught TypeError: Cannot read property 'length' of undefined. Any help would be greatly appreciated. Thanks!! JS: <link href="http://cdn.datatables.net/1.10.4/css/jquery.dataTables.css" rel="stylesheet" type="text/css"/><script src="http://cdn.datatables.net/1.10.4/js/jquery.dataTables.js" type="text/javascript"></script>jQuery(document).ready(function() { var dataObject = '[{"COLUMNS":[{ "sTitle": "NAME"}, { "sTitle": "COUNTY"}],"DATA":[["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]}]'; var columns = []; jQuery.each(dataObject.COLUMNS, function(i, value){ var obj = { sTitle: value }; columns.push(obj); }); jQuery('#example').dataTable({ "bProcessing": true, "bPaginate": true, "sPaginationType": "full_numbers", "aaData": dataObject.DATA, "aoColumns": columns });}); HTML: <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <tr><thead>column1</thead></tr> <tbody></tbody></table>
Now provide the response and nothing else.
| Hi there are several issue in the code... dataObject is string, not a json. so you can make it json object using eval() or removing ' the parameter name you are passing in datatable is wrong. you need to provide the accurate parameter. You are using the parent json object as array. but you are not using [] to get its first element. your html content is the table is wrong. since you are passing the columns name using java script. you dont need the html table headers. the length error actually occurring because of this html code. if you remove the html inside the tables then your code will not have the length error. but still the above error i mentioned will be there. please check the code bellow. may be you are looking for this code... jQuery(document).ready(function() { var dataObject = eval('[{"COLUMNS":[{ "title": "NAME"}, { "title": "COUNTY"}],"DATA":[["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]}]'); var columns = []; $('#example').dataTable({ "data": dataObject[0].DATA, "columns": dataObject[0].COLUMNS });}); <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28140671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2690708/']} | jdg_79084 |
stackexchange | llm_judgeable_groundtruth_similarity | 2481862 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The more I learned about the power of java.lang.reflect.AccessibleObject.setAccessible , the more astonished I am at what it can do. This is adapted from my answer to the question ( Using reflection to change static final File.separatorChar for unit testing ). import java.lang.reflect.*;public class EverythingIsTrue { static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static void main(String args[]) throws Exception { setFinalStatic(Boolean.class.getField("FALSE"), true); System.out.format("Everything is %s", false); // "Everything is true" }} You can do truly outrageous stuff: public class UltimateAnswerToEverything { static Integer[] ultimateAnswer() { Integer[] ret = new Integer[256]; java.util.Arrays.fill(ret, 42); return ret; } public static void main(String args[]) throws Exception { EverythingIsTrue.setFinalStatic( Class.forName("java.lang.Integer$IntegerCache") .getDeclaredField("cache"), ultimateAnswer() ); System.out.format("6 * 9 = %d", 6 * 9); // "6 * 9 = 42" }} Presumably the API designers realize how abusable setAccessible can be, but must have conceded that it has legitimate uses to provide it. So my questions are: What are the truly legitimate uses for setAccessible ? Could Java has been designed as to NOT have this need in the first place? What would the negative consequences (if any) of such design be? Can you restrict setAccessible to legitimate uses only? Is it only through SecurityManager ? How does it work? Whitelist/blacklist, granularity, etc? Is it common to have to configure it in your applications? Can I write my classes to be setAccessible -proof regardless of SecurityManager configuration? Or am I at the mercy of whoever manages the configuration? I guess one more important question is: DO I NEED TO WORRY ABOUT THIS??? None of my classes have any semblance of enforceable privacy what-so-ever. The singleton pattern (putting doubts about its merits aside) is now impossible to enforce. As my snippets above show, even some basic assumptions of how Java fundamental works is not even close to being guaranteed. ARE THESE PROBLEMS NOT REAL??? Okay, I just confirmed: thanks to setAccessible , Java strings are NOT immutable. import java.lang.reflect.*;public class MutableStrings { static void mutate(String s) throws Exception { Field value = String.class.getDeclaredField("value"); value.setAccessible(true); value.set(s, s.toUpperCase().toCharArray()); } public static void main(String args[]) throws Exception { final String s = "Hello world!"; System.out.println(s); // "Hello world!" mutate(s); System.out.println(s); // "HELLO WORLD!" }} Am I the only one who thinks this is a HUGE concern?
Now provide the response and nothing else.
| DO I NEED TO WORRY ABOUT THIS??? That depends entirely on what types of programs you're writing and for what kind of an architecture. If you're distributing a software component called foo.jar to the people of the world, you're completely at their mercy anyway. They could modify the class definitions inside your .jar (through reverse engineering or direct bytecode manipulation). They could run your code in their own JVM, etc. In this case worrying will do you no good. If you're writing a web-application that only interfaces with people and systems via HTTP and you control the application server, it's also not a concern. Sure the fellow coders at your company may create code that breaks your singleton pattern, but only if they really want to. If your future job is writing code at Sun Microsystems/Oracle and you're tasked with writing code for the Java core or other trusted components, it's something you should be aware of. Worrying, however, will just make you lose your hair. In any case they'll probably make you read the Secure Coding Guidelines along with internal documentation. If you're going to be writing Java applets, the security framework is something you should be aware of. You'll find that unsigned applets trying to call setAccessible will just result in a SecurityException. setAccessible is not the only thing that goes around conventional integrity checks. There's a non-API, core Java class called sun.misc.Unsafe that can do pretty much anything at all it wants to, including accessing memory directly. Native code (JNI) can go around this kind of control as well. In a sandboxed environment (for example Java Applets, JavaFX), each class has a set of permissions and access to Unsafe, setAccessible and defining native implementations are controlled by the SecurityManager. "Java access modifiers are not intended to be a security mechanism." That very much depends on where the Java code is being run. The core Java classes do use access modifiers as a security mechanism to enforce the sandbox. What are the truly legitimate uses for setAccessible? The Java core classes use it as an easy way to access stuff that has to remain private for security reasons. As an example, the Java Serialization framework uses it to invoke private object constructors when deserializing objects. Someone mentioned System.setErr, and it would be a good example, but curiously the System class methods setOut/setErr/setIn all use native code for setting the value of the final field. Another obvious legitimate use are the frameworks (persistence, web frameworks, injection) that need to peek into the insides of objects. Debuggers, in my opinion, don't fall into this category, as they normally don't run in the same JVM process, but instead the interface with the JVM using other means (JPDA). Could Java has been designed as to NOT have this need in the first place? That's a pretty deep question to answer well. I imagine yes, but you'd need to add some other mechanism(s) that might not be all that preferrable. Can you restrict setAccessible to legitimate uses only? The most straight-forward OOTB restriction you can apply is to have a SecurityManager and allow setAccessible only to code coming from certain sources. This is what Java already does - the standard Java classes that come from your JAVA_HOME are allowed to do setAccessible, while unsigned applet classes from foo.com aren't allowed to do setAccessible. As was said before, this permission is binary, in the sense that one either has it or not. There is no obvious way to allow setAccessible to modify certain fields/methods while disallowing others. Using the SecurityManager you could, however, disallow classes from referencing certain packages completely, with or without reflection. Can I write my classes to be setAccessible-proof regardless of SecurityManager configuration? ... Or am I at the mercy of whoever manages the configuration? You can't and you most certainly are. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2481862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276101/']} | jdg_79085 |
stackexchange | llm_judgeable_groundtruth_similarity | 48303650 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's assume we have string and a list of strings: String: str1 = <common-part> List of strings: [<common-part>-<random-text-a>, <common-part>-<random-text-b>] What is the best (in case of readability and code-purity) to get such a list: [<random-text-a>, <random-text-b>]
Now provide the response and nothing else.
| I would compute the common prefix of all strings using os.path.commonprefix , then slice the strings to remove that prefix (this function is in os.path module but doesn't check path separators, it's useable in a generic context): import osp = ["<common-part>-<some-text-a>", "<common-part>-<random-text-b>"]commonprefix = os.path.commonprefix(p)new_p = [x[len(commonprefix):] for x in p]print(new_p) result (since commonprefix is ""<common-part>-<" ): ['some-text-a>', 'random-text-b>'] notes: this method allows a full dynamic prefix, not known in advance. With reversing the strings, it's also possible to remove the common suffix. it's better to use len to slice the result instead of str.replace() : it's faster, and it only removes the start of the string, and safe since we know that all strings start by this prefix. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48303650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_79086 |
stackexchange | llm_judgeable_groundtruth_similarity | 185366 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the context of SSL/TLS certificates, what is the difference between key encipherment and data encipherment? What are some examples that highlights the difference?
Now provide the response and nothing else.
| Key encipherment means that the key in the certificate is used to encrypt another cryptographic key (which is not part of the application data). This is used within TLS in the RSA key exchange, where the pre-master secret (from which the symmetric encryption key is derived) is generated by the client, then encrypted with the servers public key and send to the server and decrypted there with the servers private key. Data encipherment means that the key in the certificate is used to encrypt application data. This is not used in TLS. But certificates are not only used for TLS (for example also in S/MIME, VPN, signing of documents ...) so there might be use cases where this is needed. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/185366', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/177528/']} | jdg_79087 |
stackexchange | llm_judgeable_groundtruth_similarity | 32600763 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the maximum number of elements that can be stored in a Map in GO? If I need to access data from Map frequently, is it a good idea to keep on adding items to Map and retrieving from it, in a long running program?
Now provide the response and nothing else.
| There is no theoretical limit to the number of elements in a map except the maximum value of the map-length type which is int . The max value of int depends on the target architecture you compile to, it may be 1 << 31 - 1 = 2147483647 in case of 32 bit, and 1 << 63 - 1 = 9223372036854775807 in case of 64 bit. Note that as an implementation restriction you may not be able to add exactly max-int elements, but the order of magnitude will be the same. Since the builtin map type uses a hashmap implementation, access time complexity is usually O(1), so it is perfectly fine to add many elements to a map, you can still access elements very fast. Note that however adding many elements will cause a rehashing and rebuilding the internals, which will require some additional calculations - which may happen occasionally when adding new keys to the map. If you can "guess" or estimate the size of your map, you can create your map with a big capacity to avoid rehashing. E.g. you can create a map with space for a million elements like this: m := make(map[string]int, 1e6) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32600763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2873262/']} | jdg_79088 |
stackexchange | llm_judgeable_groundtruth_similarity | 9746612 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to integrate ads into a already successful deployed app. However no matter what I do, I cannot seem to get the ads working. I have tried using both the code version and the drag n' drop gui version. Neither of which I can get to work. This is what I see: When it starts up it may flash for a split second white, where the ad is supposed to be, but none the less, no adds. It recognizes that it is where I place it, when I place it over a button, the button becomes unclickable. All being said, no default "microsoft advertising" image pops up. I have installed the ad SDK and have successfully been able to make the ads display in other project with ease. What gives? This is very simple page and I cannot figure out what is wrong. It also seems that I cannot place an ad on any of the other pages either... I do have the Microsoft.Advertising.Mobile and Microsoft.Advertising. Mobile.UI included in the project and my internet is working (I have an project open at the same time with ads and it works) <phone:PhoneApplicationPage x:Class="AppName.AdPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480" shell:SystemTray.IsVisible="True" xmlns:my="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"> <!--LayoutRoot is the root grid where all page content is placed--> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Margin="12,17,12,28"> <TextBlock x:Name="PageTitle" Text="Thank You!" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Width="334" /> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0" Height="569" VerticalAlignment="Top"> <Button Content="Ok" Height="72" HorizontalAlignment="Center" Margin="0,428,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" /> <my:AdControl AdUnitId="Image480_80" ApplicationId="test_client" Height="80" HorizontalAlignment="Left" Margin="-12,458,0,0" Name="adControl1" VerticalAlignment="Top" Width="480" /> </Grid> </Grid></phone:PhoneApplicationPage> using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.Phone.Controls;using Microsoft.Advertising.Mobile.UI;using Microsoft.Advertising.Mobile;namespace Stickey_Note_v._1{ public partial class AdPage : PhoneApplicationPage { public AdPage() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); } }}
Now provide the response and nothing else.
| I had the same issue and wrote a blog post about it. Here's the important stuff: The symptoms of a problem with the SDK's AdControl seem to be pretty consistent: The page loads, the control flickers briefly, showing the hint of a 1 pixel frame, and then, poof . It collapses into nothingness, leaving only a black hole of dispair. In theory, setting up the AdControl is simple. The documentation from Microsoft outlines the basics: Download and install the Microsoft Advertising SDK . Add a reference to Microsoft.Advertising.Mobile.UI . Drag the control onto the page in the Visual Studio designer. Set the AdUnitId and ApplicationId properties to either test values or actual live values, which you can obtain from Microsoft pubCenter. But it couldn't be that easy. I followed the documentation carefully, but nothing was working. I couldn't even get test ads to show up, which seemed really weird. I even reverted to an older version of my app (yay source control!) and dropped in the new .dll. Failure. Finally, I found a clue in an obscure forum post . The Microsoft documentation neglects to mention several important details. You need to pay particular attention to the following if you're upgrading an existing project to the Mango ad SDK, as I was: You must specify a height and width for the AdControl . Failing to specify the Height and Width attributes, or setting them to auto , will cause tears of frustration. I'd recommend 80 pixels high and 480 pixels wide, as that's the native size of the ads that Microsoft serves up. It seems that you can't have two AdControls on the same page, or at least not in the same parent element. The second one will collapse. There might be a way around this, but I discovered it while building my demo app and didn't care to pursue a solution. You must must must specify certain capabilities in your WMAppManifest.xml file. Since I was upgrading my app, I didn't have some of the newer capabilities declared. The one that was causing all the trouble was ID_CAP_IDENTITY_USER . The following capabilities are all required for the control to function correctly: <Capabilities> <Capability Name="ID_CAP_IDENTITY_USER"/> <Capability Name="ID_CAP_MEDIALIB"/> <Capability Name="ID_CAP_NETWORKING"/> <Capability Name="ID_CAP_PHONEDIALER"/> <Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/></Capabilities> Hope that helps! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9746612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1174574/']} | jdg_79089 |
stackexchange | llm_judgeable_groundtruth_similarity | 64498 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a really natural question for which I know a stunning solution. So I admit I have a solution, however I would like to see if anybody will come up with something different. The question is What is the probability that two numbers randomly chosen are coprime? More formally, calculate the limit as $n\to\infty$ of the probability that two randomly chosen numbers, both less than $n$ are coprime.
Now provide the response and nothing else.
| The first thing you should consider is that there are, in some sense, different "hierarchies" of numbers. At each stage, we enlarge the class of numbers, and try to do so in a way that leaves everything we could do before still the same, but that now we can do more. A common way of doing this is to start with the natural numbers (sometimes called "counting numbers" or positive integers). We start with $1$, $2$, $3,\ldots$. Here, we do define multiplication as repeated addition. For example, one way to define multiplication is to assume we know how to add, and then define it by saying:$$\begin{align*}n\times 1 &= n\\n\times (k+1) &= (n\times k) + n % need to edit at least 6 characters\end{align*}$$Using mathematical induction , we can show this defines multiplication for all positive integers, and that it has the usual properties we know (commutative, so that $n\times k = k\times n$ for all positive integer $n$ and $k$, distributes over the sum, is associative, etc). Then we have two choices for "expanding our universe of numbers": we can now define negative integers, by considering things that would help us solve all equations of the form $a+x=b$ with $a$ and $b$ positive integers; or we can introduce positive rationals (fractions) by considering all things that would help us solve all equations of the form $ax = b$. Let's do the latter, since that came first historically. So, we had the positive integers, and we knew how to add and multiply them. Now we are going to have more numbers: now, for every pair of positive integers $a$ and $b$, we will have a number "$\frac{a}{b}$", which is a number that satisfies the property that$$b\times\left(\frac{a}{b}\right) = a.$$We also say that $\frac{a}{b}$ is "the same fraction" as $\frac{c}{d}$ if and only if $ad=bc$ (here we are comparing products of positive integers, so that's fine). We also notice that our old positive integers can also be considered fractions: the positive integer $a$ is a solution to $1x = a$, so $a$ corresponds to the fraction $\frac{a}{1}$. Now, how do we add two of these numbers? Since $\frac{a}{b}$ represents the solution to $bx=a$, and $\frac{r}{s}$ represents the solution to $sx=r$, then $\frac{a}{b}+\frac{r}{s}$ represents the solution to something ; to what? A bit of algebra will tell you that it is the solution to precisely $(bs)x = (as+br)$. So we define $$\frac{a}{b}+\frac{r}{s} = \frac{as+br}{bs}.$$There's a bit of work that needs to be done to ensure that if you write the fractions differently, the answer comes out the same (if $\frac{c}{d}=\frac{a}{b}$, and if $\frac{t}{u}=\frac{r}{s}$, does $\frac{cu+td}{du} = \frac{as+br}{bs}$? Yes). And we also notice that if we add positive integers as if they were fractions , we get the same answer we did before:$$\frac{a}{1} + \frac{c}{1} = \frac{a1+c1}{1} = \frac{a+c}{1}.$$That's good; it means we are enlarging our universe, not changing it. How about products? If $\frac{a}{b}$ represents the solution to $bx=a$, and $\frac{r}{s}$ represents the solution to $sy=r$, their product will be the solution to $(bs)z = ar$. So we define $$\frac{a}{b}\times\frac{r}{s} = \frac{ar}{bs}.$$And then we notice that it extends the definition of multiplication for integers, since $\frac{a}{1}\times\frac{b}{1} = \frac{a\times b}{1}$. And we check to see that multiplication and addition still have the properties we want (commutativity, associativity, etc). (There are other ways to figure out what multiplication of fractions "should be", on the basis of what we want it to do. For example, we want multiplication to extend multiplication of integers, so $\frac{a}{1}\times\frac{b}{1}$ should be $\frac{ab}{1}$; and we want it to distribute over the sum, so we want$$\frac{a}{1} = \frac{a}{1}\times \frac{1}{1} = \frac{a}{1}\times\left(\underbrace{\frac{1}{b}+\frac{1}{b}+\cdots+\frac{1}{b}}_{b\text{ summands}}\right) = \underbrace{\left(\frac{a}{1}\times\frac{1}{b}\right) + \cdots + \left(\frac{a}{1}\times\frac{1}{b}\right)}_{b\text{ summands}}.$$So $\frac{a}{1}\times \frac{1}{b}$ should be a fraction which, when added to itself $b$ times, equals $a$; that is, a solution to $bx=a$; that is, $\frac{a}{b}$. And so on). Then we move on from the positive rationals (fractions) to the positive reals. This is more complicated, as it involves "filling in gaps" between rationals. It is very technical. But what it turns out is that for every real number you can find a sequence of rationals $q_1,q_2,q_3,\ldots$ that get progressively closer to each other and to $r$ (we say the sequence "converges to $r$"); it won't hurt too much if you think of the $q_i$ as being progressive decimal approximations to $r$ (they don't have to be, and ahead of time you don't have any notion of decimal approximation, but you can think of it that way for our purpose). So then the way we define multiplication of real numbers $r$ and $s$ is to find a sequence of rationals $q_1,q_2,q_3,\ldots$ giving the approximation to $r$, and one $p_1,p_2,p_3,\ldots$ giving the approximation to $s$, and we define $r\times s$ to be whatever it is that the sequence$$p_1\times q_1,\ p_2\times q_2,\ p_3\times q_3,\ \ldots$$approximates. This ensures that if you take rational numbers and multiply them as if they were reals you get the same thing as if you multiply them as rationals, and likewise for integers. So multiplication of positive reals is really a series of approximations made up by multiplying rationals; and multiplication of rationals is really a way to codify solutions to certain equations with integers; and it is only multiplication of (positive) integers that really corresponds to "repeated addition". Finally, once you have the positive reals, you can introduce the negative real numbers. We consider solutions to equations of the form $a+x=b$ with $a$ and $b$ positive real numbers. Some of these already have solutions, some don't. This gives us "zero" and "negative reals". We then extend the definition of multiplication to "zero" and to "the negative reals" in a way that makes sense relative to this definition. Turns out we need to make $0\times r = 0$ for all $r$, and have to respect the "rules of signs" to make sure everything still works. So we define it that way to make sure everything works and what we had before still works exactly the same. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/64498', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15453/']} | jdg_79090 |
stackexchange | llm_judgeable_groundtruth_similarity | 12836 |
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the translations of the Greek word μονογενής in Ancient Versions? What are the rendering of μονογενής into Ancient Versions of the *NT passages? Hebrew Arabic: Ethiopic: Syriac (Aramaic): Latin (Old Latin/ Latin Vulgate): Egyptian (Coptic): Georgian: Gothic: Slavonic: Does it mean "only" or "only-begotten"? *The following Bible verses have μονογενής in it: John 1:14;John 1:18;John 3:16;John 3:18 and 1 John 4:19. Luke 7:12;Luke 8:42 andLuke 9:38. Hebrews 11:17 Note Ancient Versions are the ancient translations of the NT Greek into another language.
Now provide the response and nothing else.
| Table of Contents Amharic (Ethiopic) Coptic Bohairic Sahidic Georgian Gothic Hebrew Latin Slavic Syriac (Aramaic) Amharic (Ethiopic) According to Wikipedia , Although Christianity became the state religion of Ethiopia in the 4th century, and the Bible was first translated into Ge'ez at about that time, only in the last two centuries have there appeared translations of the Bible into Amharic. Accordingly, there are no extant early Amharic manuscripts of the New Testament. Coptic Coptic translations of the Greek New Testament occur in a variety of dialects, two primarily being Bohairic and Sahidic . Bohairic For examination of the Bohairic, I reviewed the multi-volume The Coptic Version of the New Testament in the Northern Dialect, Otherwise Called Memphitic and Bohairic , compiled by George William Horner. John 1:14 John 1:18 John 3:16 John 3:18 1 John 4:9 Luke 7:12 Luke 8:42 Luke 9:38 Heb. 11:17 Analysis of the Bohairic The Bohairic manuscript is interesting in that it does not consistently use the same word to translate the Greek adjective μονογενής. Rather, in 6 of the 9 verses, x it uses the adjective mawaa . According to Crum in A Coptic Dictionary , z the Bohairic adjective mawaa means "alone, single." On the other hand, in 3 of the 9 verses, y it uses the adjective monogenēs which is actually a loanword derived from the Greek adjective μονογενής. Sahidic For examination of the Sahidic, I reviewed the multi-volume The Coptic Version of the New Testament in the Southern Dialect, Otherwise Called Sahidic and Thebaic, by George William Horner. John 1:14 John 1:18 John 3:16 John 3:18 1 John 4:9 Luke 7:12 Luke 8:42 Luke 9:38 Heb. 11:17 Analysis of the Sahidic Each of the verses used a declension of the Sahidic adjective ⲚⲞⲨⲰⲦ ( nouōt ). According to The Sahidica Lexicon: A Basic Sahidic-English Lexicon , the Sahidic adjective ⲚⲞⲨⲰⲦ translates into English as "one, the only, alone." Georgian The earliest extant Georgian manuscript is known as the Adysh Gospels (Geo. ადიშის ოთხთავი), dated to the late 9th century A.D. John 1:14 John 1:18 John 3:16 John 3:18 1 John 4:9 Luke 7:12 Luke 8:42 Luke 9:38 Heb. 11:17 Analysis of the Georgian ... Gothic The earliest extant Gothic manuscript is known as the Gothic Bible or Wulfila Bible, which was translated by Wulfila () in the 4th century A.D. According to Wikipedia , Surviving fragments of the Wulfila Bible consist of codices from the 6th to 8th century containing a large part of the New Testament and some parts of the Old Testament, largely written in Italy. These are the Codex Argenteus, which is kept in Uppsala, the Codex Ambrosianus A through Codex Ambrosianus E, containing the epistles, Skeireins, and Nehemiah 5–7, the Codex Carolinus (Romans 11–14), the Codex Vaticanus Latinus 5750 (Skeireins), the Codex Gissensis (fragments of the Gospel of Luke) and the Fragmenta Pannonica, and fragments of a 1 mm thick metal plate with verses of the Gospel of John. It does contain the Gospel of John, but it omits the relevant verses. It also omits 1 John and the Epistle to the Hebrews. The text of the Wulfila Bible is available at www.wulfila.be with corresponding interlinear of the Greek NA26th/27th ed., Latin Clementine Vulgate, English King James Version, Dutch Statenvertaling, and/or French Louis Segond Version. It also features lexical linking to Gotisch-Griechisch-Deutsches Wörterbuch by Wilhelm Streitberg. In addition, facsimiles of the Codex Argenteus are available at: http://app.ub.uu.se/arv/codex/faksimiledition/contents.html . John 1:14 omitted John 1:18 omitted John 3:16 omitted John 3:18 omitted 1 John 4:9 omitted Luke 7:12 Single red dots encompass the word ( ainaha ); double red dots encompass Luke 7:12. Facsimile of entire page of manuscript containing Luke 7:9-14 (Ms. 147 r.) is available [ here ]. , , , , , . Gothic biþeh þan nehva was daura þizos baurgs, þaruh sai, utbaurans was naus, sunus ainaha aiþein seinai, jah si silbo widowo, jah managei þizos baurgs ganoha miþ izai. Romanization Luke 8:42 Single red dots encompass the word ( ainoho ); double red dots encompass Luke 8:42. Facsimile of entire page of manuscript containing Luke 8:38-43 (Ms. 155 r.) is available [ here ]. , . , . Gothic unte dauhtar ainoho was imma swe wintriwe twalibe, jah so swalt. miþþanei þan iddja is, manageins þraihun ina. Romanization Luke 9:38 Single red dots encompass the word ( ainaha ); double red dots encompass Luke 9:38. Facsimile of entire page of manuscript containing Luke 9:36-42 (Ms. 160 v.) is available [ here ]. , : , , . Gothic jah sai, manna us þizai managein ufwopida qiþands: laisari, bidja þuk insaihvan du sunu meinamma, unte ainaha mis ist. Romanization Heb. 11:17 omitted Analysis of the Gothic Each of the three Lukan texts found in the Wulfila codices use a declension of the Gothic adjective ( ainahs ) to translate the Greek adjective μονογενής. According to Streitberg, 2 () is equivalent to the Greek adjective μονογενής and German adjective einzig (which translates into English as "only, sole; unique"). Hebrew There are no extant early Hebrew manuscripts of the New Testament. Latin The earliest extant Latin manuscript of the gospels is perhaps the Codex Vercellensis dated to the 4th century A.D. According to Wikipedia , Old Latin Codex Vercellensis Evangeliorum, preserved in the cathedral library is believed to be the earliest manuscript of the Old Latin Gospels. Its standard designation is "Codex a" (or 3 in the Beuron system of numeration). It does not contain the First Epistle of John or the Epistle to the Hebrews. I could not find the digitized manuscript of the Codex Vercellensis available online, but I found a book entitled Codex Vercellensis Iamdudum Ab Irico Et Bianchino Bis Editus Denuo Cum Manuscripto Collatus In Lucem Profertur , by Francis Aidan Cardinal Gasquet, which contains the collated text of the Codex Vercellensis. John 1:14 nati sunt et verbum caro factum est et inhabita uit in nobis et vidimus gloriam eius gloriam sicut unici filii a patre plenus gratiae et veritate John 1:18 Dm nemo vidit unquam nisi unicus filius solus sinum patris ipse enarravit John 3:16 nam sic eni dilexit deus hunc mundum ut filium suum unicum daret ut omnis qui credit in eum no pereat sed habeat vitam aeternam John 3:18 Ideo qui credit in eum non iudicatur qui autem non credit iam iudica tus est quia non credidit in nomine unici filii dei 1 John 4:9 Omitted Luke 7:12 Factum est autem cum adropinquaret portae civtatis et ecce efferebatur mortuus filius unicus matris suae et haec erat vidua et turba civitatis magna cum illa Luke 8:42 quia filia unica erat ille fere annorum duodecim et haec moriebatur et factum est dum iret turba ... at et con[pri]me[bat] Luke 9:38 et ecce virde [tur]ba exc[lam]avit dicens magister oro te respicias in filium meum quia unicus mihi est Heb. 11:17 Omitted Analysis of the Latin Each verse examined contains a declension of the Latin adjective unicus which Lewis & Short define as "one and no more, only, sole, single (class)," as well as "unique." 1 Slavonic The earliest extant Slavonic manuscript is ... John 1:14 John 1:18 John 3:16 John 3:18 1 John 4:9 Luke 7:12 Luke 8:42 Luke 9:38 Heb. 11:17 Analysis of the Slavonic ... Syriac The earliest extant Syriac manuscript containing the gospels appears to be the Curetonian Syriac. For examination of the Syriac, I reviewed the two-volume Evangelion da-Mepharreshe: the Curetonian Version of the Four Gospels, with the Readings of the Sinai Palimpsest and the Early Syriac Patristic Evidence , by Francis Crawford Burkitt. John 1:14 John 1:18 John 3:16 John 3:18 1 John 4:9 Omitted Luke 7:12 Luke 8:42 Luke 9:38 Heb. 11:17 Omitted Analysis of the Syriac The Curetonian Syriac manuscript consistently translates the Greek adjective μονογενής by a declension of the Syriac adjective ܝܚܝܕܝܐ ( yechidaya ). According to Robert Payne Smith in A Compendious Syriac Dictionary , **** the Syriac word ܝܚܝܕܝܐ means "sole, only, only-begotten." Footnotes 1 p. 1932, ūnĭcus 2 p. 4 x Luke 7:12, 8:42, 9:38; John 1:14, 3:16; Heb. 11:17 y John 1:18, 3:18; 1 John 4:9 z p. 198 aa p. 191 References Burkitt, Francis Crawford. Evangelion da-Mepharreshe. Vol. 1. Cambridge: Cambridge UP, 1904. Burkitt, Francis Crawford. Evangelion da-Mepharreshe. Vol. 2. Cambridge: Cambridge UP, 1904. Gasquet, Francis Aidan. Codex Vercellensis Iamdudum Ab Irico Et Bianchino Bis Editus Denuo Cum Manuscripto Collatus In Lucem Profertur. Vol. 1. Rome: Pustet: 1914. Gasquet, Francis Aidan. Codex Vercellensis Iamdudum Ab Irico Et Bianchino Bis Editus Denuo Cum Manuscripto Collatus In Lucem Profertur. Vol. 2. Rome: Pustet: 1914. Horner, George William. The Coptic Version of the New Testament in the Northern Dialect, Otherwise Called Memphitic and Bohairic. Vol. 2. Oxford: Clarendon, 1898. Horner, George William. The Coptic Version of the New Testament in the Northern Dialect, Otherwise Called Memphitic and Bohairic. Vol. 3. Oxford: Clarendon, 1905. Horner, George William. The Coptic Version of the New Testament in the Northern Dialect, Otherwise Called Memphitic and Bohairic. Vol. 4. Oxford: Clarendon, 1905. Horner, George William. The Coptic Version of the New Testament in the Southern Dialect, Otherwise Called Sahidic and Thebaic. Vol. 2. Oxford: Clarendon, 1911. Horner, George William. The Coptic Version of the New Testament in the Southern Dialect, Otherwise Called Sahidic and Thebaic. Vol. 3. Oxford: Clarendon, 1911. Horner, George William. The Coptic Version of the New Testament in the Southern Dialect, Otherwise Called Sahidic and Thebaic. Vol. 5. Oxford: Clarendon, 1920. Horner, George William. The Coptic Version of the New Testament in the Southern Dialect, Otherwise Called Sahidic and Thebaic. Vol. 7. Oxford: Clarendon, 1924. Lewis, Charlton T.; Short, Charles. Harper’s Latin Dictionary: A New Latin Dictionary Founded on the Translation of Freund’s Latin-German Lexicon. New York: American Book, 1879. Smith, Robert Payne. A Compendious Syriac Dictionary. Trans. Margoliouth, Jessie Payne. Oxford: Clarendon, 1903. Streitberg, Wilhelm. Die Gotische Bibel. Zweiter Teil: Gotisch-Griechisch-Deutsches Wörterbuch. Heidelberg: Carl Winter's Universitätsbuchhandlung, 1910. The Sahidica Lexicon: A Basic Sahidic-English Lexicon. Ed. Wells, J. Warren. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/12836', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/2577/']} | jdg_79091 |
stackexchange | llm_judgeable_groundtruth_similarity | 313256 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the infinite square well with bounds $0$ and $a$, the solutions to the time independent Schrodinger equation are:$$\psi_n(x)=\sqrt{\dfrac{2}{a}}\sin{\left(\dfrac{n\pi}{a}x\right)}$$One of the properties of these wave functions is that they are "mutually orthogonal", meaning that$$\int_0^a \psi_m(x)^* \psi_n(x)dx=\delta_{mn}$$Where $\delta_{mn}$ is the Kronecker delta. This fact is useful for finding the coefficient $c_n$ in the linear combination$$f(x)=\sum_{n=1}^{\infty}c_n\psi_n(x)$$However, does orthonormality mean anything in terms of the particle? Do particles with mutually orthogonal stationary states differ from particles without them from a physical point of view?
Now provide the response and nothing else.
| These orthogonal states are energy eigenstates. Every measurable quantity provides an orthogonal basis of eigenstates. The physical meaning of their orthogonality is that, when energy (in this example) is measured while the system is in one such state, it has no chance of instead being found to be in another. Thus a general state's probability of being observed in state $n$ upon making such a measurement is $c_n^\ast c_n$ . A similar analysis for two consecutive measurements, be they of the same observable or different observables, can be used to derive the probability distribution for the second measurement's result. This requires understanding the state's time-dependence between measurements. The energy eigenstates' probability distribution doesn't change over time, as the $c_n$ are simply multiplied by the unit complex number $\exp -\frac{iE_n t}{\hbar}$ over a time $t$ . | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/313256', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/72969/']} | jdg_79092 |
stackexchange | llm_judgeable_groundtruth_similarity | 11448367 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I bind an observable to an editable div text content?
Now provide the response and nothing else.
| You will need to modify the default "text" binding so that it is able to write the content of the edited div back to the observable. A simple custom binding handler for this task can look like this: ko.bindingHandlers.editableText = { init: function(element, valueAccessor) { $(element).on('blur', function() { var observable = valueAccessor(); observable( $(this).text() ); }); }, update: function(element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); $(element).text(value); }}; But please note that this example code requires jQuery. Usage is as simple as this: <div contentEditable="true" data-bind="editableText: foo"></div> Here is an example (written in CoffeeScript): http://jsfiddle.net/aBUEu/1/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11448367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177441/']} | jdg_79093 |
stackexchange | llm_judgeable_groundtruth_similarity | 53369140 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is the code that I have used to show some of the data. In this code, I am having anchor tag and I want to copy the link of that anchor tag when clicking on it. This is the code I have used as below: <div class="search_item_list clearfix" id="response"> <?php foreach($jobs as $job){ ?> <a class="copy_text" data-toggle="tooltip" title="Copy to Clipboard" href="<?=base_url().'home/company_profile_detail?id='.$job['company_id'];?>"><span class="icon link"><i class="fa fa-link"></i></span>Copy Link</a> <?php } ?></div><script> $(".copy_text").click(function(e){ e.preventDefault(); var button = $(this); var text = button.attr("href"); text.select(); $(document).execCommand("copy"); alert("Copied the text "); })</script> I am getting the jQuery as text.select is not a function.
Now provide the response and nothing else.
| try below code snippet $('.copy_text').click(function (e) { e.preventDefault(); var copyText = $(this).attr('href'); document.addEventListener('copy', function(e) { e.clipboardData.setData('text/plain', copyText); e.preventDefault(); }, true); document.execCommand('copy'); console.log('copied text : ', copyText); alert('copied text: ' + copyText); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="copy_text" data-toggle="tooltip" title="Copy to Clipboard" href="home/company_profile_detail">Copy Link</a> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53369140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9891451/']} | jdg_79094 |
stackexchange | llm_judgeable_groundtruth_similarity | 344321 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Supposedly, an SCR/thyristor is just a simple, four layer PNPN semiconductor. If that's the case.. When a circuit calls for a SCR/thyristor, and there isn't one available, can it be substituted by (i.e. crafted from) two BJTs (or other discrete components, for that matter)? Here are a couple of examples I had in mind; anode = blue, gate = green, cathode = orange:
Now provide the response and nothing else.
| There are two easy kinds of thyristors made out of two BJTs. One is the SCR and the other is a PUJT. (The PUJT will use the base of \$Q_2\$ instead of the base of \$Q_1\$ as the gate -- see circuits below.) But the main problems I encountered in making one of these work out of discrete parts is that you need to hand-select BJTs to make this work. Otherwise, nothing good comes of it and it is very, very frustrating. So the left-side schematic shown below is mostly impractical . So don't even bother. simulate this circuit – Schematic created using CircuitLab Some added components can make things work well. Spehro's circuit, I think, represents additions I'd made before to work with actual parts. (See the middle circuit.) The idea is that \$R_1\$ holds \$Q_1\$ off and \$R_2\$ also holds \$Q_2\$ off until something happens . By supplying some current via the gate input, more of this current passes through \$R_1\$ at first but as the current is increased it eventually reaches sufficient voltage drop across \$R_1\$ that \$Q_1\$'s collector manages to pull down enough on the base of \$Q_2\$ (also held off for a bit by \$R_2\$ at first) to turn \$Q_2\$ on . When \$Q_2\$ is on , it's collector supplies a lot more current and is quite able to pull up on the base of \$Q_1\$ without the gate current being supplied anymore. So the two BJTs now supply each other's base currents and the "SCR fires," so to speak. The problem with this circuit is that the two BJTs become very, very highly saturated. So if you look at the entire SCR anode-to-cathode current and ask how it flows, you realize that the anode current goes through \$Q_2\$'s emitter and then splits in about half (\$\beta=1\$) so that half of it goes through the base-emitter junction of \$Q_2\$ and about half through its collector. Similar logic applies to \$Q_1\$'s emitter current, too. The upshot here is that the voltage drop across the device must be the sum of a very saturated \$V_{CE}\$ plus a super-high-current driven base-emitter diode junction whose voltage drop depends almost entirely on the amount of current you want to drive through the device. And since this can be quite high, you can easily wind up with voltage drops exceeding a volt and perhaps even 1.5 volts. A response to this is to come up with a way to reduce the needed base currents so that the voltage drop across the BE junctions can be similarly reduced. One fix to this problem is to redesign the upper section to allow a better division of the SCR current so that more of it flows through the collector of \$Q_1\$. Using a diode like a 1N4148 achieves this. (See the right-most circuit above.) This diode is essentially just a diode-connected BJT -- with an important difference. The saturation current for typical diodes is much higher than it is for small signal BJTs. (And they can carry a fair current, too.) This means that they conduct a fair bit more current through them for the same voltage across them. In effect, this makes for a current mirror with a current gain that is very much less than 1. How much less, exactly, doesn't really matter because ANY improvement here helps to reduce the voltage drop across the entire circuit. So it's all to the good. Different diodes with some different saturation currents will yield different results. But pretty much any diode you can put hands on will have higher saturation currents than most BJTs you might apply. So it "just works," usually. So what happens? Well, the same process applies to the trigger current. You need to supply some current into the gate. But now as the collector of \$Q_1\$ pulls current from the "current mirror" above it, most of that current will come by way of the diode. (But since this isn't a resistor, the developed voltage isn't linearly related to the current, so the voltage across the diode raises up by perhaps a hundred millivolts per decade change in current.) This will develop a voltage across the diode, which gets applied to the base-emitter junction of \$Q_2\$. However, \$Q_2\$'s collector current will be nothing nearly as much here as the diode current, so most of the total SCR current now diverts through the collector of \$Q_1\$ with only a much smaller (but still quite adequate) collector current in \$Q_2\$. This collector current in \$Q_2\$ is still way more than enough to pull \$Q_1\$ fully on . But now it's only a small portion of the SCR current, most of which is passing through the diode and the collector of \$Q_1\$. This means that the \$V_{BE}\$ of each BJT is lower. And this means also that the total voltage drop across the entire circuit can be less (by some margin.) Depending on the exact resistor value for \$R_1\$ and the desired peak currents through the circuit, you can make a much better performing overall "device" this way. By proper selection of the diode (not hard, actually), you can arrange things so that the BJTs operate at a somewhat higher saturated \$\beta\$, which improves the voltage drop while still performing the desired function. You can also apply a small resistor in series with the diode to degrade the effective \$\beta\$ in \$Q_1\$. (But at some point you lose all benefits of the diode if the value is too large.) Or use a small resistor in parallel with the diode to raise the effective \$\beta\$ in \$Q_1\$. (But the entire thing will stop working if you make the parallel resistor too small.) Another diode in parallel can also be used, I suppose. I haven't tried that but the effect might be useful, as well, in reducing the total voltage drop a little. I hadn't run a simulation before, but here's an example output illustrating a difference with a anode-cathode current of about \$50\:\textrm{mA}\$: The red line shows the power dissipation of a circuit similar to the resistor-only version (middle circuit above) and the green line shows the power dissipation of the diode version (right circuit above.) (They are otherwise nearly identical.) Keep in mind these are simulated schematic parts. So actual results will be different. But the basic idea remains. You can see that the green line is lower (less power) than the red line and is in this case about 1/3rd lower in power dissipation. Meanwhile, the light blue (aqua?) line shows the anode current of the resistor-only version and the dark blue line shows the anode current of the diode version. Here, you can see that more anode current occurs because the voltage drop across the diode version is less (a \$200\:\Omega\$ resistor is acting as the anode load in my circuit simulation test, with a \$10\:\textrm{V}\$ source voltage.) So there is a lower circuit voltage drop in the diode-based circuit (which is better) and lower power dissipation, as well (which is also better.) | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/344321', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/83512/']} | jdg_79095 |
stackexchange | llm_judgeable_groundtruth_similarity | 1846204 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to calculate this integral $$\sum\limits_{k=1}^\infty\int\limits_I \frac{\lambda^k}{(k-1)!}t_k^{k-1}e^{-\lambda t_k} dt_k$$ where $I=(a,b)$. Someone told me that summation equals $\lambda$, but I don't see why. I wrote the summation as $$\sum\limits_{n=0}^\infty \frac{(\lambda t_{n+1})^n}{n!}\lambda e^{-\lambda t_{n+1}} $$ and I was trying to see if the fact that $\sum\limits_{n=0}^\infty \frac{(\lambda t)^n}{n!}=e^{\lambda t} $ could help but I'm not seeing how. Any ideas?
Now provide the response and nothing else.
| The confusion arises because of the bad choice of the name of the integration variable(s), as if it actually depended on $k$. Write the first few terms explicitly:$$\sum\limits_{k=1}^\infty\int\limits_I \frac{\lambda^k}{(k-1)!}t_k^{k-1}e^{-\lambda t_k} dt_k=\int_I \frac{\lambda}{0!}t_1^{0}e^{-\lambda t_1}dt_1+\int_I \frac{\lambda^2}{1!}t_2 e^{-\lambda t_2}dt_2+\cdots$$You can easily see that calling the first integration variable $t_1$ and the second $t_2$ is unnecessary. Rename all the $t_k$'s as $t$. Your object is just a sum of one-dimensional integrals. Then$$\sum_{k=1}^\infty\frac{\lambda^k}{(k-1)!}t^{k-1}=\lambda e^{t\lambda}\ .$$Therefore the final result is$$\lambda\int_a^b dt\ e^{-\lambda t}e^{t\lambda}=\lambda(b-a).$$Note that whoever told you that the solution is just $\lambda$ ignores the fact that it is very unlikely that $a$ and $b$ (the integration range) drop out of the game! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1846204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/308167/']} | jdg_79096 |
stackexchange | llm_judgeable_groundtruth_similarity | 10956970 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it true that in JavaScript functions return objects other than Boolean and Numbers by reference? How is this possible when those objects are destroyed when the function they belong to terminates?
Now provide the response and nothing else.
| Objects are not destroyed until all references to them are gone and garbage collected. When the object is returned, the calling code gains a reference to it, and the object is not garbage collected. Technically, the called function's stack frame is destroyed when it returns. The object, however, is not on the stack, but on the heap. The function's local reference to the object is on the stack, and is therefore destroyed, but the calling code's reference isn't destroyed until some time later. As a side note, it isn't really important how it is returned, because the function can't use the object anyway after it returns. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10956970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1404348/']} | jdg_79097 |
stackexchange | llm_judgeable_groundtruth_similarity | 44034124 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have file with line: "H:\Check\WP_20140511_029.mp4" along with other lines. I want to remove such lines indicating directory at H:\Check . I tried grep -v ".*H:\\Check.*" testout.txt > testout2.txt But it did not delete those lines. Whats wrong with my regex .*H:\\Check.* . regex101 shows that my regex correctly matches the line.
Now provide the response and nothing else.
| You can use: grep -v 'H:\\Check' testout.txt > testout2.txt It is important to use single quotes to avoid excessive escaping of backslash. Using double quotes equivalent command will be this: grep -v "H:\\\Check" testout.txt > testout2.txt EDIT: \\ in double quotes is equivalent of a single backward slash due to shell expansion that happens in double quotes only. It is evident from these echo commands: echo "H:\\Check"H:\Checkecho 'H:\\Check'H:\\Check | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44034124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1317018/']} | jdg_79098 |
stackexchange | llm_judgeable_groundtruth_similarity | 2029106 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Show that $v$ can be written as the linear combination: $$v = \frac{1}{3}s + \frac{1}{6}t$$ I don't see it. When I combine the linear combinations for $s$ and $t$ expressed by $u$ and $v$ , I get $s+t=u+5v$ , but as far as I understand, $u$ should be eliminated in the equation. Here are the equations for $s$ and $t$ (the equation for $s$ is right, but I'm not sure about $t$ ): $$s=2v-u$$ $$t=2u+3v$$
Now provide the response and nothing else.
| Short answer There are good reasons for a notation like $\dfrac{d^2y}{(dx)^2}$, but unfortunately the convention happens to be to drop the parentheses in the denominator. This goes back to Leibniz's original notation. Long answer (Note: I use $\mathrm{d}$ instead of the italic $d$ so I never forget that $\mathrm{d}$ is not like a variable.) $\Delta$ and $\mathrm{d}$ are not quite the same thing, and understanding them well may help you understand what's going on with the second derivative, so I'll start there (but you may be able to skip the first section or two). I. The meanings of $\Delta$ and $\Delta y/\Delta x$ $\Delta$ generally means something like "a difference/change in". $\Delta x$ would often be a number that represents how much $x$ changed by (say, between two points of interest). If $y$ is a quantity that depends on $x$, then $\Delta y$ means something like "a change in $y$ (and since $y$ depends on $x$ we know this change will depend on how much we're changing $x$ by: i.e. it'll change based on $\Delta x$)". For example, if $y$ stands for $f(x)$, then it would be reasonable to write $\Delta y=f(x+\Delta x)-f(x)$. The slope of a secant line (sometimes called "the average rate of change of $y$ with respect to $x$") between the points $\left(x,f(x)\right)$ and $\left(x+\Delta x,f\left(x+\Delta x\right)\right)$ is then given by $$\dfrac{f\left(x+\Delta x\right)-f(x)}{\left(x+\Delta x\right)-x}=\dfrac{f\left(x+\Delta x\right)-f(x)}{\Delta x}=\dfrac{\Delta y}{\Delta x}\tag{1}$$ II. The meanings of $\mathrm d$ and $\mathrm dy/\mathrm dx$ $\mathrm d$ generally means something like "an infinitesimal/tiny difference/change in". If $y$ is a quantity that depends on $x$, then $\mathrm dy$ means something like "a tiny change in $y$ (and since $y$ depends on $x$ we know this change will depend on how much we're changing $x$ by: i.e. it'll change based on $\mathrm dx$)". Unfortunately $\mathrm dy$ isn't very useful on its own since it's infinitesimal, but we can still compare tiny changes in $y$ to tiny changes in $x$ to get a sense for how $y$ grows. The slope of a tangent line (sometimes called "the instantaneous rate of change of $y$ with respect to $x$") at the point $\left(x,f(x)\right)$ should be what slopes of secant lines approach as $\Delta x$ gets small, so we use a limit. We define $\dfrac{\mathrm dy}{\mathrm dx}={\displaystyle \lim_{\Delta x\to0}}\dfrac{\Delta y}{\Delta x}$. This way, we have $$\dfrac{\mathrm dy}{\mathrm dx}=\lim_{\Delta x\to0}\dfrac{f\left(x+\Delta x\right)-f(x)}{\Delta x}=\lim_{h\to0}\dfrac{f\left(x+h\right)-f(x)}{h} \tag{2}$$ III. The meaning of $\Delta^2 y/\left(\Delta x\right)^2$ Sometimes we're interested in changes of changes (like "acceleration" as the change of the change of position with respect to time). As usual, we'll assume that $y$ stands for $f(x)$. To make things easier to write/think about, I'll give the function name $g(x)$ to $\Delta y$, so that $g(x)=f\left(x+\Delta x\right)-f(x)$. Note that $g(x)$ technically depends on $\Delta x$, but I don't want to write something like $g_{\Delta x}$ every time. Now we can calculate some things and see where they lead: First, we can calculate the change in the change in $y$: \begin{align}\Delta\left(\Delta y\right)&=\Delta\left(g\left(x\right)\right)\\&=g\left(x+\Delta x\right)-g\left(x\right)\\&=\left(f\left(\left(x+\Delta x\right)+\Delta x\right)-f\left(x+\Delta x\right)\right)-\left(f\left(x+\Delta x\right)-f(x)\right)\\&=f\left(x+2\Delta x\right)-2f\left(x+\Delta x\right)+f(x)\tag{3}\end{align} What about the difference in the slopes of two secant lines?:\begin{align}\Delta\left(\dfrac{\Delta y}{\Delta x}\right) & =\Delta\left(\dfrac{g(x)}{\Delta x}\right)\\ & =\dfrac{g\left(x+\Delta x\right)}{\Delta x}-\dfrac{g(x)}{\Delta x}\\ & =\dfrac{g\left(x+\Delta x\right)-g(x)}{\Delta x}\\ & =\dfrac{\Delta\left(g(x)\right)}{\Delta x}\\ & =\dfrac{\Delta\left(\Delta y\right)}{\Delta x}\tag{4}\end{align} Finally, we can look at how the slopes of secant lines are changing as compared to the change in $x$:$$\dfrac{\Delta\left(\dfrac{\Delta y}{\Delta x}\right)}{\Delta x}=\dfrac{\dfrac{\Delta\left(\Delta y\right)}{\Delta x}}{\Delta x}=\dfrac{\Delta\left(\Delta y\right)}{\left(\Delta x\right)^{2}}\tag{5}$$ Because it resembles multiplication, it's common to write $\Delta\left(\Delta y\right)$ as $\Delta^2 y$, so that this quantity we just looked at is $\dfrac{\Delta^2 y}{\left(\Delta x\right)^{2}}$. IV. The meaning of $\mathrm d^2 y/\mathrm dx^2$ Once we have a derivative, like $\dfrac{\mathrm dy}{\mathrm dx}$, we might want to differentiate it again to find things like "instantaneous acceleration". So we're interested in the following:\begin{align}\dfrac{\mathrm{d}\left(\dfrac{\mathrm{d}y}{\mathrm{d}x}\right)}{\mathrm{d}x} & =\lim_{\Delta x\to0}\dfrac{\Delta\left(\dfrac{\mathrm{d}y}{\mathrm{d}x}\right)}{\Delta x}\\ & =\lim_{\Delta x\to0}\dfrac{\Delta\left({\displaystyle \lim_{\Delta x\to0}\dfrac{\Delta y}{\Delta x}}\right)}{\Delta x}\\ & =\lim_{\Delta x\to0}\dfrac{\Delta\left({\displaystyle \dfrac{\Delta y}{\Delta x}}\right)}{\Delta x}\tag{$\star$}\\ & =\lim_{\Delta x\to0}\dfrac{\Delta^{2}y}{\left(\Delta x\right)^{2}}\tag{6}\end{align} Answer to the OP By analogy with $\dfrac{\mathrm{d}y}{\mathrm{d}x}$, it's reasonable to write the above quantity as $\dfrac{\mathrm{d}^{2}y}{\left(\mathrm{d}x\right)^{2}}$. To save writing of parentheses, the convention is often to write $\dfrac{d^{2}y}{dx^{2}}$, which I think can be confusing. Technical note When we went to the line denoted with ($\star$) above, I cheated a bit. When we're talking about limits, maybe the order or relative speeds of the two limits could matter. It would probably be better to have two different $\Delta x$s with their own limits. But for nice enough functions (at least functions with a continuous second derivative), this doesn't matter and it's safe to treat the inner and outer $\Delta x$s as the same. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2029106', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/319082/']} | jdg_79099 |
stackexchange | llm_judgeable_groundtruth_similarity | 39316069 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to decode bitmaps from Asset directory in Android 7? My App is running well on Android versions up to Marshmallow. With Android 7 it fails to load images from the Asset directory. My Code: private Bitmap getImage(String imagename) { // Log.dd(logger, "AsyncImageLoader: " + ORDNER_IMAGES + imagename); AssetManager asset = context.getAssets(); InputStream is = null; try { is = asset.open(ORDNER_IMAGES + imagename); } catch (IOException e) { // Log.de(logger, "image konnte nicht gelesen werden: " + ORDNER_IMAGES + imagename); return null; } // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, PW, PH); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // Lesen des Bitmaps in der optimierten Groesse return BitmapFactory.decodeStream(is, null, options);} As a result (only Android 7) BitmapFactory.decodeStream is null. It works correctly an older Android APIs. In debug mode I see the following Message: 09-04 10:10:50.384 6274-6610/myapp D/skia: --- SkAndroidCodec::NewFromStream returned null Can someone tell me the reason and how to correct the coding? Edit: Meanwhile i found, that removing of the first BitmapFactory.decodeStream with inJustDecodeBounds=true leads to a successful BitmapFactory.decodeStream afterwards with inJustDecodeBounds=false. Don't know the reason and don't know how to substitute the measurement of bitmap size.
Now provide the response and nothing else.
| I think we are in the same boat. My team stuck in this problem for a while like you. It seems be a problem in BitmapFactory.cpp ( https://android.googlesource.com/platform/frameworks/base.git/+/master/core/jni/android/graphics/BitmapFactory.cpp ) Some code was added in Android 7.0 and made the problem occurred. // Create the codec.NinePatchPeeker peeker;std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(streamDeleter.release(), &peeker));if (!codec.get()) { return nullObjectReturn("SkAndroidCodec::NewFromStream returned null");} And I found out the BitmapFactory.decodeStream method didn't create the bitmap after we set inJustDecodeBounds=false but when I try to create bitmap without bound decoding. It's works! The problem is about BitmapOptions in that InputStream doesn't updated when we called BitmapFactory.decodeStream again. So I reset that InputStream before decode again private Bitmap getBitmapFromAssets(Context context, String fileName, int width, int height) { AssetManager asset = context.getAssets(); InputStream is; try { is = asset.open(fileName); } catch (IOException e) { return null; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); try { is.reset(); } catch (IOException e) { return null; } options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(is, null, options);}public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize;} It's looks like we have to reset InputStream every time before reuse it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39316069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6792872/']} | jdg_79100 |
stackexchange | llm_judgeable_groundtruth_similarity | 27784283 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm totally new to couchbase. This is the sample code I use for insert and get documents: using (var bucket = Cluster.OpenBucket()){ var document = new Document<dynamic> { Id = "Hello", Content = new { name = "Couchbase" } }; var upsert = bucket.Upsert(document); if (upsert.Success) { var get = bucket.GetDocument<dynamic>(document.Id); document = get.Document; var msg = string.Format("{0} {1}!", document.Id, document.Content.name); Console.WriteLine(msg); } Console.Read();} But I have no idea how to retrieve a list of stored documents.
Now provide the response and nothing else.
| Until now, In Couchbase there are two different ways to query document content:using Views or using N1QL query language (named nickel and in developer preview 3 state right now). Views Couchbase Views creates indexes based on the content of JSON documents stored in the database and are written using MapReduce programming model. Couchbase uses MapReduce to process documents across the cluster and to create indexes based on their content.A view is a JavaScript function which is executed on every item in the dataset, does some initial processing and filtering, and then outputs the transformed result as a key-value set. The following image show you what is the structure view: For example, suppose that you have a bucket called test and you want to store documents with the following structure: public class User { [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("fname")] public string FirstName { get; set; } [JsonProperty("age")] public string Age { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("type")] public string Type { get; set; }} Now, suppose that you want to find all the users who are 25 years old and you want to know their name and email. Your view could be at this way: function(doc, meta) { if (doc.type == "user" && doc.age == 25) { emit(doc.user_id, [doc.fname, doc.email]); } } If you save this view as a Development View with Design Document Name = dev_user and View Name =userswith25, you could use this view in your code this way: var query = bucket.CreateQuery("dev_user", "userswith25");var result = bucket.Query<dynamic>(query); If you want to learn more about views, take a look this video: Views and Indexing for Couchbase 3.0 N1QL N1QL (pronounced “nickel”) is Couchbase’s next-generation query language. N1QL aims to meet the query needs of distributed document-oriented databases. A simple query in N1QL has three parts to it: SELECT - Parts of document to return FROM - The data bucket, or datastore to work with WHERE - Conditions the document must satisfy Only a SELECT clause is required in a query. The wildcard * selects all parts of the document. Queries can return a collection of different document structures or fragments. However, they will all match the conditions in the WHERE clause. As I said before, N1QL is in developer preview state, so isn't integrated with Couchbase yet. [EDIT: The .NET SDK N1QL integration no longer appears to be in alpha. ] To play with it you need to download it and integrate it with your Couchbase server. Following the previous view example, I show you a query to search users with the same conditions: var query = "SELECT fname, email FROM test WHERE type = 'user' and age = 25";var result = bucket.Query<dynamic>(query); Parallel to the development of N1QL, Coushbase is developing a Language Integrated Query (LINQ) provider for querying Couchbase Server with N1QL using the Couchbase .NET SDK. This will bring familiar LINQ syntax to N1QL and the results will be mapped to POCOs. Below I show an example of how you could use it in the future: using (var cluster = new Cluster()) { using (var bucket = cluster.OpenBucket("test")) { var users = from c in bucket.Queryable<User>() where c.Age==25 select c; foreach (var user in users) { Console.WriteLine("\tName={0}, Age={1}, Email={2}", user.FirstName, user.Age, user.Email ); } } } Also, there are other variants: Telerik has created a Linq Provider for Couchbase , I haven't used yet but I think is based in Couchbase .NET SDK 1.3, not in 2.0 which is the version you are using. You could integrate Couchbase with Elasticsearch to provide full-text search in your application using the open source search engine, Elasticsearch . With this combination you can save your documents in Couchbase and search them later using Elasticsearch. For that, you can use this elasticsearch .net client Hope this helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27784283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3530012/']} | jdg_79101 |
stackexchange | llm_judgeable_groundtruth_similarity | 2190786 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $n$ positive integer, $n\geqslant3$ and $a_1, a_2, ... , a_n, b_1, b_2, ..., b_n$ complex numbers such that $a_1\not=b_1$ and $|a_1|, |a_2|, .., |a_n|, |b_1|, |b_2|, ..., |b_n| \in (0, 1]$ . Show that $|a_1a_2...a_n-b_1b_2...b_n|=|a_1-b_1| + |a_2-b_2| +...+|a_n-b_n|$ if anf only if $a_k=b_k$ and $|a_k|=1$ ,where $k\geqslant2$. Again, problem from G.M. 11/2016. I can't solve it. I tried the case $n=3$ but that didnt work as well. I think that we can show that $|a_1a_2...a_n-b_1b_2...b_n|\leqslant|a_1-b_1|$ and the problem would be solved, but i don't know if it is correct or how to demonstrate it.
Now provide the response and nothing else.
| As a one-way implication with $n \not = 0$: $$(1+z)^n=z^n \implies \left|(1+z)^n\right|=\left|z^n\right|\implies \left|1+z\right|^n=\left|z\right|^n \implies \left|1+z\right|=\left|z\right| $$ and this is only true if $\Re(z)=-\frac12$, since you can rewrite it as $\left|z-(-1)\right|=\left|z-0\right|$ and take the perpendicular bisector on the Argand diagram | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2190786', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/408328/']} | jdg_79102 |
stackexchange | llm_judgeable_groundtruth_similarity | 18881872 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to bind a shortcut key to Edit > Tag > Wrap Selection with Tag . How do I figure out the command name so I can put that into the user key bindings?
Now provide the response and nothing else.
| Hit Ctrl ` (backtick) to open the console, then enter sublime.log_commands(True) to turn on command logging. Go through the menus and click your target, and command: insert_snippet {"name": "Packages/XML/long-tag.sublime-snippet"} comes up. Enter the following into your Preferences -> Key Bindings - User file: { "keys": ["ctrl+alt+shift+w"], "command": "insert_snippet", "args": { "name": "Packages/XML/long-tag.sublime-snippet" } } (changing the key combo if you wish) and you should be all set. Once you're done, go back to the console and enter sublime.log_commands(False) to turn off logging of every single action. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18881872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/685125/']} | jdg_79103 |
stackexchange | llm_judgeable_groundtruth_similarity | 112758 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that a regular grammar has a definition $$\begin{align}S &\to aS\\S &\to \lambda\end{align}$$ But I dont really know how to apply this information to check whether or not a grammar is regular... So for example I have a grammar $$\begin{align}S &\to aSbSb\\S &\to \lambda\end{align}$$ If I compare it to the definition of a regular grammar this is not a regular grammar right? Which also means that I can't turn this into a regex. Also could you please give me an example of a regular grammar and a non-regular grammar hopefully that will solidify my understanding.
Now provide the response and nothing else.
| It's important to distinguish between regular grammars and regular languages . Your first grammar is regular. A regular grammar is either a right-regular grammar or a left-regular grammar. In a right-regular grammar, every production's right-hand side has at most one non-terminal, and that non-terminal is the last symbol in the right-hand side. A left-regular grammar is the same except that all the non-terminals are at the beginning of their respective right-hand sides. As you observe, your second grammar is not a regular grammar, since there is a right-hand side with more than one non-terminal. A regular language is a language for which a regular grammar exists. That's a much trickier criterion, since the fact that a particular grammar is not regular does not in any way prove anything about the regularity of the language generated by that grammar. The language might or might not be regular, and there is no algorithm which will even tell you for sure. So your statement "Which also means that I can't turn this into a regex." does not follow. As it happens, your second grammar does not generate a regular language, but many non-regular grammars do recognise regular languages. Here's a simple example: $$\begin{align}S &\to aS\\S &\to Sb\\S &\to \lambda\end{align}$$ That grammar generates the language $a^*b^*$ , which is certainly a regular language. But this particular grammar is not regular because one production is left recursive and the other production is right recursive; in a regular grammar, either all productions with a non-terminal are left-regular, or all productions with a non-terminal are right-regular. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/112758', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/102263/']} | jdg_79104 |
stackexchange | llm_judgeable_groundtruth_similarity | 67335268 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please, I am having problem sending an ArrayList data to Activity . The data is an URL saved in ArrayList but after using bundle extras, I am getting null pointer exception. I also try to catch the exception but still the data i get using get extra string is null // below is the code i used to pass the dataBundle extras = new Bundle();extras.putString("VidUrl",VideoLecturesUrl.get(position));extras.putString("bookUrl",bookUrl.get(position)); extras.putString("VidTitle",titleList.get(position));Intent intent = new Intent(getActivity(),DetailsView.class);intent.putExtras(extras);startActivity(intent); // below is the receiving activity Intent intent = getIntent(); extras =intent.getExtras(); if (extras!=null){ try { Video_Url = extras.getString("VidUrl"); BookUrl = extras.getString("bookUrl"); Title = extras.getString("VidTitle"); Toast.makeText(this,Video_Url,Toast.LENGTH_SHORT).show(); Toast.makeText(this,BookUrl,Toast.LENGTH_SHORT).show(); Toast.makeText(this,Title,Toast.LENGTH_SHORT).show(); videotexTitle.setText(Title); setTitle(Title); setVideo(Video_Url.toString()); }catch (Exception e){ e.printStackTrace(); } } else { Toast.makeText(this, "the extrass is empty", Toast.LENGTH_SHORT).show(); }
Now provide the response and nothing else.
| But I cannot tell any difference between v | std::views::drop(2) and std::views::all(v) | std::views::drop(2) . Indeed, there is no difference between the two - because v | views::drop(2) already means views::all(v) | views::drop(2) . views::all is an implementation detail of Ranges to ensure that range adaptors always adapt views (not ranges). All that views::all(v) does is ensure that the result is a View, which is to say (from [range.all] ): Given a subexpression E , the expression views::all(E) is expression-equivalent to: decay-copy(E) if the decayed type of E models view . Otherwise, ref_view{E} if that expression is well-formed. Otherwise, subrange{E} . In your case, v is a vector<int> , which does not model view . But it is an lvalue, so ref_view{v} would be well-formed, so that's what happens. All the adaptors use views::all internally. For instance, drop_view has the following deduction guide: template <class R>drop_view(R&&, range_difference_t<R>) -> drop_view<views::all_t<R>>; So if you wrote drop_view(v, 2) (and you should never use meow_view directly, always use views::meow ), that would itself invoke views::all for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67335268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14856185/']} | jdg_79105 |
stackexchange | llm_judgeable_groundtruth_similarity | 9313 |
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I come from a different field (Machine learning/AI/data science), but aim to ask a philosophical question with the utmost respect:Why do quantitative financial analysts (analysts/traders/etc.) prefer (or at least seem) traditional statistical methods (traditional = frequentist/regression/normal correlation methods/ts analysis) over newer AI/machine learning methods? I've read a million models, but it seems biased?Background: I recently joined a 1B AUM (I know it's not a ton) asset management firm. I was asked to build a new model for a sector rotation strategy (basically predicting which SP 500 sector would do the best over 6 months-- chose to use forward rolling 6 month returns) they employ and my first inclination was to combine ARIMA (traditional) with random forest (feature selection) and a categorical (based on normal distribution standard deviation) gradient boosted classifier for ETFs in each sector. Not to be rude, but I beat the ValuLine timeliness for each sector. I used the above mentioned returns as my indicator and pretty much threw everthing at the wall for predictors initially (basically just combing FRED), then used randomForest to select features. I ended up combining EMA and percent change to create a pretty solid model that, like I said, beat ValuLine. I've read a lot of literature, and I haven't seen anyone do anything like this. Any help in terms of pointing me in the right direction for literature? Or any answers to the overarching idea of why isn't there more machine learning in equity markets (forgetting social/news analysis)?EDIT: For clarification, I'm really interested in long-term predictions (I think Shiller was right) based on macro predictors. Thanks PS- I've been lurking for a while. Thanks for all the awesome questions, answers, and discussions.
Now provide the response and nothing else.
| Because of: The (extreme) dominance of noise over signal The prevalence of non-repeating patterns (many of which we know are not going to repeat) A pathetic sample size for cross-validation Regime changes due to exogenous events. These are typically in the cross-val window which makes it even worse. (GFC, financial integration, trade law changes, interest rate adjustments by central banks, some idiot in a bank was hiding trades and loses 5 billions dollars, etc). It is well known that non-linear relationships are generally just artefacts of the in sample dataset There is also the following: Much price changes are driven by news such as a plane crashing or a merger announcement. Are you trying to forecast news (!?) by getting your model to learn non-linear relationships on price data? It should be clear that, if American Airlines price falls due to a terrorist hijacking, it is not going to be useful to have a random forest learn any patterns that result since it will not repeat. Because of these factors many (econometricians and practicioners) will try to use a priori knowledge to select features and impose constraints on the model in an attempt to improve generalization. This is perceived as necessary by econometricians since the data is too thin, noisy and nonstationary (i.e., the above reasons). This is not to say that "machine learning" methods such as Lasso, NNG, Elastic Nets or Ridge can't be applied. They result in essentially linear models and you can impose whatever a priori constraints on it through the metaparameters in the loss function or by using a variant that preserves hierarchies when using indicator function interactions (Tibshirani 2013...). Edit: You will still need to select which features go into the algorithm (as a prior imposition) but you can use these to achieve slightly more sparsity than you would otherwise have and introduce some bias into your conditional expectation (or state probability if you're doing multinomial categorical GLM) for improvement in variance of sampling distribution. I am however open to random forests with the right a priori constraints in place. There are indeed hundreds of papers that use machine learning to forecast financial markets. Just google something silly like "fuzzy bayesian expert adaptive learners with PSO training S&P 500" and you will get a lesson in the file-drawer effect, publication bias and substandard research methodologies (e.g. selecting 3 of 50 algorithms and 2 of 50 indices and hoping it convinces people). However, the above is an optimist's view of the industry. From those I've spoken to at low frequency funds they are simply ignorant of machine learning and couldn't apply it because they lack the knowledge and skills. If they were actually interested in being true quants, who knows how much damage they could do with deep learning or something. If you want to do real machine learning in finance and actually do something that is meritocratic/skill/scientific instead of almost completely random and full of people who practice nonsense, go to a HFT firm (not that most people practice non-sense in low frequency funds, just that many do and this is something that is absolutely impossible to get away with in HFT). That said, I am continually and consistently underwhelmed when I hear of the research methods of low frequency quant funds. | {} | {'log_upvote_score': 7, 'links': ['https://quant.stackexchange.com/questions/9313', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/6399/']} | jdg_79106 |
stackexchange | llm_judgeable_groundtruth_similarity | 61156894 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Have tensor like : x.shape = [3, 2, 2] . import torchx = torch.tensor([ [[-0.3000, -0.2926],[-0.2705, -0.2632]], [[-0.1821, -0.1747],[-0.1526, -0.1453]], [[-0.0642, -0.0568],[-0.0347, -0.0274]]]) I need to take .max() over the 2nd and 3rd dimensions. I expect some like this [-0.2632, -0.1453, -0.0274] as output. I tried to use: x.max(dim=(1,2)) , but this causes an error.
Now provide the response and nothing else.
| Now, you can do this. The PR was merged (Aug 28 2020) and it is now available in the nightly release. Simply use torch.amax() : import torchx = torch.tensor([ [[-0.3000, -0.2926],[-0.2705, -0.2632]], [[-0.1821, -0.1747],[-0.1526, -0.1453]], [[-0.0642, -0.0568],[-0.0347, -0.0274]]])print(torch.amax(x, dim=(1, 2)))# Output:# >>> tensor([-0.2632, -0.1453, -0.0274]) Original Answer As of today (April 11, 2020), there is no way to do .min() or .max() over multiple dimensions in PyTorch. There is an open issue about it that you can follow and see if it ever gets implemented. A workaround in your case would be: import torchx = torch.tensor([ [[-0.3000, -0.2926],[-0.2705, -0.2632]], [[-0.1821, -0.1747],[-0.1526, -0.1453]], [[-0.0642, -0.0568],[-0.0347, -0.0274]]])print(x.view(x.size(0), -1).max(dim=-1))# output:# >>> values=tensor([-0.2632, -0.1453, -0.0274]),# >>> indices=tensor([3, 3, 3])) So, if you need only the values: x.view(x.size(0), -1).max(dim=-1).values . If x is not a contiguous tensor, then .view() will fail. In this case, you should use .reshape() instead. Update August 26, 2020 This feature is being implemented in PR#43092 and the functions will be called amin and amax . They will return only the values. This is probably being merged soon, so you might be able to access these functions on the nightly build by the time you're reading this :) Have fun. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61156894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13253265/']} | jdg_79107 |
stackexchange | llm_judgeable_groundtruth_similarity | 4916918 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I execute a Java System (shell) command that has a space in the pathname? I've tried putting quotes and a backslash (), But it does not work. ln -s "dir1/dir2" "my\ dir/dir2"
Now provide the response and nothing else.
| By far the most reliable way is to use Runtime.exec(String[] cmdarray) . If you use Runtime.exec(String command) , Java only splits the command on whitespace. the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order. See also g++: File not found Or use ProcessBuilder something like this: ProcessBuilder pb = new ProcessBuilder("ln", "-s", "dir1/dir2", "my dir/dir2");Process p = pb.start(); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4916918', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603732/']} | jdg_79108 |
stackexchange | llm_judgeable_groundtruth_similarity | 8726268 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the session id of my application. now i want to get all the session variables by using this session id. I used <?php echo session_id()?> to get the session id but how to get all the session object values by using this session id?
Now provide the response and nothing else.
| According to php.net : There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site's referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users. This begs the question, how do you have the session ID but unable to access the script? Regardless, you would need to set the session ID and then start it...then access the data. session_id($whatever_id_you_have);session_start();echo $_SESSION['somekey']; | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8726268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1029506/']} | jdg_79109 |
stackexchange | llm_judgeable_groundtruth_similarity | 22772379 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am developing an application with several TextField objects that need to be updated to reflect changes in associated back-end properties. The TextField s are not editable, only the back-end may change their content. As I understand, the correct way about this is to run the heavy computation on a separate thread so as not to block the UI. I did this using javafx.concurrent.Task and communicated a single value back to the JavaFX thread using updateMessage() , which worked well. However, I need more than one value to be updated as the back-end does its crunching. Since the back-end values are stored as JavaFX properties, I tried simply binding them to the textProperty of each GUI element and let the bindings do the work. This doesn't work, however; after running for a few moments, the TextField s stop updating even though the back-end task is still running. No exceptions are raised. I also tried using Platform.runLater() to actively update the TextField s rather than binding. The issue here is that the runLater() tasks are scheduled faster than the platform can run them, and so the GUI becomes sluggish and needs to time to "catch up" even after the back-end task is finished. I found a few questions on here: Logger entries translated to the UI stops being updated with time Multithreading in JavaFX hangs the UI but my issue persists. In summary: I have a back-end making changes to properties, and I want those changes to appear on the GUI. The back-end is a genetic algorithm, so its operation is broken down into discrete generations. What I would like is for the TextField s to refresh at least once in between generations, even if this delays the next generation. It is more important that the GUI responds well than that the GA runs fast. I can post a few code examples if I haven't made the issue clear. UPDATE I managed to do it following James_D's suggestion. To solve the issue of the back-end having to wait for the console to print, I implemented a buffered console of sorts. It stores the strings to print in a StringBuffer and actually appends them to the TextArea when a flush() method is called. I used an AtomicBoolean to prevent the next generation from happening until the flush is complete, as it is done by a Platform.runLater() runnable. Also note that this solution is incredibly slow.
Now provide the response and nothing else.
| Not sure if I completely understand, but I think this may help. Using Platform.runLater(...) is an appropriate approach for this. The trick to avoiding flooding the FX Application Thread is to use an Atomic variable to store the value you're interested in. In the Platform.runLater method, retrieve it and set it to a sentinel value. From your background thread, update the Atomic variable, but only issue a new Platform.runLater if it's been set back to its sentinel value. I figured this out by looking at the source code for Task . Have a look at how the updateMessage method (line 1131 at the time of writing) is implemented. Here's an example which uses the same technique. This just has a (busy) background thread which counts as fast as it can, updating an IntegerProperty . An observer watches that property and updates an AtomicInteger with the new value. If the current value of the AtomicInteger is -1, it schedules a Platform.runLater . In the Platform.runLater , I retrieve the value of the AtomicInteger and use it to update a Label , setting the value back to -1 in the process. This signals that I am ready for another UI update. import java.text.NumberFormat;import java.util.concurrent.atomic.AtomicInteger;import javafx.application.Application;import javafx.application.Platform;import javafx.beans.property.IntegerProperty;import javafx.beans.property.SimpleIntegerProperty;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.layout.AnchorPane;import javafx.stage.Stage;public class ConcurrentModel extends Application { @Override public void start(Stage primaryStage) { final AtomicInteger count = new AtomicInteger(-1); final AnchorPane root = new AnchorPane(); final Label label = new Label(); final Model model = new Model(); final NumberFormat formatter = NumberFormat.getIntegerInstance(); formatter.setGroupingUsed(true); model.intProperty().addListener(new ChangeListener<Number>() { @Override public void changed(final ObservableValue<? extends Number> observable, final Number oldValue, final Number newValue) { if (count.getAndSet(newValue.intValue()) == -1) { Platform.runLater(new Runnable() { @Override public void run() { long value = count.getAndSet(-1); label.setText(formatter.format(value)); } }); } } }); final Button startButton = new Button("Start"); startButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { model.start(); } }); AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setBottomAnchor(startButton, 10.0); AnchorPane.setLeftAnchor(startButton, 10.0); root.getChildren().addAll(label, startButton); Scene scene = new Scene(root, 100, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } public class Model extends Thread { private IntegerProperty intProperty; public Model() { intProperty = new SimpleIntegerProperty(this, "int", 0); setDaemon(true); } public int getInt() { return intProperty.get(); } public IntegerProperty intProperty() { return intProperty; } @Override public void run() { while (true) { intProperty.set(intProperty.get() + 1); } } }} If you really want to "drive" the back end from the UI: that is throttle the speed of the backend implementation so you see all updates, consider using an AnimationTimer . An AnimationTimer has a handle(...) which is called once per frame render. So you could block the back-end implementation (for example by using a blocking queue) and release it once per invocation of the handle method. The handle(...) method is invoked on the FX Application Thread. The handle(...) method takes a parameter which is a timestamp (in nanoseconds), so you can use that to slow the updates further, if once per frame is too fast. For example: import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import javafx.animation.AnimationTimer;import javafx.application.Application;import javafx.beans.property.LongProperty;import javafx.beans.property.SimpleLongProperty;import javafx.geometry.Insets;import javafx.geometry.Pos;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.layout.BorderPane;import javafx.scene.layout.HBox;public class Main extends Application { @Override public void start(Stage primaryStage) { final BlockingQueue<String> messageQueue = new ArrayBlockingQueue<>(1); TextArea console = new TextArea(); Button startButton = new Button("Start"); startButton.setOnAction(event -> { MessageProducer producer = new MessageProducer(messageQueue); Thread t = new Thread(producer); t.setDaemon(true); t.start(); }); final LongProperty lastUpdate = new SimpleLongProperty(); final long minUpdateInterval = 0 ; // nanoseconds. Set to higher number to slow output. AnimationTimer timer = new AnimationTimer() { @Override public void handle(long now) { if (now - lastUpdate.get() > minUpdateInterval) { final String message = messageQueue.poll(); if (message != null) { console.appendText("\n" + message); } lastUpdate.set(now); } } }; timer.start(); HBox controls = new HBox(5, startButton); controls.setPadding(new Insets(10)); controls.setAlignment(Pos.CENTER); BorderPane root = new BorderPane(console, null, null, controls, null); Scene scene = new Scene(root,600,400); primaryStage.setScene(scene); primaryStage.show(); } private static class MessageProducer implements Runnable { private final BlockingQueue<String> messageQueue ; public MessageProducer(BlockingQueue<String> messageQueue) { this.messageQueue = messageQueue ; } @Override public void run() { long messageCount = 0 ; try { while (true) { final String message = "Message " + (++messageCount); messageQueue.put(message); } } catch (InterruptedException exc) { System.out.println("Message producer interrupted: exiting."); } } } public static void main(String[] args) { launch(args); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22772379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3482616/']} | jdg_79110 |
stackexchange | llm_judgeable_groundtruth_similarity | 19324508 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
if I am defining two beans of same class and not giving any scope. Then how many instance of class will get created. for example in applicationContext.xml <bean name="testBean" class="com.test.Example"/><bean name="myBean" class="com.test.Example"/>
Now provide the response and nothing else.
| Spring will create two beans of the type com.test.Example and the autowiring will be for the type or method name (or Qualifiers), see Spring IOC See this simple test: With this class public static class TestBean { static int INT = 1; public int test; public TestBean() { test = INT++; }} Configuration xml: <bean name="testBean" class="com.test.TestBean"/><bean name="myBean" class="com.test.TestBean"/> JUnit4 with spring container test: @ResourceTestBean testBean;@ResourceTestBean myBean;@Testpublic void test() { assertNotNull(testBean); assertNotNull(myBean); assertFalse(testBean == myBean); assertFalse(testBean.test == myBean.test);} This test dont fail, as you see, two beans of type TestBean are created. See this part in the Spring Doc: byName Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property. byType Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set. constructor Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19324508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2100510/']} | jdg_79111 |
stackexchange | llm_judgeable_groundtruth_similarity | 2749406 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Do you have any suggestions with my problem. I need to use get and post at the same time.Get because I need to output what the user has typed. And post because I need to access the mysql database in relation to that input.It looks something like this: <form name="x" method="get" action="x.php"><input name="year" type="text"><select name="general" id="general"> <font size="3"> <option value="YEAR">Year</option></form> This will output the contents of mysql depending on what the user will check: <form name="y" method="post" action"y.php"><input name="fname" type="checkbox"></form> And the form action of those two combined will look something like this: <?php if($_POST['general'] == 'YEAR'){ ?> <?php echo $_GET["year"]; ?> <?php $result2 = mysql_query("SELECT * FROM student WHERE student.YEAR='$syear'"); ?> <table border='1'> <tr> <?php if ( $ShowLastName ) { ?><th>LASTNAME</th><?php } ?> <?php if ( $ShowFirstName ) { ?><th>FIRSTNAME</th><?php } ?> </tr> <?php while ( $row = mysql_fetch_array($result2) ) { if (!$result2) { } ?> <tr> <td><?php echo $row['IDNO']?> </td> <td><?php echo $row['YEAR'] ?> </td> <?php if ( $ShowLastName ) { echo('<td>'.$row['LASTNAME'].'</td>'); } ?></td> <?php if ( $ShowFirstName ) { echo('<td>'.$row['FIRSTNAME'].'</td>'); } ?> I really get lots of undefined errors when I do this. What can you recommend that I should do in order to get the value inputted by the user together with the mysql data.
Now provide the response and nothing else.
| You can only have one verb (POST, GET, PUT, ...) when doing an HTTP Request . However, you can do <form name="y" method="post" action="y.php?foo=bar"> and then PHP will populate $_GET['foo'] as well, although the sent Request was POST'ed. However, your problem seems to be much more that you are trying to send two forms at once , directed at two different scripts. That is impossible within one Request. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2749406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225269/']} | jdg_79112 |
stackexchange | llm_judgeable_groundtruth_similarity | 47409678 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a function to call my Web API. It works well if TestCallingRemotely is set to [AllowAnonymous] . var httpWebRequest = (HttpWebRequest)WebRequest.Create( "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");httpWebRequest.ContentType = "application/json";httpWebRequest.Method = "POST";using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string input = "{}"; streamWriter.Write(input); streamWriter.Flush(); streamWriter.Close();}var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); How do I pass the username and password to the HttpWebRequest for authorization? I need to call my Web API from CLR integration, which only supports System.Net .
Now provide the response and nothing else.
| ABP's startup template uses bearer token authentication infrastructure . var token = GetToken(username, password);// var httpWebRequest = (HttpWebRequest)WebRequest.Create(// "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");// httpWebRequest.ContentType = "application/json";// httpWebRequest.Method = "POST";httpWebRequest.Headers.Add("Authorization", "Bearer " + token);// ... Get token This uses a crude way to extract the token, inspired by an MSDN article . private string GetToken(string username, string password, string tenancyName = null){ var httpWebRequest = (HttpWebRequest)WebRequest.Create( "http://localhost:6334/api/Account/Authenticate"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { var input = "{\"usernameOrEmailAddress\":\"" + username + "\"," + "\"password\":\"" + password + "\"}"; if (tenancyName != null) { input = input.TrimEnd('}') + "," + "\"tenancyName\":\"" + tenancyName + "\"}"; } streamWriter.Write(input); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); string response; using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { response = streamReader.ReadToEnd(); } // Crude way var entries = response.TrimStart('{').TrimEnd('}').Replace("\"", String.Empty).Split(','); foreach (var entry in entries) { if (entry.Split(':')[0] == "result") { return entry.Split(':')[1]; } } return null;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47409678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5676412/']} | jdg_79113 |
stackexchange | llm_judgeable_groundtruth_similarity | 22881395 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on a submission form that includes a few required fields, and I have a segment of code that allows a popup menu to appear once you hit the "submit" button, and from there once you hit "ok" on the alert you're redirected to the home page. Here's the code I have for the popup alert. <div id="popup"> <button onclick="myFunction()">Submit</button> <script> function myFunction(){ alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \n You will now be taken to the Home page.");} </script> <input type="reset" value="Reset" /></div> And this is the beginning of the code for redirecting you to the homepage. <div id="all"> <div id="text"> <h1>Your Information</h1> <form id="contact_form" action="home.html" method="post"> <input type="hidden" name="redirect" value="home.html" /> (Note: I clipped the above segment of code because the following information is only the form input boxes) And this works like you would imagine, the alert popping up once you hit the submit button. However my question is that I have a few required fields on my form, and if the fields are not filled out and you hit "submit", the popup alert appears, and once you hit "ok" on the alert, because you have yet to fill out these fields it takes you back to the form and a little box saying "this field is required" appears. This is in the wrong order. I want the alert box for the required fields to show before the popup alert for the confirmation of form submission, so that if you have required fields and you hit submit it will tell you to fill out the required fields before the message appears thanking you for submitting. This may be a simple fix of placement or adding a little code but I'm having a hard time figuring out how to do it or finding an example that could help me. If you know what to do I'd really appreciate it, thanks! Edit: This is the javascript file for the validation code. window.onload = setForm;function setForm() { document.forms[0].onsubmit = function() { if (this.checkValidity()) alert("No invalid data detected. Will retain data for further testing."); return false; }}
Now provide the response and nothing else.
| You need to tell angular that you updated the var: function TestCtrl($scope) { $scope.loading = true; setTimeout(function () { $scope.$apply(function(){ $scope.loading = false; }); }, 1000);} or just function TestCtrl($scope, $timeout) { $scope.loading = true; $timeout(function () { $scope.loading = false; }, 1000);} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22881395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2797027/']} | jdg_79114 |
stackexchange | llm_judgeable_groundtruth_similarity | 15289250 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 4 processors and am compiling a processor-hungry application. I read that using make with the -j4 switch was recommended for OpenCV; should I instead use -j8 ? What is the advantage of making for multiple processors?
Now provide the response and nothing else.
| As you say the -j flag tells make that it is allowed to spawn the provided amount of 'threads'. Ideally each thread is executed on its own core/CPU, so your multi-core/CPU environment is used to its fullest. make itself does not compile the source files. This is done by a compiler (gcc). The Makefile (input for make ) contains a set of targets. Each target has a set of dependencies (on other targets) and rules how to build the target. make reads the Makefile(s) and manages all targets, dependencies, and build rules. Besides compiling source files you can use make to perform any task that can be described by shell commands. If you set the allowed number of threads too high, it is not possible to schedule each thread on its own core. Additional scheduling (context) switches are required to let all threads execute. This additional resource usage obviously result in lower performance. There are multiple rules-of-thumb, but I guess that setting to total amount to <number of cores> + 1 is the most common. The idea behind this is that all cores have their own thread and there is one additional managing thread that handles the targets and which is next to be built. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15289250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_79115 |
stackexchange | llm_judgeable_groundtruth_similarity | 148049 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem: In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes. I have several ideas for solving this problem: Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up. Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes. Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test. But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem. What is the best strategy to keep classes that use these static helpers testable?
Now provide the response and nothing else.
| (No "official" sources here, I'm afraid - it's not like there's a specification for how to test well. Just my opinions, which will hopefully be useful.) When these static methods represent genuine dependencies, create wrappers. So for things like: ImageIO HTTP clients (or anything else network-related) The file system Getting the current time (my favourite example of where dependency injection helps) ... it makes sense to create an interface. But many of the methods in Apache Commons probably shouldn't be mocked/faked. For example, take a method to join together a list of strings, adding a comma between them. There's no point in mocking these - just let the static call do its normal work. You don't want or need to replace the normal behaviour; you're not dealing with an external resource or something that's hard to work with, it's just data. The result is predictable and you'd never want it to be anything other than what it'll give you anyway. I suspect that having removed all the static calls which really are convenience methods with predictable, "pure" outcomes (like base64 or URL encoding) rather than entry points into a whole big mess of logical dependencies (like HTTP) you'll find it's entirely practical to do the right thing with the genuine dependencies. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/148049', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/55877/']} | jdg_79116 |
stackexchange | llm_judgeable_groundtruth_similarity | 214275 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading a tutorial on marginal densities when I came across this example (rephrased). A person is crossing the street and we want to compute the probability when he gets hit by a passing car depending on the color of the traffic light. Let H be whether the person gets hit or not, and L be the color of the traffic light. So $H = \{\text{hit, not hit} \}$ and $L = \{\text{red, yellow, green} \}$. The probability of getting hit given that the light is red can be written as: $P(H = \text{hit}| L = \text{red})$. Clearly this is a conditional probability. The probability of getting hit regardless of whatever the light is can be written as: $P(H = \text{hit})$. This is marginal, as I recently understood. How can you say: $P(H,L)$. This is a joint probability. How do you translate it to a 'layman's sentence? How is it different from "The probability of getting hit AND the light is red"? Thanks for your insights.
Now provide the response and nothing else.
| You actually had your answer right there. $P(H=hit)$ is the marginal probability. It reads "The probability of getting hit.". It is the proportion of people that got hit crossing the street, irrespective of traffic light. $P(H=hit|L=red)$ is the conditional probability. It reads "The probability that you get hit, given that the light is red". It is the proportion of hits among the people that cross the street in red light. Finally, $P(H=hit, L=red)$ is the joint probability. It reads "the probability that a person gets hit by a car and that the light is red". It is the proportion of hits in red light among all people. You certainly know the relationship $P(H=hit, L=red) = P(H=hit | L=red) * P(L=red)$ In "layman's parlance", we can look at it as follows. Assume that the probability of having a red light is extremely small, but that people always get hit when crossing in red light. Let us assume you are an observer at the side of the street. You will see people getting hit, and rarely will you see the light turning red. Out of all people that cross the street, the chance they will get hit in red light is very tiny, since they almost never have that opportunity ($P(H=hit,L=red)$ is small because a red light is rare). However, if you observe long enough, you will eventually see people getting hit in red light, and notice that whenever the light is red, people crossing the street will get hit for sure ($P(H=hit|L=red)=1$). | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/214275', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/67413/']} | jdg_79117 |
stackexchange | llm_judgeable_groundtruth_similarity | 13493825 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the reactive extensions for a kind of a in process message bus.The implementation is quite simple. Register looks like public IDisposable Register<T>(Action<T> action) where T : IMessage{ return this.subject .OfType<T>() .Subscribe(action);} And send simply: private void SendMessage(IMessage message) { this.subject.OnNext(message); } However i'm now having some trouble with the exception behaviour of RX.One an exception is thrown in a registered/subscribed action - the Observable 'stream' is broken and will not subscribe anymore.Sine this message bus is used for two parts of the application to communicate i need to ensure that such a stream is never broken even if an unexpected exception is thrown.
Now provide the response and nothing else.
| If you need to ensure that the stream is never broken by an exception, then you need to have another channel for the exceptions. This behavior is not completely unexpected. From the documentation for the IObserver<T> interface : The OnError method, which is typically called by the provider to indicate that data is unavailable, inaccessible, or corrupted, or that the provider has experienced some other error condition. Given this, if the stream is unavailable, corrupted, etc, you definitely want the stream to be "faulted" (this is analagous to a channel being faulted in WCF); the state is indeterminate so you can't rely on anything else that comes from the IObservable<T> implementation; so why should there be an expectation that there will be any more observations? That said, you have a some options: Swallow the exception You'd have to wrap the action delegate that you pass into your Register function, like so: public IDisposable Register<T>(Action<T> action) where T : IMessage{ return this.subject .OfType<T>() .Subscribe(t => { // Execute action try { action(t); } catch { } });} This, of course, might not be desirable, as you might be throwing away exceptions which impact your program (or, you might know exactly what's going on here, and want to skip them), but it can be used to build on the next solution. Provide an action to take when an exception is thrown Using the above as the base, you can ask for an Action<T, Exception> which will be called when an exception is thrown. public IDisposable Register<T>(Action<T> action, Action<T, Exception> errorHandler) where T : IMessage{ return this.subject .OfType<T>() .Subscribe(t => { // Execute action try { action(t); } catch (Exception e) { errorHandler(t, e); } });} Now, when an exception is thrown from action , it will be passed to your exception handler without breaking the stream. The above can easily be overloaded to provide the behavior which will swallow the exception (which again, may or may not serve your purposes): public IDisposable Register<T>(Action<T> action) where T : IMessage{ // Call the overload, don't do anything on // exception. return Register(action, (t, e) => { });} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13493825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1019514/']} | jdg_79118 |
stackexchange | llm_judgeable_groundtruth_similarity | 25989610 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I implement keyboard shortcuts (to run a function) in PyQt5? I see I'm supposed QAction in one way or another, but I can't put the two and two together, and all examples don't seem to work with PyQt5 but instead PyQt4.
Now provide the response and nothing else.
| Use QShortcut and QKeySequence classes like this: import sysfrom PyQt5.QtCore import pyqtSlotfrom PyQt5.QtGui import QKeySequencefrom PyQt5.QtWidgets import QWidget, QShortcut, QLabel, QApplication, QHBoxLayoutclass Window(QWidget): def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) self.label = QLabel("Try Ctrl+O", self) self.shortcut = QShortcut(QKeySequence("Ctrl+O"), self) self.shortcut.activated.connect(self.on_open) self.layout = QHBoxLayout() self.layout.addWidget(self.label) self.setLayout(self.layout) self.resize(150, 100) self.show() @pyqtSlot() def on_open(self): print("Opening!")app = QApplication(sys.argv)win = Window()sys.exit(app.exec_()) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25989610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3991859/']} | jdg_79119 |
stackexchange | llm_judgeable_groundtruth_similarity | 13332268 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use subprocess.check_output() with ps -A | grep 'process_name' .I tried various solutions but so far nothing worked. Can someone guide me how to do it?
Now provide the response and nothing else.
| To use a pipe with the subprocess module, you have to pass shell=True . However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so: ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)ps.wait() In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/13332268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1771868/']} | jdg_79120 |
stackexchange | llm_judgeable_groundtruth_similarity | 8147027 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this code that doesn't work, but I think the intent is clear: testmakeshared.cpp #include <memory>class A { public: static ::std::shared_ptr<A> create() { return ::std::make_shared<A>(); } protected: A() {} A(const A &) = delete; const A &operator =(const A &) = delete;};::std::shared_ptr<A> foo(){ return A::create();} But I get this error when I compile it: g++ -std=c++0x -march=native -mtune=native -O3 -Wall testmakeshared.cppIn file included from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:52:0, from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/memory:86, from testmakeshared.cpp:1:testmakeshared.cpp: In constructor ‘std::_Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp>::_Sp_counted_ptr_inplace(_Alloc) [with _Tp = A, _Alloc = std::allocator<A>, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’:/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:518:8: instantiated from ‘std::__shared_count<_Lp>::__shared_count(std::_Sp_make_shared_tag, _Tp*, const _Alloc&, _Args&& ...) [with _Tp = A, _Alloc = std::allocator<A>, _Args = {}, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:986:35: instantiated from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_make_shared_tag, const _Alloc&, _Args&& ...) [with _Alloc = std::allocator<A>, _Args = {}, _Tp = A, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:313:64: instantiated from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_make_shared_tag, const _Alloc&, _Args&& ...) [with _Alloc = std::allocator<A>, _Args = {}, _Tp = A]’/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:531:39: instantiated from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = A, _Alloc = std::allocator<A>, _Args = {}]’/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:547:42: instantiated from ‘std::shared_ptr<_Tp1> std::make_shared(_Args&& ...) [with _Tp = A, _Args = {}]’testmakeshared.cpp:6:40: instantiated from heretestmakeshared.cpp:10:8: error: ‘A::A()’ is protected/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:400:2: error: within this contextCompilation exited abnormally with code 1 at Tue Nov 15 07:32:58 This message is basically saying that some random method way down in the template instantiation stack from ::std::make_shared can't access the constructor because it's protected. But I really want to use both ::std::make_shared and prevent anybody from making an object of this class that isn't pointed at by a ::std::shared_ptr . Is there any way to accomplish this?
Now provide the response and nothing else.
| This answer is probably better, and the one I'll likely accept. But I also came up with a method that's uglier, but does still let everything still be inline and doesn't require a derived class: #include <memory>#include <string>class A { protected: struct this_is_private; public: explicit A(const this_is_private &) {} A(const this_is_private &, ::std::string, int) {} template <typename... T> static ::std::shared_ptr<A> create(T &&...args) { return ::std::make_shared<A>(this_is_private{0}, ::std::forward<T>(args)...); } protected: struct this_is_private { explicit this_is_private(int) {} }; A(const A &) = delete; const A &operator =(const A &) = delete;};::std::shared_ptr<A> foo(){ return A::create();}::std::shared_ptr<A> bar(){ return A::create("George", 5);}::std::shared_ptr<A> errors(){ ::std::shared_ptr<A> retval; // Each of these assignments to retval properly generates errors. retval = A::create("George"); retval = new A(A::this_is_private{0}); return ::std::move(retval);} Edit 2017-01-06: I changed this to make it clear that this idea is clearly and simply extensible to constructors that take arguments because other people were providing answers along those lines and seemed confused about this. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8147027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/167958/']} | jdg_79121 |
stackexchange | llm_judgeable_groundtruth_similarity | 1407076 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to use a RequestDispatcher to send parameters from a servlet. Here is my servlet code: protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String station = request.getParameter("station"); String insDate = request.getParameter("insDate"); //test line String test = "/response2.jsp?myStation=5"; RequestDispatcher rd; if (station.isEmpty()) { rd = getServletContext().getRequestDispatcher("/response1.jsp"); } else { rd = getServletContext().getRequestDispatcher(test); } rd.forward(request, response);} Here is my jsp, with the code to read the value - however it shows null. <h1>response 2</h1> <p> <%=request.getAttribute("myStation") %> </p> Thanks for any suggestions.Greener
Now provide the response and nothing else.
| In your servlet use request.setAttribute in the following manner request.setAttribute("myStation", value); where value happens to be the object you want to read later. and extract it later in a different servlet/jsp using request.getAttribute as String value = (String)request.getAttribute("myStation") or <%= request.getAttribute("myStation")%> Do note that the scope of usage of get/setAttribute is limited in nature - attributes are reset between requests. If you intend to store values for longer, you should use the session or application context, or better a database. Attributes are different from parameters, in that the client never sets attributes. Attributes are more or less used by developers to transfer state from one servlet/JSP to another. So you should use getParameter (there is no setParameter) to extract data from a request, set attributes if needed using setAttribute, forward the request internally using RequestDispatcher and extract the attributes using getAttribute. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1407076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85682/']} | jdg_79122 |
stackexchange | llm_judgeable_groundtruth_similarity | 20982914 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to both NAudio and C# and I managed to create a simple MP3 player where you can choose a file and play it. It also has a play/pause button. I would now like to add a seek bar but have no clue on how to do this. Also is it possible to have seekbar in waveform style? The openButton click Handler private void openButton_Click(object sender, EventArgs e){ OpenFileDialog open = new OpenFileDialog(); open.Filter = "Audio File|*.mp3;"; if (open.ShowDialog() != DialogResult.OK) return; CloseWaveOut(); // disposes the waveOutDevice and audiofilereader waveOutDevice = new WaveOut(); audioFileReader = new AudioFileReader(open.FileName); waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); pauseButton.Enabled = true; }
Now provide the response and nothing else.
| Apart from the purely UI-based concerns, there are three basic things you need to be able to do: Read song length. Get playback position. Set playback position. Song length and current playback position are simple enough - they are available via the TotalTime and CurrentTime properties of the WaveStream object, which means your audioFileReader object supports them too. Once constructed, audioFileReader.TotalTime will give you a TimeSpan object with the total length of the file, and audioFileReader.CurrentTime will give you the current playback position. You can also set the playback position by assigning to audioFileReader.CurrentTime ... but doing so is a tricky process unless you know what you're doing. The following code to skip ahead 2.5 seconds works sometimes and crashes horribly at others: audioFileReader.CurrentTime = audioFileReader.CurrentTime.Add(TimeSpan.FromSeconds(2.5)); The problem here is that the resultant stream position (in bytes) may not be correctly aligned to the start of a sample, for several reasons (including floating point math done in the background). This can quickly turn your output to garbage. The better option is to use the Position property of the stream when you want to change playback position. Position is the currently playback position in bytes, so is a tiny bit harder to work on. Not too much though: audioFileReader.Position += audioFileReader.WaveFormat.AverageBytesPerSecond; If you're stepping forward or backwards an integer number of seconds, that's fine. If not, you need to make sure that you are always positioning at a sample boundary, using the WaveFormat.BlockAlign property to figure out where those boundaries are. // Calculate new positionlong newPos = audioFileReader.Position + (long)(audioFileReader.WaveFormat.AverageBytesPerSecond * 2.5);// Force it to align to a block boundaryif ((newPos % audioFileReader.WaveFormat.BlockAlign) != 0) newPos -= newPos % audioFileReader.WaveFormat.BlockAlign;// Force new position into valid rangenewPos = Math.Max(0, Math.Min(audioFileReader.Length, newPos));// set positionaudioFileReader.Position = newPos; The simple thing to do here is define a set of extensions to the WaveStream class that will handle block aligning during a seek operation. The basic align-to-block operation can be called by variations that just calculate the new position from whatever you put in, so something like this: public static class WaveStreamExtensions{ // Set position of WaveStream to nearest block to supplied position public static void SetPosition(this WaveStream strm, long position) { // distance from block boundary (may be 0) long adj = position % strm.WaveFormat.BlockAlign; // adjust position to boundary and clamp to valid range long newPos = Math.Max(0, Math.Min(strm.Length, position - adj)); // set playback position strm.Position = newPos; } // Set playback position of WaveStream by seconds public static void SetPosition(this WaveStream strm, double seconds) { strm.SetPosition((long)(seconds * strm.WaveFormat.AverageBytesPerSecond)); } // Set playback position of WaveStream by time (as a TimeSpan) public static void SetPosition(this WaveStream strm, TimeSpan time) { strm.SetPosition(time.TotalSeconds); } // Set playback position of WaveStream relative to current position public static void Seek(this WaveStream strm, double offset) { strm.SetPosition(strm.Position + (long)(offset* strm.WaveFormat.AverageBytesPerSecond)); }} With that in place, you can call audioFileReader.SetPosition(10.0) to jump to playback position 00:00:10.0 , call audioFileReader.Seek(-5) to jump back 5 seconds, etc. without worrying about seeking to a point half way through a sample. So... add some buttons to your form and set them up to call the Seek method with +/- values to move around. Then add a slider of some sort that you can use to display and set the playback position. Throw in a timer to update the slider position to the current playback position and you're about done. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20982914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2138457/']} | jdg_79123 |
stackexchange | llm_judgeable_groundtruth_similarity | 61508409 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Rails 6 app set up to use Tailwind CSS with Webpacker similarly to how it's done in this GoRails tutorial . I want to be able to change the Tailwind defaults dynamically based on the controller and action so that it's very easy for users to "skin" sections of the site by selecting a few options that then dynamically adjust a few of the Tailwind config options. (An example of how this could be used would be users logged into the admin area of the site changing their font family and background color to match their brand.) I can't just add a stylesheet to the layout based on a conditional because I'd have to override all of the instances where a Tailwind css variable I want to change (like "sans-serif"). That would be a lot of work and brittle to maintain as Tailwind evolves. It would be ideal if there was a way to dynamically insert choices selected by the user into the Tailwind config file ( /javascript/stylesheets/tailwindcss-config.js ), but I'm not sure how to do this. Also is there a better way to do this in Rails when using Tailwind? It seems like there should be some way to use Javascript from the controller to dynamically change the settings in my tailwindcss-config.js (The Tailwind config file is explained here ). So, something in that file like this: theme: { fontFamily: { display: ['Gilroy', 'sans-serif'], body: ['Graphik', 'sans-serif'], }, What was a font stack hard-coded as a configuration in Tailwind would become this: theme: { fontFamily: { display: DYNAMICALLY INSERTED FONT STACK, body: ANOTHER DYNAMICALLY INSERTED FONT STACK, }, How would you do this in Rails? I have that Tailwind config file living at /javascript/stylesheets/tailwindcss-config.js. Is this possible to do with Webpack in rails? Is this even the correct approach to take with Rails 6 using Webpacker + Tailwind?
Now provide the response and nothing else.
| I have the feeling that we'd be trying to use a 'buildtime' tool for a 'runtime' operation To directly inject the variable into tailwindcss config file would imply a rebuild of the actual css served to the user, applying the instructions in tailwind config file to the actual content put in app/javascript/css (assuming the setup used in the mentioned video tutorial). The operation is carried on by webpack, integrated through the webpacker gem. IMHO, neither webpack nor tailwind were designed with the purpose of rebuilding the assets at runtime, and, even if I'm definitely aware that a universal machine can do anything ;) I wonder where taking this route would take one, mainly in terms of maintainability. From this link it seems that triggering a rebuild of webpack on a config change is not straightforward. Here's a somewhat different path to try: In the <head> section of the application define css variables (more precisely 'css custom properties' ) for the settings you want your user to access, which can be set and changed dynamically (from js too) <style> :root{ --display-font: "<%= display_font_families %>"; --body-font: "<%= body_font_families %>"; --link-color: "<%= link_color %>"; }</style> Alternatively you could create app/assets/stylesheets/root.css.erb (the extension is important) and include it in your template before tailwind Then you should be able to change your tailwindcss config to something like the following: theme: { fontFamily: { display: "var(--display-font)", body: "var(--body-font)", }, extend: { colors: { link: "var(--link-color)", }, } This way we define a dynamic css layout that responds to the value of css variables . The variables and the structure they act on reside on the same logical level, which corresponds to the actual webpage served to the user. css variables are easily accessible from js, this is one way to have a clean access from rails too Now let's imagine that the user wants to change the link color (applied to all the links). In our imaginary settings form, she chooses an arbitrary color (in any css-valid format - the only constraint here is that it must be a valid css value , something you'll need to address with some form of input validation). We'd likely want a preview feature (client side/js): without reloading the page the user should be able to apply the new settings temporarily to the page. This can be done with a js call that sets the new value for the variable --link-color // userSelectedColor is the result of a user's choice, // say it's "#00FF00"document.documentElement.style .setProperty('--link-color', userSelectedColor); as soon as this value is changed, all the classes previously created by tailwind, and any rule that make use of the variable, will reflect the change, no need to rebuild the css at all. Please note that our user is not constrained to an arbitrary subset of the possible values, anything that can be accepted by css is fair game. By assigning to the config parameter a css variable, we actually have instructed tailwindcss to specify it in all its classes as a variable value, which now is under our control through css/js ...We definitely DON'T NEED (nor want) webpack to rebuild the styles To try to make it clearer, with our color example, in the generated css there will be classes like these - have a look at this link for an explanation of how customizing tailwind theme works /* GENERATED BY TAILWIND - well, this or something very similar :) */.text-link { color: var(--link-color);}.bg-link{ background-color: var(--link-color);}/* .border-link { ... */ clearly the browser needs to know the value of --link-color (we've defined it in the :root section) and the value itself can be any valid css, but what interests us is that it can be changed anytime, automagically propagating the change to every rule using it, it's a css variable ... and we'll want a save feature (server side/rails): when the user clicks on 'save', the new settings should be made persistent (saved in db) this is plainly accomplished (for example) handling the form submit, saving the new value, which will then be pulled from the db to valorize the css variables on the next render of the page just my 2 cents :) have fun ! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61508409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168286/']} | jdg_79124 |
stackexchange | llm_judgeable_groundtruth_similarity | 26315808 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a server machine and I am trying to allow my PC ip address to use gii . My PC ip address is 192.168.1.101 The server machine ip is 192.168.1.102 . I used composer to install the gii module . This is how my composer.json settings look like: "require": { "php": ">=5.4.0", "yiisoft/yii2": "*", "yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-swiftmailer": "*", "yiisoft/yii2-gii": "*" }, "require-dev": { "yiisoft/yii2-codeception": "*", "yiisoft/yii2-debug": "*", "yiisoft/yii2-gii": "*", "yiisoft/yii2-faker": "*" }, I have used php init and composer update and php yii migrate . I am also logged in in the frontend . This is the main.php file content: return [ 'id' => 'app-frontend', 'basePath' => dirname(__DIR__), 'bootstrap' => ['gii'], 'controllerNamespace' => 'frontend\controllers', 'components' => [ 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'errorHandler' => [ 'errorAction' => 'site/error', ], ], 'params' => $params, 'modules' => [ 'gii' => [ 'class' => 'yii\gii\Module', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.1.101'], 'password' => '123456' ], ],];
Now provide the response and nothing else.
| I had a similar issue and tried all different ipFilter changes. In the end I needed to add this to main-local.php. Which was strange because I had an advanced application, and the settings were for a 'yii2 basic' setup. http://www.yiiframework.com/doc-2.0/guide-start-gii.html if (!YII_ENV_TEST) {// configuration adjustments for 'dev' environment$config['bootstrap'][] = 'debug';$config['modules']['debug'] = 'yii\debug\Module';$config['bootstrap'][] = 'gii';$config['modules']['gii'] = 'yii\gii\Module';} I should also point out, I did add this to main.php 'modules' => [ 'gii' => [ 'class' => 'yii\gii\Module', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.1.*', 'XXX.XXX.XXX.XXX'] // adjust this to your needs ],], | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26315808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1292344/']} | jdg_79125 |
stackexchange | llm_judgeable_groundtruth_similarity | 5162 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Here's the context for the question: Proposition 4.6 of Freitag and Kiehl's book on etale cohomology shows that a sheaf (of sets) $\mathcal{F}$ (on the site Et(X)) is constructible if and only if it is the coequalizer of an etale equivalence relation $\mathcal{R}\rightrightarrows \mathcal{Y}$, where $\mathcal{R}$ and $\mathcal{Y}$ are representable sheaves. Here an etale equivalence relation is defined exactly as you would expect: $\mathcal{R}\rightarrow \mathcal{Y}\times \mathcal{Y}$ is injective, and for every etale $U\rightarrow X$, $\mathcal{R}(U)\subset \mathcal{Y}(U)\times \mathcal{Y}(U)$ is an equivalence relation (of sets). Now if the quotient $\mathcal{Y}/\mathcal{R}$ "should" be represented by the quotient $Y/R$ (where $Y$ represents $\mathcal{Y}$ and $R$ represents $\mathcal{R}$), well, it sounds like constructible sheaves should be algebraic spaces, or at least there should be some relationship. On the other hand, I don't think this could be right. So is the problem that you can't take sheafy quotients like this, or is it something more subtle?
Now provide the response and nothing else.
| It seems like your interpretation is correct. The bottom of page 39 reads As we have already seen in § 1, for every sheaf of sets $\mathcal F$ on the scheme $X$ there is a family $X_\alpha$ of etale $X$-schemes and a surjective sheaf mapping $\coprod \tilde X_\alpha\to \mathcal F$ (where $\tilde X_\alpha$ is the sheaf represented by $X_\alpha$). The sheaf $\mathcal F$ is called constructible if one can get by with a finite family. In this case $\mathcal F$ actually turns out to be the quotient of a representable sheaf by a representable equivalence relation (not separated, in general). Thus one can interpret $\mathcal F$ as an etale algebraic space over $X$ (not necessarily separated) in the sense of M. Artin, Knutson [91]. Since the disjoint union of an arbitrary collection of etale $X$-schemes is an etale $X$-scheme, they must be implicitly assuming each $X_\alpha$ is finite type or something. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/5162', 'https://mathoverflow.net', 'https://mathoverflow.net/users/88/']} | jdg_79126 |
stackexchange | llm_judgeable_groundtruth_similarity | 17855859 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am developing a real time system, and I am debating about the design of the classes. To be specific, I can't decide whether to build the "heavy" classes by using two phase construction. On the one hand, calling constructor of a "heavy" class can be a major bottle-neck at running time, and it saves me from creating classes and allocating memory of features that the user might won't use. On the other hand, two phase construction can makes surprises during execution, considering a situation when the we try to access an ability, but we can't since it didn't initialize, and suddenly we need to fully build it before using. My tendency is to go for a two phase construction method. What i like to hear is pros\cons for two phase construction at real time system. And if there is a better approach toward this. Here a code example of a heavy class (my classes sure won't look like that, but it demonstrate my idea): class VeryHeavy { private: HeavyClass1* p1; HeavyClass2* p2; HeavyClass3* p3; HeavyClass4* p4; HeavyClass5* p5; int* hugeArray [100000]; //...//};
Now provide the response and nothing else.
| This is the AGC, Apollo Guidance Computer, used both on the Apollo command module and the lunar module. Famous for almost causing the Apollo 11 landing to be scrubbed. Right in the middle of the descent to the Moon surface, this computer crashed on a real-time error. Several times. Producing System Error 1201 (Executive overflow - no vacant areas) and System Error 1202 (Executive overflow - no core sets). Armstrong and Aldrin only saw the number, the UI device you see on the right of the photo was too primitive to show strings. It was guidance controller Steve Bales that knew what the numbers meant (they had never seen the error while training) and knew that the system could recover from it. And saved the landing by giving the GO anyway, he got the Presidential Medal of Freedom for that. This is probably what your question is asking about, although we can be pretty sure that you are not trying to land a rocket. The term "real time" used to be pretty well defined in software engineering but it got muddled by the financial industry. In Apollo 11 it meant a system that has a very hard upper limit on the maximum response time to external events. Rockets need a such a system, it can't be too late sometimes when adjusting the nozzle, being late once produces a billion dollar ball of fire. The financial industry hijacked it to mean a system that's arbitrarily fast , being late sometimes isn't going to vaporize the machine although it makes the odds for a trading loss greater. They probably consider that a disaster as well :) The memory allocator you use matters a lot, also not defined in the question. Arbitrarily I'll assume your program is running on a demand-paged virtual memory operating system. Not exactly the ideal environment for a Real Time system but common enough, true real-time operating systems haven't fared well. Two-phase construction is a technique used to deal with initialization failure, exceptions thrown in a constructor are difficult to deal with, the destructor will not run so that can cause a resource leak if you allocate in the constructor without otherwise making the constructor smart enough to deal with a mishap. The alternative is to do it later, inside a member function, lazily allocating as needed. So what you worry about is that lazy allocation is going to hamper the responsiveness of the system. Producing System Error 1201. This is not in fact a primary concern on a demand-paged virtual memory operating system like Linux or Windows. The memory allocator on these operating system is fast, it only allocates virtual memory. Which doesn't cost anything, it is virtual. The true cost comes later, when you actually start to use the allocated memory. Where the "demand" of demand-paged comes into play. Addressing an array element is going to produces a page fault, forcing the operating system to map the addressed virtual memory page into RAM. Such page faults are relatively cheap, called "soft" page faults, if the machine isn't otherwise under pressure and must unmap a page being used by another process to acquire the RAM. You'd expect the OS to be able to just grab a page and map it, overhead is measured in microseconds. So in effect, if you do it right and don't try to initialize the entire array when you allocate it then your program will be subjected to tens of thousands of tiny needle pricks of overhead. Each single one small enough to not endanger a real-time response guarantee. This will happen regardless of whether you allocate the memory early or late, so whether you use two-phase construction doesn't matter. If you want to guarantee that this doesn't happen either, or want to be resilient to a storm of page faults you get when you initialize the entire array, then you'll need a very different approach, you need to page-lock the RAM allocation so that the operating system cannot unmap the page. This invariably requires tinkering with the OS settings, it typically doesn't allow a process to page-lock large amounts of memory. Two-phase construction is then out of the door as well of course. Do keep in mind that it is pretty rare for a program to know how to deal with allocation failure. They behave almost like asynchronous exceptions, ready to strike at any point in time in nearly any part of the program. Especially hard to reconcile with the real-time requirement, a system that has no response to a real-time event because it ran out of memory is of course no better than one that's late. That's still a ball of fire ;) So that in itself should be already enough reason to not bother with two-phase construction, just allocate the memory at program initialization time, before you start promising real-time response. It makes coding the program a lot simpler, the odds for failure are much lower. A pretty hard requirement for any software that runs with real-time characteristics is that it won't have to fight with other processes to acquire operating system resources. Dedicating the entire machine to just one process is expected, you are not restricted to 36864 words of rope memory and 2048 words of RAM anymore like the AGC. Hardware is cheap and plentiful enough these days to provide such a guarantee. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17855859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2260356/']} | jdg_79127 |
stackexchange | llm_judgeable_groundtruth_similarity | 7699200 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between OpenID and SAML?
Now provide the response and nothing else.
| Original OpenID 2.0 vs SAML They are two different protocols of authentication and they differ at the technical level. From a distance, differences start when users initiate the authentication. With OpenID, a user login is usually an HTTP address of the resource which is responsible for the authentication. On the other hand, SAML is based on an explicit trust between your site and the identity provider so it's rather uncommon to accept credentials from an unknown site. OpenID identities are easy to get around the net. As a developer you could then just accept users coming from very different OpenID providers. On the other hand, a SAML provider usually has to be coded in advance and you federate your application with only selected identity providers. It is possible to narrow the list of accepted OpenID identity providers but I think this would be against the general OpenID concept. With OpenID you accept identities coming from arbitrary servers. Someone claims to be http://someopenid.provider.com/john.smith . How you are going to match this with a user in your database? Somehow, for example by storing this information with a new account and recognizing this when user visits your site again. Note that any other information about the user (including his name or email) cannot be trusted! On the other hand, if there's an explicit trust between your application and the SAML Id Provider, you can get full information about the user including the name and email and this information can be trusted, just because of the trust relation. It means that you tend to believe that the Id Provider somehow validated all the information and you can trust it at the application level. If users come with SAML tokens issued by an unknown provider, your application just refuses the authentication. OpenID Connect vs SAML (section added 07-2017, expanded 08-2018) This answer dates 2011 and at that time OpenID stood for OpenID 2.0 . Later on, somewhere at 2012, OAuth2.0 has been published and in 2014, OpenID Connect (a more detailed timeline here ). To anyone reading this nowadays - OpenID Connect is not the same OpenID the original answer refers to , rather it's a set of extensions to OAuth2.0. While this answer can shed some light from the conceptual viewpoint, a very concise version for someone coming with OAuth2.0 background is that OpenID Connect is in fact OAuth2.0 but it adds a standard way of querying the user info , after the access token is available. Referring to the original question - what is the main difference between OpenID Connect (OAuth2.0) and SAML is how the trust relation is built between the application and the identity provider: SAML builds the trust relation on a digital signature, SAML tokens issued by the identity provider are signed XMLs, the application validates the signature itself and the certificate it presents. The user information is included in a SAML token, among other information. OAuth2 builds the trust relation on a direct HTTPs call from the application to the identity. The request contains the access token (obtained by the application during the protocol flow) and the response contains the information about the user. OpenID Connect further expands this to make it possible to obtain the identity without this extra step involving the call from the application to the identity provider. The idea is based on the fact that OpenID Connect providers in fact issue two tokens, the access_token , the very same one OAuth2.0 issues and the new one, the id_token which is a JWT token, signed by the identity provider. The application can use the id_token to establish a local session, based on claims included in the JWT token but the id_token cannot be used to further query other services, such calls to third party services should still use the access_token . You can think of the OpenID Connect then as a hybrid between the SAML2 (signed token) and OAuth2 (access token), as OpenID Connect just involves both. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7699200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311762/']} | jdg_79128 |
stackexchange | llm_judgeable_groundtruth_similarity | 2307673 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When I want to calculate$$\int{\frac {x^2}{ ( x\cos x -\sin x ) ^2}}\,{\rm d}x$$I have tested with software and get$${\frac {x\sin \left( x \right) +\cos \left( x \right) }{x\cos \left( x \right) -\sin \left( x \right) }}$$ But I can not come to this conclusion, neither using integration by parts, nor using trigonometric identities, nor multiplying by their conjugate, Even by rational trigonometric substitution. I do not know what else to try. Could you give me any suggestions?
Now provide the response and nothing else.
| We can rewrite $$\begin{align}\int \frac{x^2}{(\sin x - x\cos x)^2} \, \mathrm{d}x &= \int \frac{x\sin x(x\sin x + \cos x)}{(\sin x - x\cos x)^2} \, \mathrm{d}x - \int \frac{x\cos x}{\sin x - x\cos x} \, \mathrm{d}x \\ & = -\frac{x\sin x + \cos x}{\sin x - x\cos x} \color{green}{+} \int \frac{x\cos x}{\sin x- x\cos x} \, \mathrm{d}x \color{red}{-} \int \frac{x\cos x}{\sin x - x\cos x} \, \mathrm{d}x \\ & = -\frac{x\sin x + \cos x}{\sin x - x\cos x}\end{align}$$ via IBP with $u = x\sin x + \cos x \implies u' = x\cos x$ and $$\mathrm{d}v = \frac{x\sin x}{(\sin x - x\cos x)^2} \implies v = -\frac{1}{\sin x -x\cos x}$$ via straightforward $f = \sin x - x\cos x \implies f' = x\sin x$ sub. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2307673', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9823/']} | jdg_79129 |
stackexchange | llm_judgeable_groundtruth_similarity | 1682310 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a generic class which new's up an instance of the generic type. As follows: public class HomepageCarousel<T> : List<T> where T: IHomepageCarouselItem, new(){ private List<T> GetInitialCarouselData() { List<T> carouselItems = new List<T>(); if (jewellerHomepages != null) { foreach (PageData pageData in jewellerHomepages) { T item = new T(pageData); // this line wont compile carouselItems.Add(item); } } return carouselItems; }} But I get the following error: cannot provide arguments when creating an instance of a variable type I found the following related question which is very close to what I need: Passing arguments to C# generic new() of templated type However, I can't used Jared's suggested answer as I amcalling the method within the Generic class, not outside ofit, so I can't specify the concrete class. Is there a way around this? I have tried the following based on the other question, butit doesn't work as I don't know the concrete type of T tospecify. As it is called from inside the generic class, notoutside: public class HomepageCarousel<T> : List<T> where T: IHomepageCarouselItem, new(){ private List<T> LoadCarouselItems() { if (IsCarouselConfigued) { return GetConfiguredCarouselData(); } // ****** I don't know the concrete class for the following line, // so how can it be instansiated correctly? return GetInitialCarouselData(l => new T(l)); } private List<T> GetInitialCarouselData(Func<PageData, T> del) { List<T> carouselItems = new List<T>(); if (jewellerHomepages != null) { foreach (PageData pageData in jewellerHomepages) { T item = del(pageData); carouselItems.Add(item); } } return carouselItems; }} ********EDIT : ADDED POSSIBLE SOLUTIONS** So I have tested 2 possible solutions: First is exactly as explained below by Jon Skeet . Thisdefinitely works but means having an obscure lambda in theconstructor. I am not very comfortable with this as it meansusers need to know the correct lambda that is expected.After all, they could pass a lambda which doesn't new up thetype, but does something entirely unexpected Secondly, I went down the Factory method route;I added a Create method to the common interface: IJewellerHomepageCarouselItem Create(PageData pageData); Then provided an implementation in each Concrete class: public IJewellerHomepageCarouselItem Create(PageData pageData){ return new JewellerHomepageCarouselItem(pageData, null);} And used a two step initialisation syntax: T carouselItem = new T();T homepageMgmtCarouselItem = (T) carouselItem.Create(jewellerPage); Would love to hear some feedback on the merit of each of these approaches.
Now provide the response and nothing else.
| Jared's answer is still a good way to go - you just need to make the constructor take the Func<PageData, T> and stash it for later: public class HomepageCarousel<T> : List<T> where T: IHomepageCarouselItem{ private readonly Func<PageData, T> factory; public HomepageCarousel(Func<PageData, T> factory) { this.factory = factory; } private List<T> GetInitialCarouselData() { List<T> carouselItems = new List<T>(); if (jewellerHomepages != null) { foreach (PageData pageData in jewellerHomepages) { T homepageMgmtCarouselItem = factory(pageData); carouselItems.Add(homepageMgmtCarouselItem); } } return carouselItems; } Then you just pass the function into the constructor where you create the new instance of the HomepageCarousel<T> . (I'd recommend composition instead of inheritance, btw... deriving from List<T> is almost always the wrong way to go.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1682310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17194/']} | jdg_79130 |
stackexchange | llm_judgeable_groundtruth_similarity | 33573807 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to preserve comments as faithfully as possible while manipulating XML. I managed to preserve comments, but the contents are getting XML-escaped. #!/usr/bin/env python# add_host_to_tomcat.pyimport xml.etree.ElementTree as ETfrom CommentedTreeBuilder import CommentedTreeBuilderparser = CommentedTreeBuilder()if __name__ == '__main__': filename = "/opt/lucee/tomcat/conf/server.xml" # this is the important part: use the comment-preserving parser tree = ET.parse(filename, parser) # get the node to add a child to engine_node = tree.find("./Service/Engine") # add a node: Engine.Host host_node = ET.SubElement( engine_node, "Host", name="local.mysite.com", appBase="webapps" ) # add a child to new node: Engine.Host.Context ET.SubElement( host_node, 'Context', path="", docBase="/path/to/doc/base" ) tree.write('out.xml') #!/usr/bin/env python# CommentedTreeBuilder.pyfrom xml.etree import ElementTreeclass CommentedTreeBuilder ( ElementTree.XMLTreeBuilder ): def __init__ ( self, html = 0, target = None ): ElementTree.XMLTreeBuilder.__init__( self, html, target ) self._parser.CommentHandler = self.handle_comment def handle_comment ( self, data ): self._target.start( ElementTree.Comment, {} ) self._target.data( data ) self._target.end( ElementTree.Comment ) However, comments like like: <!--EXAMPLE HOST ENTRY: <Host name="lucee.org" appBase="webapps"> <Context path="" docBase="/var/sites/getrailo.org" /> <Alias>www.lucee.org</Alias> <Alias>my.lucee.org</Alias> </Host>HOST ENTRY TEMPLATE: <Host name="[ENTER DOMAIN NAME]" appBase="webapps"> <Context path="" docBase="[ENTER SYSTEM PATH]" /> <Alias>[ENTER DOMAIN ALIAS]</Alias> </Host> --> End up as: <!-- EXAMPLE HOST ENTRY: <Host name="lucee.org" appBase="webapps"> <Context path="" docBase="/var/sites/getrailo.org" /> <Alias>www.lucee.org</Alias> <Alias>my.lucee.org</Alias> </Host> HOST ENTRY TEMPLATE: <Host name="[ENTER DOMAIN NAME]" appBase="webapps"> <Context path="" docBase="[ENTER SYSTEM PATH]" /> <Alias>[ENTER DOMAIN ALIAS]</Alias> </Host> --> I also tried self._target.data( saxutils.unescape(data) ) in CommentedTreeBuilder.py , but it didn't seem to do anything. In fact, I think the problem happens somewhere after the handle_commment() step. By the way, this question is similar to this .
Now provide the response and nothing else.
| Tested with Python 2.7 and 3.5, the following code should work as intended. #!/usr/bin/env python# CommentedTreeBuilder.pyfrom xml.etree import ElementTreeclass CommentedTreeBuilder(ElementTree.TreeBuilder): def comment(self, data): self.start(ElementTree.Comment, {}) self.data(data) self.end(ElementTree.Comment) Then, in the main code use parser = ElementTree.XMLParser(target=CommentedTreeBuilder()) as the parser instead of the current one. By the way, comments work correctly out of the box with lxml . That is, you can just do import lxml.etree as ETtree = ET.parse(filename) without needing any of the above. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33573807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1026263/']} | jdg_79131 |
stackexchange | llm_judgeable_groundtruth_similarity | 882727 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have code like this. var key = "anything"; var object = { key: "key attribute" }; I want to know if there is a way to replace that key with "anything". like var object = { "anything": "key attribute" };
Now provide the response and nothing else.
| In ES6, use computed property names . const key = "anything"; const object = { [key]: "key attribute"// ^^^^^ COMPUTED PROPERTY NAME}; Note the square brackets around key . You can actually specify any expression in the square brackets, not just a variable. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/882727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109367/']} | jdg_79132 |
stackexchange | llm_judgeable_groundtruth_similarity | 17125843 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm learning OpenGL in C++ using NeHe tutorials, but I'm trying to do them with FreeImage library, instead of Glaux or SOIL. The good point I see in using FreeImage is thar it's last update was in October last year, while SOIL hasn't been updated in 5 years. The problem I have is that I'm not able to load textures correctly. Here is my code: static GLuint texture = 0;if (texture == 0){ FIBITMAP* bitmap = FreeImage_Load( FreeImage_GetFileType("textures/test/nehe_06.png", 0), "textures/test/nehe_06.png"); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 3, FreeImage_GetWidth(bitmap), FreeImage_GetHeight(bitmap), 0, GL_RGB, GL_UNSIGNED_BYTE, FreeImage_ConvertTo32Bits(bitmap)); FreeImage_Unload(bitmap);} Using this code, the texture I get is wrong: it's black, with coloured dots and strips, and changing the image gives the same result, so I assume I'm not loading the texture correctly. I've tried to swap the red and blue bits (read that FreeImage loads in BGR) with no better result. Finally, if I change the *FreeImage_ConvertTo32Bits(bitmap)* by *FreeImage_GetBits(bitmap)* I get a segfault. What I'm doing wrong?
Now provide the response and nothing else.
| There are two problems with your code - one is that you are converting to image to 32 bits but you specify a 24 bit texture format to openGL ( GL_RGB ). The second is that you are passing the FreeImage object itself to the texture rather than the converted bits. You need to do something like this instead FIBITMAP *pImage = FreeImage_ConvertTo32Bits(bitmap);int nWidth = FreeImage_GetWidth(pImage);int nHeight = FreeImage_GetHeight(pImage);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, nWidth, nHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(pImage));FreeImage_Unload(pImage); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17125843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/726172/']} | jdg_79133 |
stackexchange | llm_judgeable_groundtruth_similarity | 10988569 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the soft limit (at which the user needs to give permission to exceed)?What is the hard limit (maximum allowed).
Now provide the response and nothing else.
| Update May 2020 : Chrome now lets an origin use 60% of the storage device's space (Real nitty gritty: "storage device" is the partition containing the chrome profile directory). Updated article here https://web.dev/storage-for-the-web/#how-much The rule of thumb is 6% (edit 2015-Jul: was 10%) of the available space on the user's hard drive, less if your origin is using websql, appcache or the filesystem api. The MDN doc mentioning 5mb was outdated and has been updated. The gory details about the current policy are here: https://developer.chrome.com/apps/offline_storage Note some annoying subtleties: There is no PERSISTENT storage for indexeddb, only the stuff in the link above about TEMPORARY applies. Once your origin exhausts its share of the pool, indexeddb transactions will unhelpfully abort with no real indication why. As of now the only way to determine that lack of quota is the cause is to use queryUsageAndQuota to check how much space is left. Hopefully a future version of chrome will soon properly fill out IDBTransaction.error in these cases. Edit: chrome 26 now properly fills out IDBTransaction.error with QuotaExceededError. There is currently no API to request more storage space for indexeddb. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10988569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4906/']} | jdg_79134 |
stackexchange | llm_judgeable_groundtruth_similarity | 7656 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Defining $$\xi(s) := \pi^{-s/2}\ \Gamma\left(\frac{s}{2}\right)\ \zeta(s)$$ yields $\xi(s) = \xi(1 - s)$ (where $\zeta$ is the Riemann Zeta function). Is there any conceptual explanation - or intuition, even if it cannot be made into a proof - for this? Why of all functions does one have to put the Gamma-function there? Whoever did this first probably had some reason to try out the Gamma-function. What was it? (Best case scenario) Is there some uniform way of producing a factor out of a norm on the rationals which yields the other factors for the p-adic norms and the Gamma factor for the absolute value?
Now provide the response and nothing else.
| To the best of my understanding, the answer is yes, and this uniform way consists of some integration over the local field. This is explained in John Tate's dissertation. One starts with a certain smooth rapidly decreasing function, for which one takes the characteristic function of the p-adic integers in the nonarchimedean case and the function $e^{-|x|^2}$ for an archimedean field. This is being multiplied with $|x|^s$ (approximately) and integrated over the Haar measure of the additive group of the field. This produces the $\Gamma$-factor for an archimedean field and $(1-p^{-s})^{-1}$ for a p-adic field. | {} | {'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/7656', 'https://mathoverflow.net', 'https://mathoverflow.net/users/733/']} | jdg_79135 |
stackexchange | llm_judgeable_groundtruth_similarity | 4073161 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How could nested pattern matching, such as the following example, be re-written so that None is specified only once? I think the Maybe monad solves this problem. Is there something similar in the F# core library? Or, is there an alternative approach? match a with| Some b -> let c = b.SomeProperty match c with | Some d -> let e = d.SomeProperty //and so on... | None -> ()| None -> ()
Now provide the response and nothing else.
| you can solve this using built-in capabilities: Option.bind type A = member this.X : B option = Unchecked.defaultof<_>and B = member this.Y : С option = Unchecked.defaultof<_>and С = member this.Z : string option = Unchecked.defaultof<_>let a : A = Unchecked.defaultof<_>let v = match a.X |> Option.bind (fun v -> v.Y) |> Option.bind (fun v -> v.Z) with | Some s -> s | None -> "<none>" Frankly, I doubt that introducing full-fledged 'maybe' implementation (via computation expressions) here can shorten the code. EDIT : Dream mode - on I think that version with Option.bind can be made smaller if F# has more lightweight syntax for the special case: lambda that refer to some member of its argument: "123" |> fun s -> s.Length // current version"123" |> #.Length // hypothetical syntax This is how the sample can be rewritten in Nemerle that already has such capabilities: using System;using Nemerle.Utility; // for Accessor macro : generates property for given fieldvariant Option[T]{ | Some {value : T} | None}module OptionExtensions{ public Bind[T, U](this o : Option[T], f : T -> Option[U]) : Option[U] { match(o) { | Option.Some(value) => f(value) | Option.None => Option.None() } }}[Record] // Record macro: checks existing fields and creates constructor for its initialization class A{ [Accessor] value : Option[A];}def print(_){ // shortened syntax for functions with body -> match over arguments | Option.Some(_) => Console.WriteLine("value"); | Option.None => Console.WriteLine("none");}def x = A(Option.Some(A(Option.Some(A(Option.None())))));print(x.Value.Bind(_.Value)); // "value"print(x.Value.Bind(_.Value).Bind(_.Value)); // "none" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4073161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/162396/']} | jdg_79136 |
stackexchange | llm_judgeable_groundtruth_similarity | 38684187 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my directory: miuse/application miuse/application/views/templates/header.php miuse/bootstrap/css miuse/bootstrap/js miuse/bootstrap/fonts This is my controller code: <?php class page extends CI_controller{ public function view($page= 'home') { if(!file_exists(APPPATH.'views/pages/'.$page.'.php')) { show_404(); } $data['title']='Moodlist home'; $this->load->view('templates/header', $data); } }?> This is my view code: <!DOCTYPE html><html lang="en"><head><title> <?php echo $title; ?></title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><link rel="stylesheet" href="http://localhost/miuse/bootstrap/css/bootstrap.css"><link rel="stylesheet" href="header.css" type="text/css"></head><body><header class="container"><div class="row"><h1 class="col-sm-4">List</h1> <nav class="col-sm-8 text-right"> <p>Home</p> <p>Category</p> <p>About us</p> </nav> </div></header></body></html> when i run my view normally in a browser it shows proper output but when i load it with codeigniter view then it shows different output which i dont want.
Now provide the response and nothing else.
| Please Follow below steps : A) USING JAVA : For Old Chrome Version (<50): //Create a instance of ChromeOptions classChromeOptions options = new ChromeOptions();//Add chrome switch to disable notification - "**--disable-notifications**"options.addArguments("--disable-notifications"); //Set path for driver exe System.setProperty("webdriver.chrome.driver","path/to/driver/exe");//Pass ChromeOptions instance to ChromeDriver ConstructorWebDriver driver =new ChromeDriver(options); For New Chrome Version (>50): //Create a map to store preferences Map<String, Object> prefs = new HashMap<String, Object>(); //add key and value to map as follow to switch off browser notification//Pass the argument 1 to allow and 2 to blockprefs.put("profile.default_content_setting_values.notifications", 2); //Create an instance of ChromeOptions ChromeOptions options = new ChromeOptions(); // set ExperimentalOption - prefs options.setExperimentalOption("prefs", prefs); //Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browserWebDriver driver = new ChromeDriver(options); For Firefox : WebDriver driver ;FirefoxProfile profile = new FirefoxProfile();profile.setPreference("permissions.default.desktop-notification", 1);DesiredCapabilities capabilities=DesiredCapabilities.firefox();capabilities.setCapability(FirefoxDriver.PROFILE, profile);driver = new FirefoxDriver(capabilities);driver.get("http://google.com"); B) USING PYTHON : from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsoption = Options()option.add_argument("--disable-infobars")option.add_argument("start-maximized")option.add_argument("--disable-extensions")# Pass the argument 1 to allow and 2 to blockoption.add_experimental_option( "prefs", {"profile.default_content_setting_values.notifications": 1})driver = webdriver.Chrome( chrome_options=option, executable_path="path-of-driver\chromedriver.exe")driver.get("https://www.facebook.com") C) USING C#: ChromeOptions options = new ChromeOptions();options.AddArguments("--disable-notifications"); // to disable notificationIWebDriver driver = new ChromeDriver(options); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38684187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6659969/']} | jdg_79137 |
stackexchange | llm_judgeable_groundtruth_similarity | 217536 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Both the inverting amplifier and non-inverting amplifier use negative feedback. Both provide gain. But one inverts the signal while the other does not. How to know which one to use? Are there applications where only one of the two can be used (provides both positive and negative supplies exist)? Is it true that single supply op amp can only create non-inverting amplifier?
Now provide the response and nothing else.
| There are a couple reasons (at least) for choosing a particular configuration: If you need a high input impedance, then you are forced into a non-inverting configuration. This is commonly required in a buffering situation. An inverting configuration has an input impedance equal to the input resistor which may load the source circuit. If you need a summing amplifier, then inverting is the way to go as the inverting input is the summing junction. Is it true that single supply op amp can only create non-inverting amplifier? No. With a DC offset (on the non-inverting input) you can have an inverting configuration although the input signal will need to be ac coupled under most circumstances. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/217536', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20711/']} | jdg_79138 |
stackexchange | llm_judgeable_groundtruth_similarity | 232131 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a (connected) closed $n$-manifold and $G=\pi_1(X)$ be the fundamental group of $X$. There is a classifying map $f: X \rightarrow K(G, 1)$ which induces an isomorphism on $\pi_1$. I would like know when the map $f_*: H_n(X, \mathbb{Z}) \rightarrow H_n(K(G,1), \mathbb{Z})$ is injective, or even when $f_*: H_n(X, \mathbb{Q}) \rightarrow H_n(K(G,1), \mathbb{Q})$ is injective. (Here $K(G, 1)$ is not assumed to be a manifold.) For example, if $X$ is simply connected, the induced map $f_*$ is the zero map on $H_n$ and when $X$ is the n-torus $T^n$, the induced map $f_*$ is an isomorphism. Is there any condition on $\pi_1(X)$ that will imply injectivity of $f_*$ on $H_n$?
Now provide the response and nothing else.
| There can not be such a condition. For any finitely presented group $G$, we can find a closed 4-manifold $N$ with fundamental group $G$. In dimension $n \geq 6$, we can now take $M = N \times S^{n-4}$, a $n$-manifold with fundamental group $G$. Then the classifying map $f\colon M \to BG$ of the universal cover $\tilde{M} \to M$ factors through $N$, hence$$f_{\ast}\colon \ H_n(M;\mathbb Z) \to H_n(BG;\mathbb Z)$$ is zero. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/232131', 'https://mathoverflow.net', 'https://mathoverflow.net/users/88164/']} | jdg_79139 |
stackexchange | llm_judgeable_groundtruth_similarity | 28015753 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to return a structure that looks like this: { results: [ ["ooid1", 2.0, "Söme text"], ["ooid2", 1.3, "Åther text"], ]} That's an array of arrags that is string, floating point number, unicode character. If it was Python I'd be able to: import jsonjson.dumps({'results': [["ooid1", 2.0, u"Söme text"], ...]) But in Go you can't have an array (or slice) of mixed types. I thought of using a struct like this: type Row struct { Ooid string Score float64 Text rune} But I don't want each to become a dictionary, I want it to become an array of 3 elements each.
Now provide the response and nothing else.
| Use []interface{} type Results struct { Rows []interface{} `json:"results"`} You will then have to use type assertion if you want to access the values stored in []interface{} for _, row := range results.Rows { switch r := row.(type) { case string: fmt.Println("string", r) case float64: fmt.Println("float64", r) case int64: fmt.Println("int64", r) default: fmt.Println("not found") } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28015753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205832/']} | jdg_79140 |
Subsets and Splits