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
41497277
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basic setup: 1) App is React and Redux, 2) App is served by a front facing NGINX serving static files like html, pictures and of course the app itself. It also forwards all relevant requests (web sockets and/or AJAX) to the back end (phoenix/elixir). 3) Users are required to authenticate. I'm using redux-oidc library, which is client side only and it works fine. 4) After user logs on is when I get hazy on what to do next. Question(s): 1) I can't send the state along with the first request because I don't know who the user is and, thus, don't know which state to send. Meanwhile application is already booted (empty store created, login component displayed), 2) After user logs on I can't show anything (like user specific nav bar, timeline , mailbox) I have to saturate the store and let react do its job. What approach should I take? 3) Server rendering is out because a) I'm not using Node and rendering react components using chosen framework is messy and complicated at best and b) I won't be able to export the app to NGinx since it only serves static assets and there is no server logic run there. I could, theoretically, get rid of NGinx, have server based login on the API server and send down HTML along with JSON state which could be used to render the app on the client. However, NGinx does not only serve static assets but also load balances few instances and, thus, getting rid of it is not something I want to do. Any advice would be appreciated. Now provide the response and nothing else.
Hydrating the state after the store was created, can be achieved by creating a main reducer that can bypass the top level reducers, and replace the whole state. Reducers are functions that get the current state, combine it with the payload of an action, and return a new state. Usually the main reducer is a combination of all top reducers using combineReducers , and the state is the combination of state pieces returned by the top level reducers. However, the main reducer can react to actions directly. If the main reducer receives a certain action ( hydrate ), instead of calling the combined reducers, it returns the action's payload (the saved state). Other actions are passed to the combined reducers. const mainReducer = (state = {}, action) => action.type === 'hydrate' ? action.payload // hydrate the state : reducers(state, action); // create new state by using combined reducers Working example: const { combineReducers, createStore } = Redux;const people = (state = [], action) => action.type === 'people' ? [...state, action.payload] : state;const items = (state = [], action) => action.type === 'items' ? [...state, action.payload] : state;const reducers = combineReducers({ people, items});const mainReducer = (state = {}, action) => action.type === 'hydrate' ? action.payload : reducers(state, action);const store = createStore(mainReducer);store.subscribe(() => console.log(store.getState()));store.dispatch({ type: 'people', payload: 5 });store.dispatch({ type: 'items', payload: 'green' });store.dispatch({ type: 'hydrate', payload: { people: [20, 30, 50, 100], items: ['green', 'yellow', 'red']}}); <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.min.js"></script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41497277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981375/']}
jdg_84641
stackexchange
llm_judgeable_groundtruth_similarity
11847815
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Error: 1071 - Specified key was too long; max key length is 1000 bytes CREATE TABLE `phppos_modules_actions` ( `action_id` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `module_id` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `action_name_key` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `sort` INT NOT NULL , PRIMARY KEY ( `action_id` , `module_id` )) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_unicode_ci; I know the error occurs because of 255x2x3 (3 bytes per character) This doesn't happen on all installations. What setting can I change? Now provide the response and nothing else.
NO_ENGINE_SUBSTITUTION disabled with INNODB not active, a bad combination Up to MySql 5.5 the sqlmode default was a blank string, that means that the sqlmode NO_ENGINE_SUBSTITUTION was not set by default According to MySql docs (see https://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_no_engine_substitution ) this is the meaning of sqlmode NO_ENGINE_SUBSTITUTION: Control automatic substitution of the default storage engine when astatement such as CREATE TABLE or ALTER TABLE specifies a storageengine that is disabled or not compiled in. Because storage engines can be pluggable at runtime, unavailableengines are treated the same way: With NO_ENGINE_SUBSTITUTION disabled, for CREATE TABLE the defaultengine is used and a warning occurs if the desired engine isunavailable. For ALTER TABLE, a warning occurs and the table is notaltered. With NO_ENGINE_SUBSTITUTION enabled, an error occurs and the table isnot created or altered if the desired engine is unavailable. So: if NO_ENGINE_SUBSTITUTION is disabled AND INNODB is switched OFF, MySql will switch to MYISAM also if you specify INNODB in your CREATE TABLE statement. If the table you are creating is OK for MYISAM, you just receive a warning and the table is created. That is not your case, your creation statement include an index that is beyond the 1000 bytes limit of MYISAM, then the creation fails with error 1071 reporting the error of MYISAM. That is because the working engine is MYISAM, not INNODB. PROOF MySql version 5.1.56 community Case 1: Options in my.cnf sql-mode="" default-storage-engine=MYISAM skip-innodb uncommented (without#) Return on execution of your create statement:Error Code: 1071. Specified key was too long; max key length is 1000 bytesExplanation: INNODB is not active, the engine is automatically switched to MYISAM that returns this error as they key is longer than MYISAM 1000 bytes limit. The key length is: 2 fields x 255 char x 3 bytes utf8 encoding + 2 x 1 length byte = 1532 bytes Case 2: Options in my.cnfsql-mode="NO_ENGINE_SUBSTITUTION"default-storage-engine=MYISAMskip-innodb uncommented (without#)Return on execution of your create statement:Error Code: 1286. Unknown table engine 'INNODB'Explanation: INNODB is not active but the engine substitution is not permittedby sql mode therefore the DB returns an error about the attempt of using a disabled engine. Case 3: Options in my.cnfsql-mode="NO_ENGINE_SUBSTITUTION"default-storage-engine=MYISAMskip-innodb commented (with#)Return on execution of your create statement:Table creation OK!Explanation: INNODB is active (skip-innodb commented) and it is used also if the default engine is MYISAM. To reproduce the tests restart MySql after every change in my.cnf. Since MySql version 5.6 sqlmode is no more empty by default and contains NO_ENGINE_SUBSTITUTION, moreover INNODB is the default engine, so the error is difficult to meet. OTHER TESTS No other way of reproducing the error: Error Code: 1071. Specified key was too long; max key length is 1000 bytes while trying to create an INNODB table has been found. In INNODB you have two kinds of ERROR 1071: Error Code: 1071. Specified key was too long; max key length is 767 bytes this has nothing to do with innodb_large_prefix ON or OFF, but is only related to the size of a single VARCHAR column being used as an index. Mysql store varchar utf8 with 3 bytes plus 1 byte for the length up 255 character and 2 after (see: http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html ), so if you try to set a key with VARCHAR(256) utf8 you get: 256 x 3 + 2 = 770 bytes and you get the previous error, as the max key length for a single column is 767 bytes for an InnoDB table. A VARCHAR(255) is ok, because: 255 x 3 + 1 = 766 bytes I tested it on four installations of Mysql, version 5.1.56, 5.5.33, 5.6 and 5.7, and that is confirmed. No issue with your query with VARCHAR(255), issue with VARCHAR(256): Error Code: 1071. Specified key was too long; max key length is 767 bytes As you can see the message is different, because it is an INNODB message not a MYISAM one! The other type of ERROR 1071 for INNODB tables is: Error Code: 1071. Specified key was too long; max key length is 3072 bytes This is related to keys with multiple columns. For those keys to be enabled you need to set innodb_large_prefix to on.Anyway, if you try to run something like this: CREATE TABLE `phppos_modules_actions` ( `action_id` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `module_id` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `action_name_key` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `action_name_key1` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `action_name_key2` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `sort` INT NOT NULL , PRIMARY KEY ( `action_id` , `module_id`, `action_name_key`, `action_name_key1`, `action_name_key2` )) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_unicode_ci; With a key of 5 VARCHAR(255) utf8 columns, that is 3830 bytes, you will run into the: Error Code: 1071. Specified key was too long; max key length is 3072 bytes Exotic Hypothesis During the search of the cause I formulated and tested different and pretty weird hypothesis: ROW format Tested REDUNDANT, COMPACT, COMPRESS, DYNAMIC: no impact on table creation with your statement. FILE format Tested Antelope and Barracuda: no impact on table creation with your statement. MySql built Tested 32bit and 64 bit MySql: no impact on table creation with your statement. Others similar failures Here you can find the same error in the same situation: https://www.drupal.org/node/2466287 I tested that statement in the 3 test situations listed in PROOF and it reproduced exactly the same behavior as yours, so I can say the issue is the same. In that case they switched to other DB, but the problem is the mix of setting, not the DB version. References A very good article of indexing with INNODB is given here: http://mechanics.flite.com/blog/2014/07/29/using-innodb-large-prefix-to-avoid-error-1071/ WARNING: disabling INNODB by uncommenting skip-innodb in my.cnf after the creation of INNODB table with index longer than 1000 will not permit the start of MySql service Regards
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11847815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/627473/']}
jdg_84642
stackexchange
llm_judgeable_groundtruth_similarity
33259191
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 install libicu-dev on mac. This is the instruction recommended on the documentation sudo apt-get install python-numpy libicu-dev http://polyglot.readthedocs.org/en/latest/Installation.html I am using anaconda but it seems to always throw up an In file included from _icu.cpp:27: ./common.h:86:10: fatal error: 'unicode/utypes.h' file not found #include <unicode/utypes.h> error Now provide the response and nothing else.
I just got PyICU to install on OSX, after it was failing due to that same error. Here is what I recommend: Install homebrew (package manager for OSX) brew install icu4c # Install the library; may be already installed Verify that the necessary include directory is present: ls -l /usr/local/opt/icu4c/include/ If you do not have that directory, you may need to reinstall icu4u. I found that I had to do the following: brew remove icu4c brew install icu4c Try to install polyglot to see if it can find icu4c: pip install polyglot If that still complains, you can try specifying library location: CFLAGS=-I/usr/local/opt/icu4c/include LDFLAGS=-L/usr/local/opt/icu4c/lib pip install polyglot EDIT: There have been further changes. My current process for installing icu: brew install icu4c brew link icu4c --force ICU_VERSION=<BREW_ICU_VERSION> CFLAGS=-I/usr/local/opt/icu4c/include LDFLAGS=-L/usr/local/opt/icu4c/lib pip install pyicu
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33259191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939166/']}
jdg_84643
stackexchange
llm_judgeable_groundtruth_similarity
3253
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Today in the cafeteria my friend dropped a chicken wing on the floor and immediately picked it up and ate it. Afterward he claimed that the chicken wing was still safe to eat if it was consumed within 5 seconds after being on the floor. He said that it's the "five second rule". Is this rule safe to follow? Now provide the response and nothing else.
Image Source Jillian Clarke researched this in 2003 when she was a high school science intern at the University of Illinois . Among Clarke's findings : 70% of women and 56% of men are familiar with the 5-second rule, and most use it to make decisions about tasty treats that slip through their fingers. Women are more likely than men to eat food that's been on the floor. Cookies and candy are much more likely to be picked up and eaten than cauliflower or broccoli . And, if you drop your food on a floor that does contain microorganisms, the food can be contaminated in 5 seconds or less . Clarke was awarded the 2004 IG Nobel Prize in Public Health for her work. Food Scientist Paul Dawson at Clemson University also looked into it. His findings were published in the Journal of Applied Microbiology : Three experiments were conducted to determine the survival and transfer of Salmonella Typhimurium from wood, tile or carpet to bologna (sausage) and bread . In the case of the 5-second-rule we found that bacteria was transferred from tabletops and floors to the food within five seconds , that is the 5-second-rule is not an accurate guide when it comes to eating food that has fallen on the floor. The MythBusters also busted the 5-second-rule : Even if something spends a mere millisecond on the floor, it attracts bacteria. How dirty it gets depends on the food's moisture, surface geometry and floor condition — not time. Here is the video.
{}
{'log_upvote_score': 8, 'links': ['https://skeptics.stackexchange.com/questions/3253', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/2760/']}
jdg_84644
stackexchange
llm_judgeable_groundtruth_similarity
39224904
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 construct a pair of elements: array: *mut T array_len: usize array is intended to own the data However, Box::into_raw will return *mut [T] . I cannot find any info on converting raw pointers to slices. What is its layout in memory? How do I use it from C? Should I convert to *mut T ? If so, how? Now provide the response and nothing else.
If you just want some C function to mutably borrow the Vec , you can do it like this: extern "C" { fn some_c_function(ptr: *mut i32, len: ffi::size_t);}fn safe_wrapper(a: &mut [i32]) { unsafe { some_c_function(a.as_mut_ptr(), a.len() as ffi::size_t); }} Of course, the C function shouldn't store this pointer somewhere else because that would break aliasing assumptions. If you want to "pass ownership" of the data to C code, you'd do something like this: use std::mem;extern "C" { fn c_sink(ptr: *mut i32, len: ffi::size_t);}fn sink_wrapper(mut vec: Vec<i32>) { vec.shrink_to_fit(); assert!(vec.len() == vec.capacity()); let ptr = vec.as_mut_ptr(); let len = vec.len(); mem::forget(vec); // prevent deallocation in Rust // The array is still there but no Rust object // feels responsible. We only have ptr/len now // to reach it. unsafe { c_sink(ptr, len as ffi::size_t); }} Here, the C function "takes ownership" in the sense that we expect it to eventually return the pointer and length to Rust, for example, by calling a Rust function to deallocate it: #[no_mangle]/// This is intended for the C code to call for deallocating the/// Rust-allocated i32 array.unsafe extern "C" fn deallocate_rust_buffer(ptr: *mut i32, len: ffi::size_t) { let len = len as usize; drop(Vec::from_raw_parts(ptr, len, len));} Because Vec::from_raw_parts expects three parameters, a pointer, a size and a capacity, we either have to keep track of the capacity as well somehow, or we use Vec's shrink_to_fit before passing the pointer and length to the C function. This might involve a reallocation, though.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39224904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/883113/']}
jdg_84645
stackexchange
llm_judgeable_groundtruth_similarity
988522
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 have been trying to understand the intuitive meaning of quotient ring for quite some times but unfortunately I could not find any. Now I am approaching this question from a different angle, hoping that the answer would make me a more enlightened student. I know the most important and common example of quotient ring is $$\mathbb{Z}/n\mathbb{Z} = \{0, 1, 2, \ldots, n-1\}.$$Having known that, I also know that math names and symbols were not coined casually, they are in fact the consensus of mathematicians over periods of decades if not centuries. Then here is my question: Do the words "quotient," "factor" and division symbol "/" have any meaning at all in the above example? What I would like to know is that, since mathematicians choose names and symbols painstakingly and carefully, the "quotient," "factor" and "/" should be indicative of something. I am looking forward to learn from you and thank you very much for your time and help. Now provide the response and nothing else.
$R/I$ is the ring $R$, treated as though everything in $I$ were really just zero. For example, let $R$ be the ring of all functions $f:\mathbb{R}\to\mathbb{R}$, and let $I$ be the ideal $\{f\in R\mid f(0) = 0\}$. What is $R/I$? Well, it's a ring of functions, but a function that vanishes at $0$ is treated as though it really is the zero function. So $R\to \mathbb{R}$ sending $f\mapsto f(0)$ induces an isomorphism $R/I\to \mathbb{R}$. The quotient ring is precisely identifying two functions whenever they agree at $0$. By the same token, $\mathbb{Z}/n\mathbb{Z}$ is to be understood as the ring where "multiples of $n$ are zero". In other words, it is the ring of remainders modulo $n$. This is all summed up in the universal property of the quotient: a morphism $R\to S$ whose kernel contains $I$ is exactly the same as a morphism $R/I\to S$. In other words, $R/I$ is the "universal" way of contracting elements of $I$ to zero. The intuitive meaning here, of "factor", is: "Get rid of it!"
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/988522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80219/']}
jdg_84646
stackexchange
llm_judgeable_groundtruth_similarity
44140404
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 following component that creates an MdDialog export class SideNavsComponent implements OnInit, AfterViewInit, OnDestroy { eventDispatcher: EventDispatcher authEmailDialogRef: MdDialogRef<AuthEmailDialogComponent> constructor(public dialog: MdDialog,) { this.eventDispatcher = new EventDispatcher() } signIn( event ): void { this.isSignedIn = event.checked this.openDialog() } openDialog() { this.authEmailDialogRef = this.dialog.open( AuthEmailDialogComponent, { height: '500px', width: '300px', disableClose: true } ) } ngOnDestroy() { } ngAfterViewInit() { } ngOnInit() { event_dispatcher.on( 'CLOSE authEmailDialogRef', ( target: Object ) => { this.authEmailDialogRef.close() } ) }} The component below creates a button that when clicked closes the MdDialog created above by sending and event that is intercepted within the SideNavsComponent#ngOnInit method export class AuthEmailDialogComponent implements OnInit {eventDispatcher: EventDispatcher = new EventDispatcher()}cancel() { event_dispatcher.dispatch( 'CLOSE authEmailDialogRef', '') }} The MdDialog is closed(), but a detection change error always occurs with the following: ERROR Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges at viewDestroyedError (core.es5.js:8636) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12781) at checkAndUpdateView (core.es5.js:12122) at callWithDebugContext (core.es5.js:13184) at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:12724) at ViewRef_.detectChanges (core.es5.js:10196) at asterisk.component.ts:37 at ZoneDelegate.webpackJsonp.1467.ZoneDelegate.invokeTask (zone.js:414) at Object.onInvokeTask (core.es5.js:4119) at ZoneDelegate.webpackJsonp.1467.ZoneDelegate.invokeTask (zone.js:413)View_MdDialogContainer_Host_0 @ MdDialogContainer_Host.html:1proxyClass @ compiler.es5.js:14091DebugContext_.logError @ core.es5.js:13124ErrorHandler.handleError @ core.es5.js:1144next @ core.es5.js:4757schedulerFn @ core.es5.js:3830SafeSubscriber.__tryOrUnsub @ Subscriber.js:236SafeSubscriber.next @ Subscriber.js:185Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ core.es5.js:3816NgZone.triggerError @ core.es5.js:4188onHandleError @ core.es5.js:4149webpackJsonp.1467.ZoneDelegate.handleError @ zone.js:385webpackJsonp.1467.Zone.runTask @ zone.js:184ZoneTask.invoke @ zone.js:476timer @ zone.js:1491setInterval (async)scheduleTask @ zone.js:1501webpackJsonp.1467.ZoneDelegate.scheduleTask @ zone.js:400onScheduleTask @ zone.js:290webpackJsonp.1467.ZoneDelegate.scheduleTask @ zone.js:394webpackJsonp.1467.Zone.scheduleTask @ zone.js:225webpackJsonp.1467.Zone.scheduleMacroTask @ zone.js:248(anonymous) @ zone.js:1527proto.(anonymous function) @ zone.js:1402AsteriskComponent @ asterisk.component.ts:37createClass @ core.es5.js:10870createDirectiveInstance @ core.es5.js:10701createViewNodes @ core.es5.js:12064callViewAction @ core.es5.js:12508execComponentViewsAction @ core.es5.js:12417createViewNodes @ core.es5.js:12091createRootView @ core.es5.js:11969callWithDebugContext @ core.es5.js:13184debugCreateRootView @ core.es5.js:12644ComponentFactory_.create @ core.es5.js:9890ComponentFactoryBoundToModule.create @ core.es5.js:3427ViewContainerRef_.createComponent @ core.es5.js:10092PortalHostDirective.attachComponentPortal @ material.es5.js:2135MdDialogContainer.attachComponentPortal @ material.es5.js:19218MdDialog._attachDialogContent @ material.es5.js:19486MdDialog.open @ material.es5.js:19400webpackJsonp.751.SideNavsComponent.openDialog @ side-navs.component.ts:39webpackJsonp.751.SideNavsComponent.signIn @ side-navs.component.ts:35(anonymous) @ SideNavsComponent.html:32handleEvent @ core.es5.js:11892callWithDebugContext @ core.es5.js:13184debugHandleEvent @ core.es5.js:12772dispatchEvent @ core.es5.js:8792(anonymous) @ core.es5.js:10720schedulerFn @ core.es5.js:3842SafeSubscriber.__tryOrUnsub @ Subscriber.js:236SafeSubscriber.next @ Subscriber.js:185Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ core.es5.js:3816ToggleButton.toggle @ togglebutton.js:42(anonymous) @ ToggleButton.html:4handleEvent @ core.es5.js:11892callWithDebugContext @ core.es5.js:13184debugHandleEvent @ core.es5.js:12772dispatchEvent @ core.es5.js:8792(anonymous) @ core.es5.js:9384(anonymous) @ platform-browser.es5.js:2683webpackJsonp.1467.ZoneDelegate.invokeTask @ zone.js:414onInvokeTask @ core.es5.js:4119webpackJsonp.1467.ZoneDelegate.invokeTask @ zone.js:413webpackJsonp.1467.Zone.runTask @ zone.js:181ZoneTask.invoke @ zone.js:476MdDialogContainer_Host.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}} How can I prevent the changeDetection firing after the component is destroyed; in otherwords how can I make this code work without the error? NB: Tried many suggestions on stackoverflow but none worked. Thanks Now provide the response and nothing else.
The issue is the close action of the dialog is removing the item from the view, and your EventDispatcher IS NOT AN ANGULAR METHOD so it fires outside the zone context and freaks it out. It goes like this: Dialog exists in view, sets state Clicks close Fires your event to start Your event is read (out of context) Deletes from view (still out of context) Change detection finally catches up to look for changes in your component, OH SNAP WHERE'S THE COMPONENT? You can either use a different method to communicate with the dialog, or switch to onPush() for change detection I suggest you Use the afterClosed handle instead: this. authEmailDialogRef.afterClosed().subscribe(result => { console.log(`Dialog result: ${result}`); // Pizza!}); I pulled that snippet straight from the docs: HERE
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44140404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2258442/']}
jdg_84647
stackexchange
llm_judgeable_groundtruth_similarity
200892
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 $\sigma (n)$ be the sum-of-divisors function. For example, $\sigma(7)=1+7=2^3$. I know some results about triplets of positive integers $(n,a,b)$ where $a,b\ge 2$ such that $\sigma (n)=a^b$, but I'd like to ask the following question : What is known and unknown about the triplets? I'd like to know any relevant references as well. Added : It is my understanding that so-called friend Don gave me an excellent answer for each fixed $b$. By the way, it'd be nice if somebody could show me some references for each fixed $a$. Added : I've known the following results for a fixed $a$. There exist pairs $(n,b)$ such that $\sigma(n)=2^b$ if and only if $n$ is a product of distinct Mersenne primes . There exist no pairs $(n,b)$ such that $\sigma(n)=3^b$. I would like to know if more general results for each fixed $a$ are known. Added : When I was trying to expand the case for $a=3$, I found that there exist no pairs $(n,b)$ such that $\sigma(n)=p^b$ where $p$ is a Fermat prime . Now provide the response and nothing else.
For each fixed $k$, there are infinitely many squarefree numbers $n$ for which $\sigma(n)$ is a $k$th power. See: W.D. Banks, J.B. Friedlander, C. Pomerance and I.E. Shparlinski, Multiplicative structure of values of the Euler function, High Primes and Misdemeanours: Lectures in Honour of the Sixtieth Birthday of Hugh Cowie Williams (A. Van der Poorten, ed.), Fields Inst. Comm. 41 (2004), pp. 29-47. (The main object of study there is the Euler function $\phi$. But since $\phi(n) = \prod_{p\mid n}(p-1)$ on squarefree $n$, while $\sigma(n) = \prod_{p\mid n}(p+1)$, the methods carry over essentially unchanged.) There is also more recent work of Banks and Luca (google "power totients"), Freiberg ("products of shifted primes"), and Freiberg and Pomerance (google "square totients"). As an example of an unsolved problem, I think we don't know if there are infinitely many prime powers $p^e$ for which $\sigma(p^e)$ is a power. For related work, look up the Nagell--Ljunggren equation.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/200892', 'https://mathoverflow.net', 'https://mathoverflow.net/users/34490/']}
jdg_84648
stackexchange
llm_judgeable_groundtruth_similarity
2222466
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 following code: funcs = [] for i in range(10): def func(): print i funcs.append(func) for f in funcs: f() The problem is that func is being overriden. Ie the output of the code is: 999... How would you solve this without defining new functions? The optimal solution would be to change the name of the function. Ie: for i in range(10): def func+i():... (or some other weird syntax) Now provide the response and nothing else.
The problem is not that func is being overwritten, it's that the value of i is being evaluated when the function is called, not when it is defined. If you want to evaluate i at definition time, put it in the function declaration, as a default argument to func . funcs = []for i in range(10): def func(value=i): print value funcs.append(func)for f in funcs: f() Default arguments are evaluated once, when the function is defined, so the incrementing loop will not affect them. This would work just as well if you used def func(i=i): print i but I used the name value to make it clear which name is being used within the function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2222466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170713/']}
jdg_84649
stackexchange
llm_judgeable_groundtruth_similarity
29766317
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 Customize the Login button in Facebook? I don't want to use Facebook default login button. Now provide the response and nothing else.
For SDK 4.0 : U should add a button and in button action use the below code : - (IBAction)loginButtonClicked:(id)sender { FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { // Process error NSLog(@"error %@",error); } else if (result.isCancelled) { // Handle cancellations NSLog(@"Cancelled"); } else { if ([result.grantedPermissions containsObject:@"email"]) { // Do work NSLog(@"%@",result); NSLog(@"Correct"); } } }];} Updated : To receive Users Information - (IBAction)loginButtonClicked:(id)sender { FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { // Process error NSLog(@"error %@",error); } else if (result.isCancelled) { // Handle cancellations NSLog(@"Cancelled"); } else { if ([result.grantedPermissions containsObject:@"email"]) { // Do work [self fetchUserInfo]; } } }]; }-(void)fetchUserInfo { if ([FBSDKAccessToken currentAccessToken]) { NSLog(@"Token is available"); [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) { if (!error) { NSLog(@"Fetched User Information:%@", result); } else { NSLog(@"Error %@",error); } }]; } else { NSLog(@"User is not Logged in"); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29766317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4630678/']}
jdg_84650
stackexchange
llm_judgeable_groundtruth_similarity
50742013
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 data that was set up by someone else on S3… The data is visitors data… with columns like VisitorId, Partner, Date, etc… The data is partitioned by day (the people that owns it, query mostly by date)… But I wanted to query it too from Athena, and most of my queries tend to group by VisitorId, so I shall query/scan every, day, year,month… My questions are: I was told I can’t/shouldn’t query by any other than date, I mean I must have ‘date’ in the ‘where’ clause… is this true? Can I index by VisitorId (as if it were a non-clustered index in sql server). Is my only option to load the data all over again, but this time partitioned by VisitorId? Notice that the data as it is now partitioned by day, suits well for the people using it now… I just happened to need the same data but I want to query it differently… Now provide the response and nothing else.
Okay seems as i found a solution finally. I added some comments to the instructions how i made it work. 1. checkstyle's jar file somewhere 2. a checkstyle XML check file somewhere 3. To configure git: * git config --add checkstyle.jar <location of jar> * git config --add checkstyle.checkfile <location of checkfile> * git config --add java.command <path to java executale> [optional defaults to assuming it's in your path] I checked my config (can be found in the .git directory of your git reposirtory) and it looked like this: ... [checkstyle] checkfile = C:\\Users\\schuster\\Desktop\\checkstyle jar = C:\\Users\\schuster\\Desktop\\checkstyle ... So since im Working on Windows i changed it to: ...[checkstyle] checkfile = C:/Users/schuster/Desktop/checkstyle/google_checks.xml jar = C:/Users/schuster/Desktop/checkstyle/checkstyle.jar... . 4. Put this in your .git/hooks directory as pre-commit 'This' is the file i linked when i stated my problem. So this file needs to be in the /hooks directory. But it has to be renamed as one of the existing samples which are already in there. Since my hook is a pre-commit hook i took the "pre-commit" filename. Next this file has to become an executable. To do that type in chmod +x pre-commit in the /hooks directory of your git repository. If you work with Windows do that using the Git Bash. EDIT : In case someone want to use this script and is wondering why it doesnt abort even if checks fail - here is how to fix it.in line 58 if (&run_and_log_system ($command)) has to be chanted to if (!&run_and_log_system ($command))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50742013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4979809/']}
jdg_84651
stackexchange
llm_judgeable_groundtruth_similarity
10652615
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 using CoreData and I set the NSManagedObjectContext in AppDelegate file. I need to get that managedObjectContext in a ViewController which is many levels deep in the naviagation tree. Obviously, I do not want to pass it along all the init methods. I have tried [[[UIApplication sharedApplication] delegate] managedObjectContext]; but I get this error " No known instance method for selector 'managedObjectContext' " Can someone guide me on how to get the managedObjectContext from AppDelegate to this ViewContoller ? Now provide the response and nothing else.
First you need to create a property in your AppDelegate.h like the following: @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext; // or strong if you ARC instead of retain Using readonly prevent you to modify the context externally. In AppDelegate.m synthesize it like: @synthesize managedObjectContext; Always within the AppDelegate.m override the getter method like - (NSManagedObjectContext *)managedObjectContext{ if (managedObjectContext != nil) return managedObjectContext; NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:coordinator]; } return managedObjectContext;} Once done you have a managedObjectContext property which can be accessed anywhere with AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];NSManagedObjectContext* context = appDelegate.managedObjectContext; A more cool approach could be to create a class method in your AppDelegate.h like the following: + (AppDelegate *)sharedAppDelegate; Then in AppDelegate.m do like the following: + (AppDelegate *)sharedAppDelegate{ return (AppDelegate *)[[UIApplication sharedApplication] delegate];} Now, anywhere, before having imported your AppDelegate header ( #import "AppDelegate.h" ), you can do: AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];NSManagedObjectContext* context = appDelegate.managedObjectContext; Note Using such an approach causes your application to become rigid. To overcome this problem I suggest you to read about passing-around-a-nsmanagedobjectcontext-on-the-iphone by Marcus Zarra. Hope it helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10652615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/817126/']}
jdg_84652
stackexchange
llm_judgeable_groundtruth_similarity
381408
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 clarification. Let $A=\{1,2,3\}$ be a set and $R=\{(1,2)\}$ be a relation on $A$. Is it a Transitive relation? I am confused because some text books say $R$ is transitive if it contains only one ordered pair. I am not able to explain why $R$ can said to be transitive in the above case. A relation is said to be transitive if $(a,b) \in R$ and $(b,c) \in R$ then $(a,c) \in R $. If P then Q. $P: (a,b) \in R$ and $(b,c) \in R$ and $Q:(a,c) \in R$ But here only one condition of $P$ is satisfied. According to some source, if second condition i.e, $(b,c) \in R$ does not exist, $R$ is said to be transitive. Can we say $R$ is transitive? Or do we need both conditions of $P$? Now provide the response and nothing else.
Yes, it is a transitive relation, vacuously so. That is, there are no counter examples in the relation that violate transitivity. Transitivity requires that If $(P)$: $(i)$ $(a, b) \in R\;$ AND $(ii)$ $(b, c) \in R$, (conditions) THEN $(Q)$: it must follow that $(a, c) \in R$ (consequent) Since $(P)$, the conditions (i) and (ii), will never both be realized/satisfies since the only element in $R$ is $(1, 2)$, we have that the implication $(P) \implies (Q)$ is vacuously true . NOTE: We can equivalently define transitivity as a property that HOLDS UNLESS there exists a case (counterexample) for which both conditions in $(P)$ are met, but the consequent $(Q)$ is false (does not hold.)
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/381408', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64682/']}
jdg_84653
stackexchange
llm_judgeable_groundtruth_similarity
288954
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 coming from my first course in undergraduate analysis, and it's confusing to me how to show that some operation is "well-defined". For example, my professor left as something for us to figure out on our own, not homework, to show ourselves that if $a,b,c$ and $d$ are integers, and ($b,d\not=0$) that $$\left[\left(\frac{a}{b}\right)\right]+\left[\left(\frac{c}{d}\right)\right]=\left[\left(\frac{ad+bc}{bd}\right)\right]$$ is well defined. He then made an example that said: If $\frac{a'}{b'}\sim\frac{a}{b}$ and $\frac{c'}{d'}\sim \frac{c}{d}$, then $\frac{a'c'}{b'd'}\sim \frac{ac}{bd}$. Also above in the brackets are supposed to be $2$ classes of element's. Now provide the response and nothing else.
To show that addition is well-defined there means to show that using different elements to represent the same equivalence class leads to the same result. You need to show that if $[\frac{a}{b}]=[\frac{a'}{b'}]$ and $[\frac{c}{d}]=[\frac{c'}{d'}]$, then $[\frac{ad+bc}{bd}]=[\frac{a'd'+b'c'}{b'd'}]$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/288954', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43372/']}
jdg_84654
stackexchange
llm_judgeable_groundtruth_similarity
1404704
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: It can be shown that using the definition of the Gamma function as:$$\Gamma(t) = \int_0^\infty x^{t-1} e^{-x} dx $$ that $$\Gamma(\tfrac{1}{2}) = \sqrt{\pi}$$ or slightly abusing notation, that $(-\frac{1}{2})! = \sqrt{\pi}$. Is there an intuitive explanation to this? I want to make clear that I am not per se interested in a proof of this fact (most often these are clever technical manipulations) but in insight into this phenomenon. Now provide the response and nothing else.
Consider the area of the surface of the $n-$Ball with radius $1$ . It is given by: $$A_{n}=2\frac{\pi^{n/2}}{\Gamma(n/2)}$$ Our intuition tells us that for $n=1$ the surface "area" (or to be mathematically more precise the, Hausdorff measure as @Michael Galuza pointed out correctly)should be 2, because it consist of two points. To make this consistent with the above formula we have to demand that $$\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1404704', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157862/']}
jdg_84655
stackexchange
llm_judgeable_groundtruth_similarity
5382271
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 say I define macro with arguments, then invoke it as follows: #define MIN(x,y) ((x)<(y)?(x):(y))int x=1,y=2,z;z=MIN(y,x); Given that (a) macro works as text substitution, (b) that actual args here are like formal args, only swapped, -- will this specfic z=MIN(y,x) work as expected ? If it will, why ?I mean, how preprocessor manages not to confuse actual and formal args ? This question is about technicalities of C compiler . This is not c++ question. This question does not recommend anybody to use macros. This question is not about programming style. Now provide the response and nothing else.
The internal representation of the macro will be something like this, where spaces indicate token boundaries, and #1 and #2 are magic internal-use-only tokens indicating where parameters are to be substituted: MIN( #1 , #2 ) --> ( ( #1 ) < ( #2 ) ? ( #1 ) : ( #2 ) ) -- that is to say, the preprocessor doesn't make use of the names of macro parameters internally (except to implement the rules about redefinitions). So it doesn't matter that the formal parameter names are the same as the actual arguments. What can cause problems is when the macro body makes use of an identifier that isn't a formal parameter name, but that identifier also appears in the expansion of a formal parameter. For instance, if you rewrote your MIN macro using the GNU extensions that let you avoid evaluating arguments twice... #define MIN(x, y) ({ \ __typeof__(x) a = (x); \ __typeof__(y) b = (y); \ a < b ? a : b; \}) and then you tried to use it like this: int minint(int b, int a) { return MIN(b, a); } the macro expansion would look like this: int minint(int b, int a){ return ({ __typeof__(b) a = (b); __typeof__(a) b = (a); a < b ? a : b; });} and the function would always return its first argument, whether or not it was smaller. C has no way to avoid this problem in the general case, but a convention that many people use is to always put an underscore at the end of the name of each local variable defined inside a macro, and never put underscores at the ends of any other identifiers. (Contrast the behavior of Scheme's hygienic macros , which are guaranteed to not have this problem. Common Lisp makes you worry about it yourself, but at least there you have gensym to help out.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5382271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/564524/']}
jdg_84656
stackexchange
llm_judgeable_groundtruth_similarity
6004129
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 the following shorthand for $(document).ready ? (function($){//some code})(jQuery); I see this pattern used a lot, but I'm unable to find any reference to it. If it is shorthand for $(document).ready() , is there any particular reason it might not work? In my tests it seems to always fire before the ready event. Now provide the response and nothing else.
The shorthand for $(document).ready(handler) is $(handler) (where handler is a function). See here . The code in your question has nothing to do with .ready() . Rather, it is an immediately-invoked function expression (IIFE) with the jQuery object as its argument. Its purpose is to restrict the scope of at least the $ variable to its own block so it doesn't cause conflicts. You typically see the pattern used by jQuery plugins to ensure that $ == jQuery .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6004129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427276/']}
jdg_84657
stackexchange
llm_judgeable_groundtruth_similarity
17623523
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 work with comma/tab-separated data files often that might look like this: key1,1,2.02,hello,4key2,3,4.01,goodbye,6... I might read and pre-process this in Python into a list of lists, like this: [ [ key1, 1, 2.02, 'hello', 4 ], [ key2, 3, 4.01, 'goodbye', 6 ] ] Sometimes, I like saving this list of lists as a pickle, since it preserves the different types of my entries. If the pickled file is big, though, it would be great to read this list of lists back in a streaming fashion. In Python, to load a text file as a stream, I use the follwoing to print out each line: with open( 'big_text_file.txt' ) as f: for line in f: print line Can I do something similar for a Python list, i.e.: import picklewith open( 'big_pickled_list.pkl' ) as p: for entry in pickle.load_streaming( p ): # note: pickle.load_streaming doesn't exist print entry Is there a pickle function like "load_streaming"? Now provide the response and nothing else.
This would work. What is does however is unpickle one object from the file, and then print the rest of the file's content to stdout What you could do is something like: import cPicklewith open( 'big_pickled_list.pkl' ) as p: try: while True: print cPickle.load(p) except EOFError: pass That would unpickle all objects from the file until reaching EOF. If you want something that works like for line in f: , you can wrap this up easily: def unpickle_iter(file): try: while True: yield cPickle.load(file) except EOFError: raise StopIteration Now you can just do this: with open('big_pickled_list.pkl') as file: for item in unpickle_iter(file): # use item ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17623523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292461/']}
jdg_84658
stackexchange
llm_judgeable_groundtruth_similarity
3905388
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 just tryng to create a simple webpart in visual studio 2010 (for sharepoint 2010)I created an empty sharepoint project, then added a webpart. I wrote a simple code (pasting it from a book with examples)I Build the project, then deploy it (without errors) Then when i go to the webpage where i want to add my webpart, i get this error when adding it: "unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain:$Resource:core,ImportErrorMessage;" Any idea about it? If it's needed i'll post the code of the .cs file Thanks Now provide the response and nothing else.
You can print it recursively by overriding toString in all your classes. If you want to have a method like printObjectRecursively(Object o) you need to dive into reflection, fetch the fields, print their name and content recursively using printObjectRecursively(someField) . Example: public class Test { public static void main(String[] args) { A a = new A(); System.out.println(a); }}class A { int i = 5; B obj = new B(); String str = "hello"; public String toString() { return String.format("A: [i: %d, obj: %s, str: %s]", i, obj, str); }}class B { int j = 17; public String toString() { return String.format("B: [j: %d]", j); }} Prints: A: [i: 5, obj: B: [j: 17], str: hello] A reflection-based recursive print method could be written something like this private static final List LEAVES = Arrays.asList( Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class, String.class);public static String toStringRecursive(Object o) throws Exception { if (o == null) return "null"; if (LEAVES.contains(o.getClass())) return o.toString(); StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getSimpleName()).append(": ["); for (Field f : o.getClass().getDeclaredFields()) { if (Modifier.isStatic(f.getModifiers())) continue; f.setAccessible(true); sb.append(f.getName()).append(": "); sb.append(toStringRecursive(f.get(o))).append(" "); } sb.append("]"); return sb.toString();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3905388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465588/']}
jdg_84659
stackexchange
llm_judgeable_groundtruth_similarity
29024313
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 tried to follow the steps at http://enable-cors.org/server_aspnet.html to have my RESTful API (implemented with ASP.NET WebAPI2) work with cross origin requests (CORS Enabled). It's not working unless I modify the web.config. I installed WebApi Cors dependency: install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api Then in my App_Start I've got the class WebApiConfig as follows: public static class WebApiConfig{ public static void Register(HttpConfiguration config) { var corsAttr = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(corsAttr); var constraintsResolver = new DefaultInlineConstraintResolver(); constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint)); config.MapHttpAttributeRoutes(constraintsResolver); config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config)); //config.EnableSystemDiagnosticsTracing(); config.Services.Replace(typeof(ITraceWriter), new SimpleTraceWriter(WebContainerManager.Get<ILogManager>())); config.Services.Add(typeof(IExceptionLogger), new SimpleExceptionLogger(WebContainerManager.Get<ILogManager>())); config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); }} but after that I run the application, I request a resource with Fiddler like: http://localhost:51589/api/v1/persons and in the response I cannot see the HTTP headers that I should see such as: Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS Access-Control-Allow-Origin: * Am I missing some step? I have tried with the following annotation on the controller: [EnableCors(origins: "http://example.com", headers: "*", methods: "*")] Same result, no CORS enabled. However, if I add the following in my web.config (without even installing the AspNet.WebApi.Cors dependency) it works: <system.webServer><httpProtocol> <!-- THESE HEADERS ARE IMPORTANT TO WORK WITH CORS --> <!-- <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" /> <add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" /> <add name="Access-Control-Allow-Credentials" value="true" /> </customHeaders> --></httpProtocol><handlers> <!-- THESE HANDLERS ARE IMPORTANT FOR WEB API TO WORK WITH GET,HEAD,POST,PUT,DELETE and CORS--> <!-- <remove name="WebDAV" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />--></handlers> Any help would be much appreciated! Thank you. Now provide the response and nothing else.
I've created a pared-down demo project for you. Source : https://github.com/bigfont/webapi-cors Api Link : https://cors-webapi.azurewebsites.net/api/values You can try the above API Link from your local Fiddler to see the headers. Here is an explanation. Global.ascx All this does is call the WebApiConfig . It's nothing but code organization. public class WebApiApplication : System.Web.HttpApplication{ protected void Application_Start() { WebApiConfig.Register(GlobalConfiguration.Configuration); }} WebApiConfig.cs The key method for your here is the EnableCrossSiteRequests method. This is all that you need to do. The EnableCorsAttribute is a globally scoped CORS attribute . public static class WebApiConfig{ public static void Register(HttpConfiguration config) { EnableCrossSiteRequests(config); AddRoutes(config); } private static void AddRoutes(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "Default", routeTemplate: "api/{controller}/" ); } private static void EnableCrossSiteRequests(HttpConfiguration config) { var cors = new EnableCorsAttribute( origins: "*", headers: "*", methods: "*"); config.EnableCors(cors); }} Values Controller The Get method receives the EnableCors attribute that we applied globally. The Another method overrides the global EnableCors . public class ValuesController : ApiController{ // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS response.", "It works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS response. ", "It works only from two origins: ", "1. www.bigfont.ca ", "2. the same origin." }; }} Web.config You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty. <?xml version="1.0" encoding="utf-8"?><configuration></configuration> Demo var url = "https://cors-webapi.azurewebsites.net/api/values"$.get(url, function(data) { console.log("We expect this to succeed."); console.log(data);});var url = "https://cors-webapi.azurewebsites.net/api/values/another"$.get(url, function(data) { console.log(data);}).fail(function(xhr, status, text) { console.log("We expect this to fail."); console.log(status);}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29024313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2948212/']}
jdg_84660
stackexchange
llm_judgeable_groundtruth_similarity
51959638
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 extract content files from a Nuget package to a project referencing my package. Based on Justin Emgarten's comment Packages.config projects use the content folder Project.json/PackageReference/NETCore SDK projects use the contentFiles folder So ok great, I created a .NET Core 2.1 Console Application project and followed the NuGet ContentFiles Demystified blog post which was written in 2016 at the time of project.json but should still work nowadays. I created an image at c:\dev\ContentFilesExample\contentFiles\any\any\images\dnf.png then created a c:\dev\ContentFilesExample\ContentFilesExample.nuspec file and copy pasted the content: <?xml version="1.0"?><package> <metadata minClientVersion="3.3.0"> <id>ContentFilesExample</id> <version>1.0.0</version> <authors>nuget</authors> <!-- The NuGet team authored this package --> <owners>nuget</owners> <!-- The NuGet team owns this package --> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>A content v2 example package.</description> <tags>contentv2 contentFiles</tags> <!-- Build actions for items in the contentFiles folder --> <contentFiles> <!-- Include Assets as Content --> <files include="**/images/*.*" buildAction="EmbeddedResource" /> </contentFiles> </metadata></package> Then I generated the Nuget package with the command nuget pack ContentFilesExample.nuspec and opened it using Nuget Package Explorer Great my picture is there as expected. And now the final non-working step. I install this Nuget package in my .NET Core 2.1 project but the image is missing. No trace of the image in the root directory of my project, neither in the obj folder nor in the bin folder. I tried to close and re-open visual studio as stated in some comments somewhere but that didn't solve the issue. I also tried to change my .NET Core project style to PackageReference but again, this didn't solve the issue <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.1</TargetFramework> <RestoreProjectStyle>PackageReference</RestoreProjectStyle> </PropertyGroup> <ItemGroup> <PackageReference Include="ContentFilesExample" Version="1.0.0" /> </ItemGroup> <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup></Project> So what am I doing wrong? Are content files in Nuget packages really supported by .NET Core? Thank you Now provide the response and nothing else.
I ended up on this question after hours and hours of googling for a solution, so I decided to write another answer to make things clear because MS docs suck <files> element in .nuspec file is for the packer . It tells nuget which files to pack (if there are no <files> element in your nuspec - nuget will use the directory naming convention) <contentFiles> element is for the consumer - it tells how and when to extract the files. If you want a file to appear in your project after installing - you have to pack it with a target that says contentFiles/any/any where "any/any" part tells nuget it's for ANY language and ANY framework. (optional) if you also want this file to work with the old nuget mode, that uses packages.config - you have to pack it again, 2nd time, this time - to "content" folder, so older consumers can still use it. nuspec <metadata> ... <contentFiles> <files include="**/myfile.cs" /> </contentFiles> </metadata> <files> <file src="myfile.cs" target="contentFiles\any\any" /> <!-- this is for new format --> <file src="myfile.cs" target="content" /> <!-- this is for the old format --> </files> PS. Some more details in my blog post here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51959638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203116/']}
jdg_84661
stackexchange
llm_judgeable_groundtruth_similarity
604757
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: An exercise in Lang's algebra book is: let $k$ an infinite field, and $E$ an algebraic extension of $k$. Then $E$ has the same cardinality as $k$. How can one can prove this? Now provide the response and nothing else.
HINT: First prove that $k[x]$ and $k$ have the same cardinality, you can do that by showing that $k[x]\cong\bigcup k^n$, and by induction $k^n$ and $k$ have the same cardinality, so $|k[x]|=\aleph_0\cdot|k|=|k|$; then show there is a surjection from $k[x]$ onto $E$, and an injection from $k$ into $E$. Conclude the wanted equality. (Note that this makes a heavy use of the axiom of choice, and indeed without the axiom of choice one might have a counterexample of an algebraic closure of the rational numbers which is not countable.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/604757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/60859/']}
jdg_84662
stackexchange
llm_judgeable_groundtruth_similarity
48739991
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 possible to change the inkbar color of the active tab? By default the ink bar is blue. See here for an example. I tried this in SCSS, but it doesn't work. .mat-tab-label-container{ .mat-tab-list{ .mat-ink-bar { background-color: green } }}.mat-tab-label-active{ color: green } Anyone can please help, Now provide the response and nothing else.
This could be similar to what you want to achieve Please see this link ( Cannot style mat-tab without ::ng-deep and !important ) and upvote if it helps you, I think this is similar to what you want to achieve. To answer your question You need to use Selector specificity and then put your style in the root style /src/styles.css (NOTE: that don't put it in the components styleUrls your style will not work) to style the ink bar .mat-tab-group.mat-primary .mat-ink-bar, .mat-tab-nav-bar.mat-primary .mat-ink-bar{ background: yellow; height: 10px;} Change ink-bar from underline to elliptical covering the item You can try this code to make it elliptical to cover the item. /* label style */.mat-tab-label{ background: #e7e7e7; color: black; min-width: 60px!important;}/* focus style */.mat-tab-group.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus, .mat-tab-group.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus, .mat-tab-nav-bar.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus, .mat-tab-nav-bar.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus{ background: #e7e7e7;}/* ink bar style */.mat-tab-group.mat-primary .mat-ink-bar, .mat-tab-nav-bar.mat-primary .mat-ink-bar{ background: rgba(149, 165, 166,0.3); height: 35px; border-radius: 100px; margin-bottom: 5px;} Please see the live sample here. https://stackblitz.com/edit/dmgrave-ng-so-anser-tabs-style?file=styles.css Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48739991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9243237/']}
jdg_84663
stackexchange
llm_judgeable_groundtruth_similarity
14715889
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 tried using multi_query but I keep getting a strict Standards message popping up. $querystring = "INSERT INTO responses VALUES('1', '2', '3', '4'); INSERT INTO responses VALUES('1', '2', '3', '4')";if (mysqli_multi_query($db, $querystring)) { do { if ($result = mysqli_store_result($db)) { // } } while (mysqli_next_result($db));}echo "end"; The error message I get is: Strict Standards : mysqli_next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method I've tried adding and removing -; but had no luck. Now provide the response and nothing else.
While pipodesign corrected the error within the $querystring and alleviated the problem, the actual solution was not provided regarding the Strict Standards error. I disagree with SirBT's advice, changing from DO WHILE to WHILE is not necessary. The Strict Standards message that you receive is quite informative.To obey, use this: do{} while(mysqli_more_results($db) && mysqli_next_result($db)); Then, there is no need for you to write a conditional exit or break inside of the loop because the while condition will break the loop on the first occurrence of an error. *note, the if statement before the do-while will deny entry to the loop if the first query has an error. In your example, you are only running INSERT queries, so you won't receive any result sets to process. If you want to count how many rows you've added, use mysqli_affected_rows(). As a complete solution for your question: if(mysqli_multi_query($db,$querystring)){ do{ $cumulative_rows+=mysqli_affected_rows($db); } while(mysqli_more_results($db) && mysqli_next_result($db));}if($error_mess=mysqli_error($db)){echo "Error: $error_mess";}echo "Cumulative Affected Rows: $cumulative_rows"; Output: // if no errorsCumulative Affected Rows: 2// if error on second queryError: [something]Cumulative Affected Rows: 1// if error on first queryError: [something]Cumulative Affected Rows: 0 LATE EDIT: Since people new to mysqli are stumbling across this post, I'll offer a general yet robust snippet to handle queries with/without result sets using multi_query() and add a feature to display which query in the array is being handled... Classic "IF(){DO{} WHILE}" Syntax : if(mysqli_multi_query($mysqli,implode(';',$queries))){ do{ echo "<br><br>",key($queries),": ",current($queries); // display key:value @ pointer if($result=mysqli_store_result($mysqli)){ // if a result set while($rows=mysqli_fetch_assoc($result)){ echo "<br>Col = {$rows["Col"]}"; } mysqli_free_result($result); } echo "<br>Rows = ",mysqli_affected_rows($mysqli); // acts like num_rows on SELECTs } while(next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli));}if($mysqli_error=mysqli_error($mysqli)){ echo "<br><br>",key($queries),": ",current($queries),"Syntax Error:<br>$mysqli_error"; // display array pointer key:value}//if you want to use the snippet again...$mysqli_error=null; // clear variablesreset($queries); // reset pointer Reinvented Wheel "WHILE{}" Syntax (...for those who don't like post-test loops): while((isset($multi_query) && (next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli))) || (!isset($multi_query) && $multi_query=mysqli_multi_query($mysqli,implode(';',$queries)))){ echo "<br><br>",key($queries),": ",current($queries); // display array pointer key:value if($result=mysqli_store_result($mysqli)){ while($rows=mysqli_fetch_assoc($result)){ echo "<br>Col = {$rows["Col"]}"; } mysqli_free_result($result); } echo "<br>Rows = ",mysqli_affected_rows($mysqli); // acts like num_rows on SELECTs}if($mysqli_error=mysqli_error($mysqli)){ echo "<br><br>",key($queries),": ",current($queries),"Syntax Error:<br>$mysqli_error"; // display array pointer key:value}//if you want to use the snippet again...$multi_query=$mysqli_error=null; // clear variablesreset($queries); // reset pointer So, either snippet given the following queries will offer the same output: Query array: $queries[]="SELECT * FROM `TEST`";$queries[]="INSERT INTO `TEST` (Col) VALUES ('string1'),('string2')";$queries[]="SELECT * FROM `TEST`";$queries[]="DELETE FROM `TEST` WHERE Col LIKE 'string%'"; Output: 0: SELECT * FROM `TEST`Rows = 01: INSERT INTO `TEST` (Col) VALUES ('string1'),('string2')Rows = 22: SELECT * FROM `TEST`Col = string1Col = string2Rows = 23: DELETE FROM `TEST` WHERE Col LIKE 'string%'Rows = 2 Modify my snippets per your needs. Leave a comment if you discover a bug.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14715889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2044498/']}
jdg_84664
stackexchange
llm_judgeable_groundtruth_similarity
16016003
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 following macro which plots a Scatter graph for three columns. One column (AL13, downwards) is on the x axis. How do I get it to plot the other two columns (AK and AM) onto the same scatter? Also in different colour to each other? Thank You Sub Graphing() Set rng4 = ActiveSheet.Range(Range("AP13"), Range("AV33"))With ActiveSheet.ChartObjects.Add(Left:=rng4.Left, Width:=rng4.Width, Top:=rng4.Top, Height:=rng4.Height) .Chart.ChartType = xlXYScatter .Chart.HasLegend = False .Chart.Axes(xlCategory).TickLabels.Font.Size = 18 .Chart.Axes(xlValue).TickLabels.Font.Size = 18 Set srs = .Chart.SeriesCollection.NewSeries srs.Values = Range(Range("AK13"), Range("AK13").End(xlDown)) srs.XValues = Range(Range("AL13"), Range("AL13").End(xlDown)) srs.Values = Range(Range("AM13"), Range("AM13").End(xlDown)) End WithEnd Sub Now provide the response and nothing else.
Your code is already working; a datetime.timedelta object is returned. To get the total number of seconds instead, you need to call the .total_seconds() method on the resulting timedelta : from django.utils.timezone import utcdef get_time_diff(self): if self.time_posted: now = datetime.datetime.utcnow().replace(tzinfo=utc) timediff = now - self.time_posted return timediff.total_seconds() .total_seconds() returns a float value, including microseconds. Note that you need to use a timezone aware datetime object, since the Django DateTimeField handles timezone aware datetime objects as well. See Django Timezones documentation . Demonstration of .total_seconds() (with naive datetime objects, but the principles are the same): >>> import datetime>>> time_posted = datetime.datetime(2013, 3, 31, 12, 55, 10)>>> timediff = datetime.datetime.now() - time_posted>>> timediff.total_seconds()1304529.299168 Because both objects are timezone aware (have a .tzinfo attribute that is not None ), calculations between them take care of timezones and subtracting one from the other will do the right thing when it comes to taking into account the timezones of either object.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16016003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/678878/']}
jdg_84665
stackexchange
llm_judgeable_groundtruth_similarity
5382164
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've been searching for hours on this error that appears in the output window. I'm pretty new to bindings in WPF, so I'm sure there's something I'm missing. Full text of the error (there is one for each binding path, all similar to this one): System.Windows.Data Error: 39 : BindingExpression path error: 'TestItem' property not found on 'object' ''String' (HashCode=-842352750)'. BindingExpression:Path=TestItem; DataItem='String' (HashCode=-842352750); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') EDIT: Everything seems to work as it should, but I get these errors in the output window. XAML: <UserControl> <UserControl.Resources> <c:MyData x:Key="myDataSource"/> <DataTemplate x:Key="image"> <Image x:Name="TheImage" /> <DataTemplate.Triggers> <DataTrigger Binding="{Binding Path=PassFail}" Value="PASS"> <Setter TargetName="TheImage" Property="Source" Value="Images/accept.png" /> </DataTrigger> <DataTrigger Binding="{Binding Path=PassFail}" Value="FAIL"> <Setter TargetName="TheImage" Property="Source" Value="Images/delete.png" /> </DataTrigger> <DataTrigger Binding="{Binding Path=PassFail}" Value="WARNING"> <Setter TargetName="TheImage" Property="Source" Value="Images/warning.png" /> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> <Storyboard x:Key="OnMouseLeftButtonDown1"/> </UserControl.Resources> <UserControl.DataContext> <Binding Source="{StaticResource myDataSource}"/> </UserControl.DataContext> <ListView Margin="0,94,-4,-7" x:Name="lsvwOutput" ItemsSource="{Binding Source={StaticResource myDataSource}}" MouseUp="lsvwOutput_MouseUp" FontFamily="Verdana"> <ListView.View> <GridView> <GridViewColumn Header="Test Item" Width="300" DisplayMemberBinding="{Binding Path=TestItem}" /> <GridViewColumn Header="Information" Width="0" DisplayMemberBinding="{Binding Path=Information}"/> <GridViewColumn Header="Result" Width="0" DisplayMemberBinding="{Binding Path=PassFail}"/> <GridViewColumn Header="Result" CellTemplate="{StaticResource image}" /> </GridView> </ListView.View> </ListView</UserControl> Code behind: public class MyData : INotifyPropertyChanged{ private string _testitem = ""; private string _information = ""; private string _passfail = ""; public string TestItem { get { return _testitem; } set { _testitem = value; OnPropertyChanged("TestItem"); } } public string Information { get { return _information; } set { _information = value; OnPropertyChanged("Information"); } } public string PassFail { get { return _passfail; } set { _passfail = value; OnPropertyChanged("PassFail"); } } public string Text { get; set; } Now provide the response and nothing else.
You don't want to set the DataContext on the UserControl. Instead, you want to set it in the scope of the UserControl. Usually you do this in the constructor of the UserControl. I usually add a line like this: this.RootElement.DataContext = myData; Where RootElement is the first sub-element (the Content) of your UserControl (usually a panel like Grid or StackPanel). In your case it would be: this.lsvwOutput.DataContext = FindResource("myDataSource") ; And makes sure that it's after the InitializeComponent() call. It's just a question of scoping. You set the datacontext on the root panel of the usercontrol. This is a really non-obvious part of WPF. UPDATE: As Markus points out below, in the case of a listview, you want to set an array of data, not just a data point. Take that into consideration when setting the DataContext in your constructor.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5382164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259403/']}
jdg_84666
stackexchange
llm_judgeable_groundtruth_similarity
16965
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Recursion utilizes some self similar nature of an object (some representation of the given problem) to produce some quantitative measure (output) on the object through some algorithm (utilizing the self similar nature). Can one represent algorithms as fractals (such a representation is not possible is not obvious nor how the representation should be if one exists) of some measurable information of the object the algorithm works on? Has the tools used in the study of fractals provided any illuminating examples for lower or upper bounds for recursive complexity of algorithms? I am looking for examples and references along the lines of whether algorithms can be treated as fractals and tools about fractals can be used to prove results about algorithms. just added Would we be compelled to redefine some essential property of Sierpinski triangle if Walsh Transform or Sierpinski triangle transform is shown to be fully linear? http://en.wikipedia.org/wiki/Walsh_matrix Now provide the response and nothing else.
Blum, Shub, and Smale proved that membership in the Mandelbrot set is undecidable in the Real RAM model of computation (known in some upstart circles as the BSS model ). The high-level argument is one sentence long: Any Real RAM computable set is the countable union of semi-algebraic sets, so its boundary has Hausdorff dimension 1, but the boundary of the Mandelbrot set has Hausdorff dimension 2. By the same argument, almost every interesting fractal is uncomputable in the real-RAM model.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/16965', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1812/']}
jdg_84667
stackexchange
llm_judgeable_groundtruth_similarity
40066166
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 know this question has been asked many times, but I tried pretty much everything I could find on the net and still can't get the text to render properly in canvas no matter what (and with whatever combinations) I tried. For the blurry lines and shapes problem, simply adding +0.5px to the coordinates solved the problem : however, this solution doesn't seem to work for text rendering. Note : I never use CSS to set canvas width and height (just tried it once to check if setting size properties in both HTML and CSS would change anything). Also problem doesn't seem to be browser-related. I tried : creating canvas with HTML, then with javascript instead of html setting width and height in HTML element, then with JS, then with both HTML and JS add 0.5px to text coordinates with every possible combination changing font-family and font-size changing font-size unit (px, pt, em) opening file with different browsers to check if anything changes disabling alpha channel using canvas.getContext('2d', {alpha:false}) which just made most of my layers disapear without solving the problem See comparison between canvas and html font rendering here : https://jsfiddle.net/balleronde/1e9a5xbf/ Is it even possible to get the text in canvas to render like text in dom element ? Any advice or suggestion would be greatly appreciated Now provide the response and nothing else.
DOM quality text on the Canvas. A closer look If you zoom in on the DOM text you will see the following (top is canvas, bottom is DOM, center is hopefully at pixel size (not on retina displays)) As you can see there are coloured sections on the bottom text. This is because it has been rendered using a technique called true type Note using true type is an optional setting on browsers and operating systems. If you have it turned off or have a very low res device the zoomed text above will look the same (no coloured pixels in the bottom image) Pixels and sub pixels When you look closely at a LCD display you will see that each pixel is made up of 3 sub pixels arranged in a row, one each for red, green, and blue. To set a pixel you supply the RGB intensity for each colour channel, and the appropriate RGB sub pixels are set. We generally accept that red is first and blue last, but the reality is it does not matter what order the colours are as long as they are close to each other you get the same result. When you stop thinking about colour and just about controllable image elements you triple the horizontal resolution of your device. As most text is monochromatic you don't have to worry too much about the alignment of the RGB subpixels and you can render the text to the sub pixel rather than the whole pixel and thus get high quality text. The sub pixels are so small most people do not notice the slight colour distortions, and the benefit is well worth the slightly dirty look. Why no true type for canvas When using sub pixels you need to have full control of each, including the alpha value. For the display drivers alpha applies to all the sub pixels of a pixel, you can not have blue at alpha 0.2 and red on the same pixel at alpha 0.7. But if you know what the sub pixel values are under each sub pixel you can do the alpha calculations instead of letting the hardware do it. That gives you algha control at a sub pixel level. Unfortunately (no... fortunate for 99.99% of cases) the canvas allows transparency, but you have no way of knowing what the sub pixels under the canvas are doing, they can be any colour, and hence you can not do the alpha calculations needed to use sub pixels effectively. Home grown subpixel text. But you don't have to have a transparent canvas and if you make all your pixels non transparent (alpha = 1.0) you regain sub pixel alpha control. The following function draws canvas text using sub pixels. It is not very fast but it does get better quality text. It works by rendering the text at 3 times the normal width. Then it uses the extra pixels to calculate the sub pixel values and when done puts the sub pixel data onto the canvas. Update When I wrote this answer I totaly forgot about zoom settings. Using sub pixels requiers a presise match between display physical pixel size and DOM pixel size. If you have zoomed in or out this will not be so and thus locating sub pixels becomes much more difficult. I have updated the demos to try to detect the zoom settings. As there is not standard way to do this I have just used devicePixelRatio which for FF and Chrome are !== 1 when zoomed (And as I dont have a retina decvice I am only guessing if the bottom demo works). If you wish to see the demo correctly and you do not get a zoom warning though are still zoomed set the zoom to 1. Addistionaly you may wish to set the zoom to 200% and use the bottom demo as it seems that zooming in reduces the DOM text quality considerably, while the canvas sub pixel maintains the high quality. Top text is normal Canvas text, center is (home made) sub pixel text on canvas and bottom is DOM text PLEASE note if you have Retina Display or a very high resolution display you should view the snippet below this one if you do not see high quality canvas text. Standard 1 to 1 pixel demo. var createCanvas =function(w,h){ var c = document.createElement("canvas"); c.width = w; c.height = h; c.ctx = c.getContext("2d"); // document.body.appendChild(c); return c;}// converts pixel data into sub pixel datavar subPixelBitmap = function(imgData){ var spR,spG,spB; // sub pixels var id,id1; // pixel indexes var w = imgData.width; var h = imgData.height; var d = imgData.data; var x,y; var ww = w*4; var ww4 = ww+4; for(y = 0; y < h; y+=1){ for(x = 0; x < w; x+=3){ var id = y*ww+x*4; var id1 = Math.floor(y)*ww+Math.floor(x/3)*4; spR = Math.sqrt(d[id + 0] * d[id + 0] * 0.2126 + d[id + 1] * d[id + 1] * 0.7152 + d[id + 2] * d[id + 2] * 0.0722); id += 4; spG = Math.sqrt(d[id + 0] * d[id + 0] * 0.2126 + d[id + 1] * d[id + 1] * 0.7152 + d[id + 2] * d[id + 2] * 0.0722); id += 4; spB = Math.sqrt(d[id + 0] * d[id + 0] * 0.2126 + d[id + 1] * d[id + 1] * 0.7152 + d[id + 2] * d[id + 2] * 0.0722); d[id1++] = spR; d[id1++] = spG; d[id1++] = spB; d[id1++] = 255; // alpha always 255 } } return imgData;}// Assume default textBaseline and that text area is contained within the canvas (no bits hanging out)// Also this will not work is any pixels are at all transparentvar subPixelText = function(ctx,text,x,y,fontHeight){ var width = ctx.measureText(text).width + 12; // add some extra pixels var hOffset = Math.floor(fontHeight *0.7); var c = createCanvas(width * 3,fontHeight); c.ctx.font = ctx.font; c.ctx.fillStyle = ctx.fillStyle; c.ctx.fontAlign = "left"; c.ctx.setTransform(3,0,0,1,0,0); // scale by 3 // turn of smoothing c.ctx.imageSmoothingEnabled = false; c.ctx.mozImageSmoothingEnabled = false; // copy existing pixels to new canvas c.ctx.drawImage(ctx.canvas,x -2, y - hOffset, width,fontHeight,0,0, width,fontHeight ); c.ctx.fillText(text,0,hOffset); // draw thw text 3 time the width // convert to sub pixel c.ctx.putImageData(subPixelBitmap(c.ctx.getImageData(0,0,width*3,fontHeight)),0,0); ctx.drawImage(c,0,0,width-1,fontHeight,x,y-hOffset,width-1,fontHeight); // done}var globalTime;// render loop does the drawingfunction update(timer) { // Main update loop globalTime = timer; ctx.setTransform(1,0,0,1,0,0); // set default ctx.globalAlpha= 1; ctx.fillStyle = "White"; ctx.fillRect(0,0,canvas.width,canvas.height) ctx.fillStyle = "black"; ctx.fillText("Canvas text is Oh hum "+ globalTime.toFixed(0),6,20); subPixelText(ctx,"Sub pixel text is best "+ globalTime.toFixed(0),6,45,25); div.textContent = "DOM is off course perfect "+ globalTime.toFixed(0); requestAnimationFrame(update);}function start(){ document.body.appendChild(canvas); document.body.appendChild(div); ctx.font = "20px Arial"; requestAnimationFrame(update); // start the render}var canvas = createCanvas(512,50); // create and add canvasvar ctx = canvas.ctx; // get a global contextvar div = document.createElement("div");div.style.font = "20px Arial";div.style.background = "white";div.style.color = "black";if(devicePixelRatio !== 1){ var dir = "in" var more = ""; if(devicePixelRatio > 1){ dir = "out"; } if(devicePixelRatio === 2){ div.textContent = "Detected a zoom of 2. You may have a Retina display or zoomed in 200%. Please use the snippet below this one to view this demo correctly as it requiers a precise match between DOM pixel size and display physical pixel size. If you wish to see the demo anyways just click this text. "; more = "Use the demo below this one." }else{ div.textContent = "Sorry your browser is zoomed "+dir+".This will not work when DOM pixels and Display physical pixel sizes do not match. If you wish to see the demo anyways just click this text."; more = "Sub pixel display does not work."; } document.body.appendChild(div); div.style.cursor = "pointer"; div.title = "Click to start the demo."; div.addEventListener("click",function(){ start(); var divW = document.createElement("div"); divW.textContent = "Warning pixel sizes do not match. " + more; divW.style.color = "red"; document.body.appendChild(divW); });}else{ start();} 1 to 2 pixel ratio demo. For retina, very high resolution, or zoomed 200% browsers. var createCanvas =function(w,h){ var c = document.createElement("canvas"); c.width = w; c.height = h; c.ctx = c.getContext("2d"); // document.body.appendChild(c); return c;}// converts pixel data into sub pixel datavar subPixelBitmap = function(imgData){ var spR,spG,spB; // sub pixels var id,id1; // pixel indexes var w = imgData.width; var h = imgData.height; var d = imgData.data; var x,y; var ww = w*4; var ww4 = ww+4; for(y = 0; y < h; y+=1){ for(x = 0; x < w; x+=3){ var id = y*ww+x*4; var id1 = Math.floor(y)*ww+Math.floor(x/3)*4; spR = Math.sqrt(d[id + 0] * d[id + 0] * 0.2126 + d[id + 1] * d[id + 1] * 0.7152 + d[id + 2] * d[id + 2] * 0.0722); id += 4; spG = Math.sqrt(d[id + 0] * d[id + 0] * 0.2126 + d[id + 1] * d[id + 1] * 0.7152 + d[id + 2] * d[id + 2] * 0.0722); id += 4; spB = Math.sqrt(d[id + 0] * d[id + 0] * 0.2126 + d[id + 1] * d[id + 1] * 0.7152 + d[id + 2] * d[id + 2] * 0.0722); d[id1++] = spR; d[id1++] = spG; d[id1++] = spB; d[id1++] = 255; // alpha always 255 } } return imgData;}// Assume default textBaseline and that text area is contained within the canvas (no bits hanging out)// Also this will not work is any pixels are at all transparentvar subPixelText = function(ctx,text,x,y,fontHeight){ var width = ctx.measureText(text).width + 12; // add some extra pixels var hOffset = Math.floor(fontHeight *0.7); var c = createCanvas(width * 3,fontHeight); c.ctx.font = ctx.font; c.ctx.fillStyle = ctx.fillStyle; c.ctx.fontAlign = "left"; c.ctx.setTransform(3,0,0,1,0,0); // scale by 3 // turn of smoothing c.ctx.imageSmoothingEnabled = false; c.ctx.mozImageSmoothingEnabled = false; // copy existing pixels to new canvas c.ctx.drawImage(ctx.canvas,x -2, y - hOffset, width,fontHeight,0,0, width,fontHeight ); c.ctx.fillText(text,0,hOffset); // draw thw text 3 time the width // convert to sub pixel c.ctx.putImageData(subPixelBitmap(c.ctx.getImageData(0,0,width*3,fontHeight)),0,0); ctx.drawImage(c,0,0,width-1,fontHeight,x,y-hOffset,width-1,fontHeight); // done}var globalTime;// render loop does the drawingfunction update(timer) { // Main update loop globalTime = timer; ctx.setTransform(1,0,0,1,0,0); // set default ctx.globalAlpha= 1; ctx.fillStyle = "White"; ctx.fillRect(0,0,canvas.width,canvas.height) ctx.fillStyle = "black"; ctx.fillText("Normal text is Oh hum "+ globalTime.toFixed(0),12,40); subPixelText(ctx,"Sub pixel text is best "+ globalTime.toFixed(0),12,90,50); div.textContent = "DOM is off course perfect "+ globalTime.toFixed(0); requestAnimationFrame(update);}var canvas = createCanvas(1024,100); // create and add canvascanvas.style.width = "512px";canvas.style.height = "50px";var ctx = canvas.ctx; // get a global contextvar div = document.createElement("div");div.style.font = "20px Arial";div.style.background = "white";div.style.color = "black";function start(){ document.body.appendChild(canvas); document.body.appendChild(div); ctx.font = "40px Arial"; requestAnimationFrame(update); // start the render}if(devicePixelRatio !== 2){ var dir = "in" var more = ""; div.textContent = "Incorrect pixel size detected. Requiers zoom of 2. See the answer for more information. If you wish to see the demo anyways just click this text. "; document.body.appendChild(div); div.style.cursor = "pointer"; div.title = "Click to start the demo."; div.addEventListener("click",function(){ start(); var divW = document.createElement("div"); divW.textContent = "Warning pixel sizes do not match. "; divW.style.color = "red"; document.body.appendChild(divW); });}else{ start();} For even better results. To get the best results you will need to use webGL. It is a relatively simple modification from standard anti-aliasing to sub pixel anti-aliasing. An example of standard vector text rendering using webGL can be found at WebGL PDF WebGL API will happily sit besides 2D canvas API and copying the result of webGl rendered content to a 2D canvas is as simple as rendering an image context.drawImage(canvasWebGL,0,0)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40066166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6937077/']}
jdg_84668
stackexchange
llm_judgeable_groundtruth_similarity
48968243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: MvvmCross.Droid.Support.v7.AppCompat 5.6.3 Depends on Xamarin.Android.Support.v7.AppCompat (>=25.3.1) Xamarin.Android.Support.v7.AppCompat 26.1.0.1 Depends on MonoAndroid, Version= v8.0 MvvmCross.Plugin.Location.Fused 5.6.3 Depends on MonoAndroid,Version= v0.0 Question: How can I use both MvvmCross.Droid.Support.v7.AppCompat 5.6.3 and MvvmCross.Plugin.Location.Fused 5.6.3 in the same project when they depend on different versions of MonoAndroid? Thanx, Marc Now provide the response and nothing else.
Default height for bottomSheet is half the screenSize If you want your bottomSheet to EXPAND according to your content DYNAMICALLY use below code showModalBottomSheet<dynamic>(isScrollControlled: true,context: context,builder: (BuildContext bc) { return Wrap( children: <Widget>[...] ) }) This will automatically expand the bottomSheet according to content inside. For adding a radius on top of bottomSheet return below code to `bottomSheet' Container( child: Container( decoration: new BoxDecoration( color: forDialog ? Color(0xFF737373) : Colors.white, borderRadius: new BorderRadius.only( topLeft: const Radius.circular(25.0), topRight: const Radius.circular(25.0))), child: yourWidget(), ),) Complete code meeting both requirements showModalBottomSheet<dynamic>(isScrollControlled: true,context: context,builder: (BuildContext bc) { return Wrap( children: <Widget>[ Container( child: Container( decoration: new BoxDecoration( color: forDialog ? Color(0xFF737373) : Colors.white, borderRadius: new BorderRadius.only( topLeft: const Radius.circular(25.0), topRight: const Radius.circular(25.0))), child: yourWidget(), ), ) ] ) })
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48968243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5578991/']}
jdg_84669
stackexchange
llm_judgeable_groundtruth_similarity
30953299
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For pandas , I'm looking for a way to write conditional values to each row in column B, based on substrings for corresponding rows in column A. So if cell in A contains "BULL" , write "Long" to B . Or if cell in A contains "BEAR" , write "Short" to B . Desired output: A B"BULL APPLE X5" "Long""BEAR APPLE X5" "Short""BULL APPLE X5" "Long" B is initially empty: df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']],columns=['A','B']) Now provide the response and nothing else.
Your code would error as you creating the Dataframe incorrectly, just create a single column A then add B based on A : import pandas as pddf = pd.DataFrame(["BULL","BEAR","BULL"], columns=['A'])df["B"] = ["Long" if ele == "BULL" else "Short" for ele in df["A"]]print(df) A B0 BULL Long1 BEAR Short2 BULL Long Or do you logic with the data before you create the dataframe: import pandas as pddata = ["BULL","BEAR","BULL"]data2 = ["Long" if ele == "BULL" else "Short" for ele in data]df = pd.DataFrame(list(zip(data, data2)), columns=['A','B'])print(df) A B 0 BULL Long 1 BEAR Short 2 BULL Long For your edit: df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']], columns=['A','B'])df["B"] = df["A"].map(lambda x: "Long" if "BULL" in x else "Short" if "BEAR" in x else "")print(df) A B0 BULL APPLE X5 Long1 BEAR APPLE X5 Short2 BULL APPLE X5 Long Or just add the column after: df = pd.DataFrame(['BULL APPLE X5','BEAR APPLE X5','BLL APPLE X5'], columns=['A'])df["B"] = df["A"].map(lambda x: "Long" if "BULL" in x else "Short" if "BEAR" in x else "")print(df) Or using contains: df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']], columns=['A','B'])df["B"][df['A'].str.contains("BULL")] = "Long"df["B"][df['A'].str.contains("BEAR")] = "Short"print(df)0 BULL APPLE X5 Long1 BEAR APPLE X5 Short2 BULL APPLE X5 Long
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30953299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4909923/']}
jdg_84670
stackexchange
llm_judgeable_groundtruth_similarity
1489422
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 string that contains well formed xml in it. I want to navigate the XML in that string to extract the text in certain nodes. How do I efficiently accomplish this using a built-in .NET class. Which .NET XML class would you use and why? Many thanks for your help. Note 1: Linq is not available to me.Note 2: Editing the XML is not important. Read-only access is what I need. Now provide the response and nothing else.
For speed, use an XmlReader : using (StringReader sr = new StringReader(myString))using (XmlReader xr = XmlReader.Create(sr)){ while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && xr.Name == "foo") { Console.WriteLine(xr.ReadString()); } }} The above prints out the text content of every element named "foo" in the XML document. (Well, sort of. ReadString doesn't handle nested elements very gracefully.) Using an XPathDocument is slower, because the entire document gets parsed before you can start searching it, but it has the merit of simplicity: using (StringReader sr = new StringReader(myString)){ XPathDocument d = new XPathDocument(sr); foreach (XPathNavigator n in d.CreateNavigator().Select("//foo/text()")) { Console.WriteLine(n.Value); }} If you're not concerned with performance or memory utilization, it's simplest to use an XmlDocument : XmlDocument d = new XmlDocument();d.LoadXml(myString);foreach (XmlNode n in d.SelectNodes("//foo/text()")){ Console.WriteLine(n.Value);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1489422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49881/']}
jdg_84671
stackexchange
llm_judgeable_groundtruth_similarity
103846
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get the total size of files satisfying a find , e.g.: ls $(find -maxdepth 2 -type f) However, this kind of invocation of ls does not produce the total size as well. Now provide the response and nothing else.
Believe it or not you can do this with find and du . I used a similar technique that I wrote up on my blog a while a go. That article is titled: [one-liner]: Calculating Disk Space Usage for a List of Files Using du under Linux . The gist of that post is a command such as this: $ find -maxdepth 2 -type f | tr '\n' '\0' | du -ch --files0-from=- Example This will list the size of all the files along with a summary total. $ find -maxdepth 2 -type f | tr '\n' '\0' | du -ch --files0-from=- | tail -100 ./92086/2.txt0 ./92086/5.txt0 ./92086/14.txt0 ./92086/19.txt0 ./92086/18.txt0 ./92086/17.txt4.0K ./load.bash4.0K ./100855/plain.txt4.0K ./100855/tst_ccmds.bash21M total NOTE: This solution requires that du support the --files0-from= switch which is a GNU switch, to my knowledge. excerpt from du man page --files0-from=F summarize disk usage of the NUL-terminated file names specified in file F; If F is - then read names from standard input Also this method suffers from not being able to deal with special characters in file names, such as spaces and non-printables. Examples du: cannot access `./101415/fileD': No such file or directorydu: cannot access `E': No such file or directory These could be dealt with by introducing more tr .. .. commands to substitute them with alternative characters. However there is a better way, if you have access to GNU's find . Improvements If your version of find offers the --print0 switch then you can use this incantation which deals with files that have spaces and/or special characters that aren't printable. $ find -maxdepth 2 -type f -print0 | du -ch --files0-from=- | tail -100 ./92086/2.txt0 ./92086/5.txt0 ./92086/14.txt0 ./92086/19.txt0 ./92086/18.txt0 ./92086/17.txt4.0K ./load.bash4.0K ./100855/plain.txt4.0K ./100855/tst_ccmds.bash21M total
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/103846', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/24044/']}
jdg_84672
stackexchange
llm_judgeable_groundtruth_similarity
209633
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm running OpenBSD 5.7 on VirtualBox on my Windows 7, to learn more about Unix, but I can't use sudo with my password. I've set up a user called adminvpn but when I try to run any command using sudo it tells that my password is wrong! I have already tried my root password and my user password and I'm 100% sure they are correct and they are only letters... I have reinstalled OpenBSD 3 times and this is driving me crazy. When I try to use my password for "adminvpn" I get adminvpn is not in the sudoers file. This incident will be reported. I'm able to log in with root and using my root password. I'm almost giving up to running it with a user. Now provide the response and nothing else.
The error message tells you what is wrong even if it doesn't tell you exactly how to fix it. adminvpn is not in the sudoers file. sudo lets you run commands as the administrator. In order to be able to use sudo, you need to be made an administrator. Accounts are not made administrators by default. Run the command visudo (as root, of course) and add a line like the following: adminvpn ALL=(ALL) ALL Save the file and exit. You can now run any command as root with sudo . Note that visudo will run your favorite editor, as indicated by the environment variable VISUAL . If you haven't configured that, you'll get vi. If you're uncomfortable with vi, install another editor (e.g. pkg_add nano ) and add a line like export VISUAL=nano to ~/.profile ; run the command in your interactive shell as well for it to take effect in the current session. Unless configured otherwise, sudo requires you to type your own password. Knowledge of the root password is not necessary, that's the point of sudo . The point of typing your password is to make sure it isn't someone else typing while you left your keyboard unattended. By the way, OpenBSD isn't the most beginner-friendly Unix out there. If you want a gentler learning curve, try Ubuntu.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/209633', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/119404/']}
jdg_84673
stackexchange
llm_judgeable_groundtruth_similarity
49296
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 would seem logical that the more times an event does not happen, the more likely it is to happen, for example: If a coin is flipped and it lands on tails 10 times in a row it would seam more likely that the next flip will result in heads. The Infinite Monkey Theorem is one such idea that suggests this is true, http://en.wikipedia.org/wiki/Infinite_monkey_theorem It states that if some number of monkeys are left in a room with typewriters for an infinite amount of time then they will eventually compose all written texts ever produced. This seems to suggest that since the chance of the monkeys writing a work, say Shakespeare's Romeo and Juliet , is very low. The more times they do not write it, the more likely they are to write it, until the chance becomes significant and it, the writing of the play, happens. However another idea, Gambler's Fallacy states quite the opposite. http://en.wikipedia.org/wiki/Gambler%27s_fallacy It states that the chance of an event does not increase with the number of times it does not occur. So what is the answer? Does the likelihood of an event go up the more times it does not happen, or does it stay the same? And if it does stay the same then how does one explain the Infinite Monkey Theorem? Now provide the response and nothing else.
The Infinite Monkey Theorem (I didn't know it was a theorem!) basically says that a given finite string of text will appear with probability 1 in an infinite truly random string of text. What it means to be "truly random" is the delicate point. Anyway, in practice, you cannot produce an infinite string of text "at once" but what you can do (employing monkeys, tossing dice, or instructing your laptop) is to print out a random sequence of letters of increasing, albeit finite, length. As the length increases, so does the probability to find a precise string embedded in that sequence, and this may give the false impression that the chance of producing it improves, because of previous "failures". In fact it is not so, as the Gambler's Fallacy says. If a perfect coin ("perfect" meaning that "head" has exactly a 50% chance) is tossed ten times and you get "head" ten times, "head" has still a 50% chance at the eleventh toss. Believing the opposite, namely that the chance of getting another "head" is lower than 50%, would be equivalent to believing that the coin has some sort of "internal mechanism" that remembers the past flippings, which is rather absurd.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/49296', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12917/']}
jdg_84674
stackexchange
llm_judgeable_groundtruth_similarity
40976031
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In this code snippet , why is it that this.identifier doesn't work but _self.url works? getConfig() { let _self = this; return function () { this.page.url = this.url || window.location.href; this.page.identifier = _self.identifier; this.page.category_id = this.categoryId; this.language = this.lang; };} So does let _self = this actually do? Now provide the response and nothing else.
Functions have something called a context. A context is the object the function is being called on. let person = { name:"bill", speak:function(){ console.log("hi i am "+this.name) }} if you were to do person.speak() it will be called on the object that was defined. The variable person is the context so when you say this. it's the same as saying person.name Now you can attach the function to something else. var newperson = {name:'jill'}newperson.speak = person.speak; this will print hi i am jill when it's called. Now on to step two. GetConfig returns a function, however this function is not attached any object. Check this out. let person = { name:"bill", getSpeakFunction:function(){ return function(){ console.log('hi my name is '+this.name) } }}let func = person.getSpeakFunction() Now the function func is all by himself. Now when it is called who is this who the hell are you talking about.That is what the function is thinking. So we can help the function out by saying. let person = { name:"bill", getSpeakFunction:function(){ let context = this; //listen hear function this is what i am talking about return function(){ console.log('hi my name is '+context.name) } }}let func = person.getSpeakFunction() this is special the language decides the value of this, however context is not. Context will be whatever is assigned to it. It will not change unless you the programmer changes it. so using the word _self , context , $this or anything else when you assign the value of this to it.it is 'locked in place' like any other regular variable. let a = 2;//this will never changelet _self = this //_self will never change as it's your variable Now when you call your function and it looks for _self . It knows exactly what you are talking about.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40976031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3073280/']}
jdg_84675
stackexchange
llm_judgeable_groundtruth_similarity
4605419
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 have SOAP and RESTful in the same WCF service. I have ahieved it as well apart from one issue. Following is my web.config: <service behaviorConfiguration="webBehaviour" name="MyServices"> <clear /> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" name="basicHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="ws" binding="wsHttpBinding" bindingConfiguration="WsHttp" name="wsHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="web" binding="webHttpBinding" bindingConfiguration="WebHttp" behaviorConfiguration="webBehavior" name="webHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="json" binding="webHttpBinding" bindingConfiguration="WebHttp" behaviorConfiguration="webJSONBehavior" name="webJSONHttpBinding" contract="DJSharedServices.ISharedServices" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" name="mexBinding" /> </service> </services> When I have all the endpoints it gives the following error: An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:System.NullReferenceException: Object reference not set to an instance of an object. at System.ServiceModel.Description.WsdlExporter.CreateWsdlBindingAndPort(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName, Port& wsdlPort, Boolean& newBinding, Boolean& bindingNameWasUniquified) at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName) at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName) at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata() at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized() at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension) at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData() at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage) at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest) at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message) at SyncInvokeGet(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) Things work fine if I comment out json end point. Can you please help me finding out why?? Thanks in advance. Now provide the response and nothing else.
well I just added changed the binding configuration for json behaviour. I was using same binging configuration for JSON and POX. Now I have changed the configuration to: <service behaviorConfiguration="WebBehaviour" name="MyServices"> <clear /> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" name="basicHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="ws" binding="wsHttpBinding" bindingConfiguration="WsHttp" name="wsHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="web" binding="webHttpBinding" bindingConfiguration="WebHttp" behaviorConfiguration="webBehavior" name="webHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="json" binding="webHttpBinding" bindingConfiguration="WebjsonHttp" behaviorConfiguration="webJSONBehavior" name="webJSONHttpBinding" contract="DJSharedServices.IMyServices" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" name="mexBinding" /> </service> and added binding configuration: <webHttpBinding> <binding name="WebHttp" > <security mode="None"></security> </binding> <binding name="WebjsonHttp" > <security mode="None"></security> </binding> </webHttpBinding>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4605419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2030479/']}
jdg_84676
stackexchange
llm_judgeable_groundtruth_similarity
39798042
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 app wherein I am looking to take user input in the "ui" file and use that information to update a dataframe in the "server" file. The following is a simplified version of what the code looks like: Dataframe <- readRDS(Dataframe.rds)Table <- readRDS(Table.rds) ui <- fluidPage( selectInput("Location","Location", unique(as.character(Table$Locations)), multiple = TRUE) )server <- function(input,output) { Dataframe2 <- Dataframe %>% select(get(input$Location)) } The above code works if I do not use the "multiple = TRUE" option for selectInput, meaning that the Dataframe2 object only selects the column that matches with the single input that the user has chosen. However, I do not know how I can do the same thing for multiple inputs, when the choices could vary from only 1 item being passed on from selectInput up to 10 items in total. Now provide the response and nothing else.
If I understood your question correctly this is an example with multiple selection using the mtcars data frame: library(shiny)library(dplyr)data(mtcars)ui <- fluidPage( titlePanel("MTCARS"), selectInput("Columns","Columns", names(mtcars), multiple = TRUE), verbatimTextOutput("dfStr"))server <- function(input, output) { Dataframe2 <- reactive({ mtcars[,input$Columns] }) output$dfStr <- renderPrint({ str(Dataframe2()) })}shinyApp(ui, server)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39798042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3974784/']}
jdg_84677
stackexchange
llm_judgeable_groundtruth_similarity
39665299
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 having a hard time understanding quicksort, most of the demonstrations and explanations leave out what actually happens ( http://me.dt.in.th/page/Quicksort/ for example). Wikipedia says: Pick an element, called a pivot, from the array. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values. How would that work with an array of 9,1,7,8,8 for example with 7 as the pivot? The 9 needs to move to the right of the pivot, all quicksort implementations are in place operations it seems so we can't add it after the 8,8, so the only option is to swap the 9 with the 7. Now the array is 7,1,9,8,8. The idea behind quicksort is that now we have to recursively sort the parts to the left and right of the pivot. The pivot is now at position 0 of the array, meaning there's no left part, so we can only sort the right part. This is of no use as 7>1 so the pivot ended up in the wrong place. In this image 4 is the pivot, then why is 5 going almost all the way to the left? It's bigger than 4! After a lot of swapping it ends up being sorted but I don't understand how that happened. Now provide the response and nothing else.
Quicksort The Quicksort steps are: Pick an element, called a pivot, from the list. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation . Recursively sort the sub-list of lesser elements and the sub-list of greater elements.The base case of the recursion are lists of size zero or one, which never need to be sorted. Lomuto partition scheme This scheme chooses a pivot which is typically the last element inthe array. The algorithm maintains the index to put the pivot in variable i and each time it finds an element less than or equal to pivot, thisindex is incremented and that element would be placed before thepivot. As this scheme is more compact and easy to understand, it is frequently used in introductory material. Is less efficient than Hoare's original scheme. Partition algorithm (using Lomuto partition scheme) algorithm partition(A, lo, hi) is pivot := A[hi] i := lo // place for swapping for j := lo to hi – 1 do if A[j] ≤ pivot then swap A[i] with A[j] i := i + 1 swap A[i] with A[hi] return i Quicksort algorithm (using Lomuto partition scheme) algorithm quicksort(A, lo, hi) is if lo < hi then p := partition(A, lo, hi) quicksort(A, lo, p – 1) quicksort(A, p + 1, hi) Hoare partition scheme Uses two indices that start at the ends of the array beingpartitioned, then move toward each other, until they detect aninversion: a pair of elements, one greater than the pivot, onesmaller, that are in the wrong order relative to each other. Theinverted elements are then swapped. There are many variants of this algorithm, for example, selecting pivot from A[hi] instead of A[lo] partition algorithm (using Hoare partition scheme) algorithm partition(A, lo, hi) is pivot := A[lo] i := lo – 1 j := hi + 1 loop forever do i := i + 1 while A[i] < pivot do j := j – 1 while A[j] > pivot if i >= j then return j swap A[i] with A[j] quicksort algorithm(using Hoare partition scheme) algorithm quicksort(A, lo, hi) is if lo < hi then p := partition(A, lo, hi) quicksort(A, lo, p) quicksort(A, p + 1, hi) Hoare partition scheme vs Lomuto partition scheme The pivot selection The execution speed of the algorithm depends largely on how this mechanism is implemented, poor implementation can assume that the algorithm is run at a slow speed. The choice of pivot determines partitions the data list, therefore, this is the most critical part of the implementation of the Quicksort algorithm. It is important to try that selecting the pivot left and right partitions have an identical size as much as possible . Best and worst case Worst case The most unbalanced partition occurs when the pivot divides the list into two sublists of sizes _0 and n − 1 . This may occur if the pivot happens to be the smallest or largest element in the list, or in some implementations when all the elements are equal. Best Case In the most balanced case, each time we perform a partition we divide the list into two nearly equal pieces. This means each recursive call processes a list of half the size. Formal analysis Worst-case analysis = O(n²) Best-case analysis = O(n) factor Average-case analysis = O(n log n) Examples source Using additional memory def quicksort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) return sort(less)+equal+sort(greater) else: return array Usage: quicksort([12,4,5,6,7,3,1,15]) Without additional memory def partition(array, begin, end): pivot = begin for i in xrange(begin+1, end+1): if array[i] <= array[begin]: pivot += 1 array[i], array[pivot] = array[pivot], array[i] array[pivot], array[begin] = array[begin], array[pivot] return pivotdef quicksort(array, begin=0, end=None): if end is None: end = len(array) - 1 if begin >= end: return pivot = partition(array, begin, end) quicksort(array, begin, pivot-1) quicksort(array, pivot+1, end) Usage: quicksort([97, 200, 100, 101, 211, 107]) In your example Debug Lomuto partition References: http://www.cs.bilkent.edu.tr/~atat/473/lecture05.pdf http://codefap.com/2012/08/the-quick-sort-algorithm/ http://visualgo.net/sorting https://en.wikipedia.org/wiki/Quicksort
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39665299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1078107/']}
jdg_84678
stackexchange
llm_judgeable_groundtruth_similarity
59434242
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 deploy .NET core web API to Heroku. Below is my Dockerfile : FROM mcr.microsoft.com/dotnet/core/aspnet:2.1 AS runtimeWORKDIR /appCOPY /out ./CMD ASPNETCORE_URLS=http://*:$PORT dotnet dotnetcoreapi.dll This Dockerfile works fine on Heroku, but when I tried to deploy with FROM mcr.microsoft.com/dotnet/core/aspnet:2.1 AS runtimeWORKDIR /appCOPY /out ./ENTRYPOINT ["dotnet","dotnetcoreapi.dll"] Heroku gives me this error: Unable to start Kestrel. System.Net.Sockets.SocketException (13): Permission denied Why doesn't ENTRYPOINT ["dotnet","dotnetcoreapi.dll"] work on Heroku? Both versions work fine on my local machine Now provide the response and nothing else.
I've just solved this problem thanks to Chis' answer and this blogpost . It turns out that Heroku really wants to take care of the ports for you (probably for security reasons). With boilerplate asp core template, with docker suport added you start with: Program.cs: using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;namespace TestWebApp{ public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }} Dockerfile: #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS baseWORKDIR /appEXPOSE 80EXPOSE 443FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS buildWORKDIR /srcCOPY ["TestWebApp/TestWebApp.csproj", "TestWebApp/"]RUN dotnet restore "TestWebApp/TestWebApp.csproj"COPY . .WORKDIR "/src/TestWebApp"RUN dotnet build "TestWebApp.csproj" -c Release -o /app/buildFROM build AS publishRUN dotnet publish "TestWebApp.csproj" -c Release -o /app/publishFROM base AS finalWORKDIR /appCOPY --from=publish /app/publish .ENTRYPOINT ["dotnet", "TestWebApp.dll"] Heroku expects your app to run on the port Heroku gives you in PORT environment variable. It'll expose 80 (HTTP) and 443 (HTTPS) ports for you. So what you have to do is: Remove these lines form your Dockerfile : EXPOSE 80EXPOSE 443 Then you have to make your application listen on that port. To make it work, you have to change your Program.cs file: public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { var port = Environment.GetEnvironmentVariable("PORT"); webBuilder.UseStartup<Startup>() .UseUrls("http://*:" + port); }); Then Heroku does it's magic and your app still gets HTTPS support. Hint: The default Dockerfile won't work out of the box with Heroku CLI. The generated Dockerfile is supposed to be ran from the solution level (not project level). I was unable to force heroku CLI to use a Dockerfile form a nested direcotry. The way I made id work was: Go to your solution directory Create Dockerfile Paste modified content: #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS baseWORKDIR /appFROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS buildWORKDIR /srcCOPY ["TestWebApp/TestWebApp.csproj", "TestWebApp/"]RUN dotnet restore "TestWebApp/TestWebApp.csproj"COPY ./TestWebApp ./TestWebAppWORKDIR "/src/TestWebApp"RUN dotnet build "TestWebApp.csproj" -c Release -o /app/buildFROM build AS publishRUN dotnet publish "TestWebApp.csproj" -c Release -o /app/publishFROM base AS finalWORKDIR /appCOPY --from=publish /app/publish .ENTRYPOINT ["dotnet", "TestWebApp.dll"] heroku login heroku container:login heroku container:push web --app your-app & heroku container:release web --app your-app
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59434242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6925845/']}
jdg_84679
stackexchange
llm_judgeable_groundtruth_similarity
10016562
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 looking for a better solution for two things: How can I understand if the data is fetched and ready, I use BasicDealList.on("reset", function(){}) to understand if the data is fetched from ajax and parsed and ready to be used but it feels dirty. If an empty JSON comes from fetching such as {} , it still shows BasicDealList.length as 1 while it should be 0 thus I was forced to check if the first element is empty via collection.length == 1 && jQuery.isEmptyObject(BasicDealList.toJSON()[0] which is very ugly. Here is the code: BasicDeal = Backbone.Model.extend(); BasicDealCollection = Backbone.Collection.extend({ model: BasicDeal, url: '/some/ajax/url/',});BasicDealList = new BasicDealCollection();BasicDealList.on("reset", function(collection, response){ isEmpty = collection.length == 1 && jQuery.isEmptyObject(BasicDealList.toJSON()[0]); if (isEmpty){ // render no deal found html } else{ // render list of deals }}BasicDealList.fetch(); Now provide the response and nothing else.
If you don't like listening for reset , you can pass a callback directly to .fetch() : BasicDealList.fetch({ success: function(collection, response){ // ... }}); If, later in your app, you want to know whether you've fetched the data already, you could usually just check BasicDealList.length . If you want to avoid making repeated requests for collections that are actually empty on the server, you'll probably need to work out a custom solution, e.g. setting a flag on .fetch() : BasicDealList.fetch({ success: function(collection, response){ BasicDealList.fetched = true; // ... }}); As for the empty data issue, you should be returning [] from the server instead of {} . Backbone's Collection calls this.add(models, ...) within .reset() , and .add() checks whether the models argument is an array; if it's not, it wraps it in one: models = _.isArray(models) ? models.slice() : [models]; So passing {} will result in models set to [{}] , which is not what you want. If you can't control the server, you could do the check for {} in a custom .parse() method, returning [] if it's found.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10016562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151937/']}
jdg_84680
stackexchange
llm_judgeable_groundtruth_similarity
33086346
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the following code, are pS and s.pS guaranteed to be equal in the final line? In other words, in the statement S s = S(); , can I be sure that a temporary S will not be constructed? #include <iostream>using namespace std;struct S{ S() { pS = this; } S* pS;};int main(){ S s = S(); S* pS = &s; cout << pS << " " << s.pS << endl;} In every compiler I've tested this in pS == s.pS , but I'm not sufficiently familiar with the standard to be able to satisfy myself that this is guaranteed. Now provide the response and nothing else.
NO The compiler isn't obligated to do copy elision. The standard simply specifies that, [class.copy]: When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...] I can disable copy elision via -fno-elide-constructors , and then the two pointers will definitely be different. For example: $g++ -std=c++11 -Wall -pedantic -fno-elide-constructors -Wall -Wextra main.cpp && ./a.out0x7fff5a598920 0x7fff5a598930 And in the general case, if we add S(S&& ) = delete , then the above code wouldn't even compile.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33086346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/995218/']}
jdg_84681
stackexchange
llm_judgeable_groundtruth_similarity
2751540
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: It is said for two functions $f,g$ to be equal they must have same domain and codomain and for each $x\in X$, $f(x)=g(x)$. But shouldn't functions such as $f:\Bbb R \to \Bbb C$ where $f(x)=x^2$ and $g:\Bbb R \to \Bbb R$ where $g(x)=x^2$ still be considered equal functions for example? Even if codomain is different. Now provide the response and nothing else.
It might be worth noting that from a set theoretic standpoint, the copy of the reals contained in the complex numbers is not the same set as the reals on their own. They are isomorphic, but distinct as sets. We usually construct $\mathbb{C}$ as an ordered pair $(x,y) \in \mathbb{R} \times \mathbb{R}$, and define multiplication on these pairs. Here $x$ is the real part of the complex number and $y$ is the imaginary part. We have a natural isometric embedding of $\mathbb{R}$ into $\mathbb{C}$ by $x \mapsto (x,0)$. Thus, if we're talking about the real number "$2$" in $\mathbb{C}$, we're really talking about the ordered pair $(2,0)$. To bring it back, the two functions you described:$$f:\mathbb{R} \rightarrow \mathbb{R}, \quad f(x) = x^2$$$$g:\mathbb{R} \rightarrow \mathbb{C}, \quad g(x) = x^2$$Obviously $f$ and $g$ give the "same information" in some sense, but the objects in the image are set theoretically distinct, even if we interact with them in exactly the same way.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2751540', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/546620/']}
jdg_84682
stackexchange
llm_judgeable_groundtruth_similarity
653
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: On a large Cisco Catalyst switch stack, almost all switchports are patched. I need to identify the ports, which are not in use, for connecting further devices. Following switchports, cabling, patch fields and sockets to possible end devices is laborious and even then there could be temporarily used sockets. Looking at the activity of port LEDs is not reliable, since a user device can be shut off. What's the easiest way to detect all unused switchports via IOS commands? Now provide the response and nothing else.
I frequently use sh int | i (FastEthernet|0 packets input) or the same with GigabitEthernet, whatever kind of interfaces I want to check. sh int (which is show interfaces ) gives a huge list of ste status of all interfaces The pipe symbol | can be used for filtering, but also in search expressions | i (for include ) filters the output which matches the following search expressions I use (...|...) to match two conditions: the interface name and a status I like to see, we can use regular expressions here, like this "or" expression The output can look like: ...FastEthernet1/0/31 is up, line protocol is up (connected) 95445640 packets input, 18990165053 bytes, 0 no bufferFastEthernet1/0/32 is up, line protocol is up (connected)FastEthernet1/0/33 is up, line protocol is up (connected)FastEthernet1/0/34 is down, line protocol is down (notconnect) 0 packets input, 0 bytes, 0 no bufferFastEthernet1/0/35 is down, line protocol is down (notconnect)FastEthernet1/0/36 is up, line protocol is up (connected)FastEthernet1/0/37 is down, line protocol is down (notconnect) 0 packets input, 0 bytes, 0 no buffer... Now I can see my candidates, with actually 0 packets input over time, even if my expression matches numbers just ending with 0. I could make it more perfect, but being easy to remember is also a benefit. The interface names right before each 0 packets input lines are my candidates. Check each chosen interface if it's really unused by sh int <name> From time to time, it's good to clear the counters: clear counters [type number] It can be good practice, to leave unused switchports shutdown. So it's easy to identify them using sh ip int bri or the like. And you don't run into problems if you use a switchport which was definitly shut off before.
{}
{'log_upvote_score': 6, 'links': ['https://networkengineering.stackexchange.com/questions/653', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/231/']}
jdg_84683
stackexchange
llm_judgeable_groundtruth_similarity
405762
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: The energy of a photon depends on its wavelength, so theoretically when it is blueshifted it should have more energy right? Then what if a spaceship with a solar panel on the front is traveling towards the sun at relativistic speeds. An incoming photon undergoes a blueshift from the observer on the spacecraft. So does the solar panel read the same energy as if the light wasn't blueshifted? I see two options here: 1. Either the solar panel reads two different numbers depending on the observer. (almost like 2 realities exist) 2. Or it reads the same because the energy of the photon is not actually based on wavelength To keep it simple let's imagine we're only talking about one photon, because time dilation might affect the power level the solar panel was reading. Now provide the response and nothing else.
The energy of a photon is related to its frequency or wavelength. However the energy is a conserved quantity in a specific reference frame, but it is not an invariant. Another reference frame in relative motion vs. the former measures a different energy. In the example the observer on the spaceship approaching the sun experiences the blueshift of the solar photons. The solar panel on the spaceship reads a higher energy of the solar radiation.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/405762', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/195575/']}
jdg_84684
stackexchange
llm_judgeable_groundtruth_similarity
13432209
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 absolute newbie in Ruby and Rails project, so I'm sorry if this is dumb question. I've installed heroku toolbelt using wget -qO- https://toolbelt.heroku.com/install-ubuntu.sh | sh . Also I tried gem install heroku . But when I type: MY_USER@home-PC:~$ heroku version<internal:gem_prelude>:1:in `require': cannot load such file -- rubygems.rb (LoadError) from <internal:gem_prelude>:1:in `<compiled>' I've checked in google and people suggest that gem and current ruby are different versions so I've checked it and they seem to the same: MY_USER@home-PC:~$ which ruby/home/MY_USER/.rvm/rubies/ruby-1.9.3-p327/bin/rubyMY_USER@home-PC:~$ gem env | grep 'RUBY EXECUTABLE' - RUBY EXECUTABLE: /home/MY_USER/.rvm/rubies/ruby-1.9.3-p327/bin/ruby I have no idea what to do more, so please help. Sorry for the maybe stupid question, thanks in advance. EDIT: Forgot to say I'm running Ubuntu 12.10. Now provide the response and nothing else.
The problem is that the heroku executable you installed probably starts with a line like this: #!/usr/bin/ruby This will force the heroku command to always use the system-wide ruby ( /usr/bin/ruby ) and it will never run your rvm version of ruby. To fix it simply edit the first line of the heroku script to this: #!/usr/bin/env ruby This will make the heroku command run whichever ruby command is in the current PATH , instead of a hard coded path like previously. To find the location of the heroku script, so you can edit it, simply type: which heroku It should print out the location of the script so you can find it and load it into your editor.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13432209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1226137/']}
jdg_84685
stackexchange
llm_judgeable_groundtruth_similarity
3736417
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 integrate $$\int_{-\infty}^{\infty} xe^{-2\lambda |x|} dx$$ We are given that $\lambda$ is positive and realThis is my attempt $$\int_{-\infty}^{0} x e^{2\lambda x} dx+ \int_{0}^{\infty} xe^{-2\lambda x} dx$$ Using u-sub $u = {2\lambda x}$ and integrating by parts $$\frac{1}{2\lambda}\int_{-\infty}^{0} ue^{u} du+ \frac{1}{2\lambda}\int_{0}^{\infty} ue^{-u} du$$ $$= \frac{1}{2\lambda}(-1+1) = 0$$ But it seems wrong to me Now provide the response and nothing else.
This derivation is correct. You can also just notice that the function under the integral is odd i.e. $$f(-x)=-f(x)$$ for every $x$ . So... of course the definite integral from $-\infty$ to $+\infty$ if it is well defined (i.e. if it converges) will be equal to zero. See also: Even and Odd functions It is also important to note that the two improper integrals of $f(x)$ (from minus infinity to zero and from zero to plus infinity) converge. Why is this important? Because there are odd functions for which the integral from $-\infty$ to $+\infty$ is not zero but is undefined. A very simple example is $f(x)=x$ which is such an odd function. Integral of f(x)=x from minus infinity to plus infinity
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3736417', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/557301/']}
jdg_84686
stackexchange
llm_judgeable_groundtruth_similarity
375
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: After discovering a few difficulties with genome assembly, I've taken an interest in finding and categorising repetitive DNA sequences, such as this one from Nippostrongylus brasiliensis [each base is colour-coded as A: green; C: blue; G: yellow; T: red]: [FASTA file associated with this sequence can be found here ] These sequences with large repeat unit sizes are only detectable (and assembleable) using long reads (e.g. PacBio, nanopore) because any subsequence smaller than the unit length will not be able to distinguish between sequencing error and hitting a different location within the repeat structure. I have been tracking these sequences down in a bulk fashion by two methods: Running an all-vs-all mapping, and looking for sequences that map to themselves lots of times Carrying out a compression of the sequence (e.g. bzip2), and finding sequences that have a compression rate that is substantially higher than normal After I've found a suspicious sequence, I then want to be able to categorise the repeat (e.g. major repeat length, number of tandem repeats, repetitive sequence). This is where I'm getting stuck. For doing a "look, shiny" demonstration, I currently have a very manual process of getting these sequences into a format that I can visualise. My process is as follows: Use LAST to produce a dot plot of self-mapping for the mapping Visually identify the repetitive region, and extract out the region from the sequence Use a combination of fold -w <width> and less -S to visually inspect the sequence with various potential repeat unit widths to find the most likely repeat unit size Display the sequence in a rectangular and circular fashion using my own script , wrapping at the repeat unit length But that process is by no means feasible when I've got thousands of potential repetitive sequences to fish through. Is there any better way to do this? Given an arbitrary DNA sequence of length >10kb, how can I (in an automated fashion) find both the location of the repeat region, and also the unit length (bearing in mind that there might be multiple repeat structures, with unit lengths from 30bp to 10kb)? An example sequence can be found here , which has a ~21kb repeat region with ~171bp repeat units about 1/3 of the way into the sequence. A Kmer-based Analysis I've now seen human sequences with repetitive regions in excess of 10kb (i.e. out of the range of most linked-read applications). My current idea is centred around creating hash tables of short sequences (currently 13-mers) and tracking their location: Process the sequence, storing the location of each kmer For each kmer, find out how many times it appears in the sequence For repeated kmers, find out how much of a gap there is between the next time that kmer occurs Report the median and modal gap length of repeated kmers, and statistics associated with their frequency in the sequence Some local repetitive regions may be lost in the statistics with this approach, it's hard to tell if there are multiple repetitive regions within a single sequence, and if the repeat units are themselves slightly repetitive (enough that a kmer is duplicated within a repeat unit), then the algorithm will under-report the repetitiveness (see step 3). Now provide the response and nothing else.
Yes, that blog post does represent just one guy's opinion (hi!) and it does date all the way back to 2014 , which is, like, decades in genomics years. :-) By the way, there is quite a bit of literature discussing the improvements that expected read counts derived from an Expectation Maximization algorithm provide over raw read counts. I'd suggest reading the RSEM papers for a start [ 1 ][ 2 ] . But your main question is about the mechanics of running RSEM and EBSeq. First, RSEM was written explicitly to be compatible with EBSeq, so I'd be very surprised if it does not work correctly out-of-the-box. Second, EBSeq's MedianNorm function worked very well in my experience for normalizing the library counts. Along those lines, the blog you mentioned above has another post that you may find useful. But all joking aside, these tools are indeed dated. Alignment-free RNA-Seq tools provide orders-of-magnitude improvements in runtime over the older alignment-based alternatives, with comparable accuracy. Sailfish was the first in a growing list of tools that now includes Salmon and Kallisto . When starting a new analysis from scratch (i.e. if you ever get the original FASTQ files), there's really no good reason not to estimate expression using these much faster tools, followed by a differential expression analysis with DESeq2, edgeR, or sleuth. 1 Li B, Ruotti V, Stewart RM, Thomson JA, Dewey CN (2010) RNA-Seq gene expression estimation with read mapping uncertainty. Bioinformatics , 26(4):493–500, doi:10.1093/bioinformatics/btp692 . 2 Li B, Dewey C (2011) RSEM: accurate transcript quantification from RNA-Seq data with or without a reference genome. BMC Bioinformatics , 12:323, doi:10.1186/1471-2105-12-323 .
{}
{'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/375', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/73/']}
jdg_84687
stackexchange
llm_judgeable_groundtruth_similarity
20223034
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 make one Asus Xtion work in java with opencv 2.4.7 and OpenNI (i have both installed). My problem is that the flags doens't work.. CV_CAP_OPENNI CV_CAP_OPENNI_DEPTH_MAP CV_CAP_OPENNI_POINT_CLOUD_MAP CV_CAP_OPENNI_DISPARITY_MAP CV_CAP_OPENNI_DISPARITY_MAP_32F CV_CAP_OPENNI_VALID_DEPTH_MASK No one is working, why? Now provide the response and nothing else.
It's hard to see the exact values and setup of your constraints as you've pasted them here, so I'm not sure from looking at your screenshots where you have gone wrong. In lieu of an explanation of what's wrong in your setup, I've created a basic sample project with a very similar view hierarchy and constraint setup to the one you describe. The horizontal scrolling works as expected in the sample project, which uses the "Pure AutoLayout" approach that Apple describes in the Technical Note . I also had a lot of trouble originally getting Auto Layout to work with UIScrollView . The key to getting it to work is making sure that all of the items in the scroll view, taken together, have constraints that eventually link to all sides of the scroll view and that contribute to the AutoLayout system being able to determine a contentSize for the scroll view that will be bigger than its frame. It looks like you were trying to do that in your code, but maybe you had some superfluous constraints in there that were making the contentSize too small. Also of note, as others mentioned, with AutoLayout and UIScrollview, you no longer set the contentSize explicitly. The AutoLayout System calculates the contentSize based on your constraints. I also found this ebook chapter to be very helpful in making me understand how all this works. Hope all this helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20223034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1854135/']}
jdg_84688
stackexchange
llm_judgeable_groundtruth_similarity
145402
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I cannot seem to make it work. GNU sed documentation says to escape the pipe, but that doesn't work, nor does using a straight pipe without the escape. Adding parens makes no difference. $ echo 'catdogpearbananacatdog' | sed 's/cat|dog/Bear/g'catdogpearbananacatdog$ echo 'catdogpearbananacatdog' | sed 's/cat\|dog/Bear/g'catdogpearbananacatdog Now provide the response and nothing else.
By default sed uses POSIX Basic Regular Expressions , which don't include the | alternation operator. You can switch it into using Extended Regular Expressions , which do include | alternation, with -E (or -r in some older versions of some implementations). You can use: echo 'cat dog pear banana cat dog' | sed -E -e 's/cat|dog/Bear/g' and it will work on compliant systems. ( -e optionally marks the sed script itself - you can leave it out, it just guards against some kinds of mistake) Portability to very old sed s is complicated, but you can also switch to awk if you need it, which uses EREs everywhere.
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/145402', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43342/']}
jdg_84689
stackexchange
llm_judgeable_groundtruth_similarity
160451
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: Referring to this lecture , I want to know what is the difference between supremum and maximum. It looks same as far as the lecture is concerned when it explains pointwise supremum and pointwise maximum Now provide the response and nothing else.
A maximum of a set must be an element of the set. A supremum need not be. Explicitly, if $X$ is a (partially) ordered set, and $S$ is a subset, then an element $s_0$ is the supremum of $S$ if and only if: $s\leq s_0$ for all $s\in S$; and If $t\in X$ is such that $s\leq t$ for all $s\in S$, then $s_0\leq t$. By contrast, an element $m$ is the maximum of $S$ if and only if: $s\leq m$ for all $s\in S$; and $m\in S$. Note that if $S$ has a maximum, then the maximum must be the supremum: indeed, if $t\in X$ is such that $s\leq t$ for all $s\in S$, then in particular $m\in S$, so $m\leq t$, proving that $m$ satisfies the conditions to be the supremum. But it is possible for a set to have a supremum but not a maximum. For instance, in the real numbers, the set of all negative numbers does not have a maximum: there is no negative number $m$ with the property that $n\leq m$ for all negative numbers $n$. However, the set of all negative numbers does have a supremum: $0$ is the supremum of the set of negative numbers. Indeed, $a\leq 0$ for all negative numbers $a$; and if $a\leq b$ for all negative numbers $a$, then $0\leq b$. The full relationship between supremum and maximum is: If $S$ has a maximum $m$, then $S$ also has a supremum and in fact $m$ is also a supremum of $S$. Conversely, if $S$ has a supremum $s$, then $S$ has a maximum if and only if $s\in S$, in which case the maximum is also $s$. In particular, if a set has both a supremum and a maximum, then they are the same element. The set may also have neither a supremum nor a maximum (e.g., the rationals as a subset of the reals). But if it has only one them, then it has a supremum which is not a maximum and is not in the set.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/160451', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31820/']}
jdg_84690
stackexchange
llm_judgeable_groundtruth_similarity
4231817
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 image file on the disk and I am resizing the file and saving it back to disk as a new image file. For the sake of this question, I am not bringing them into memory in order to display them on the screen, only to resize them and resave them. This all works just fine. However, the scaled images have artifacts on them like shown here: android: quality of the images resized in runtime They are saved with this distortion, as I can pull them off the disk and look at them on my computer and they still have the same issue. I am using code similar to this Strange out of memory issue while loading an image to a Bitmap object to decode the bitmap into memory: BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(imageFilePathString, options);int srcWidth = options.outWidth;int srcHeight = options.outHeight;int scale = 1;while(srcWidth / 2 > desiredWidth){ srcWidth /= 2; srcHeight /= 2; scale *= 2;}options.inJustDecodeBounds = false;options.inDither = false;options.inSampleSize = scale;Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(imageFilePathString, options); Then I am doing the actual scaling with: Bitmap scaledBitmap = Bitmap.createScaledBitmap(sampledSrcBitmap, desiredWidth, desiredHeight, false); Lastly, the new resized image is saved to disk with: FileOutputStream out = new FileOutputStream(newFilePathString);scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); Then, as I mentioned, if I pull that file off the disk and look at it, it has that quality issue linked above and looks terrible. If I skip the createScaledBitmap and just save the sampledSrcBitmap right back to disk there is no problem, it seems to only happen if the size changes. I have tried, as you can see in the code, setting inDither to false as mentioned here http://groups.google.com/group/android-developers/browse_thread/thread/8b1abdbe881f9f71 and as mentioned in the very first linked post above. That didn't change anything. Also, in the first post I linked, Romain Guy said: Instead of resizing at drawing time (which is going to be very costly), try to resize in an offscreen bitmap and make sure that Bitmap is 32 bits (ARGB888). However, I have no idea how to make sure the Bitmap stays as 32 bits through the whole process. I have also read a couple other articles such as this http://android.nakatome.net/2010/04/bitmap-basics.html but they all seemed to be addressing drawing and displaying the Bitmap, I just want to resize it and save it back to disk without this quality problem. Thanks much Now provide the response and nothing else.
After experimenting I have finally found a way to do this with good quality results. I'll write this up for anyone that might find this answer helpful in the future. To solve the first problem, the artifacts and weird dithering introduced into the images, you need to insure your image stays as a 32-bit ARGB_8888 image. Using the code in my question, you can simply add this line to the options before the second decode. options.inPreferredConfig = Bitmap.Config.ARGB_8888; After adding that, the artifacts were gone but edges throughout the images came through jagged instead of crisp. After some more experimentation I discovered that resizing the bitmap using a Matrix instead of Bitmap.createScaledBitmap produced much crisper results. With those two solutions, the images are now resizing perfectly. Below is the code I am using in case it benefits someone else coming across this problem. // Get the source image's dimensionsBitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(STRING_PATH_TO_FILE, options);int srcWidth = options.outWidth;int srcHeight = options.outHeight;// Only scale if the source is big enough. This code is just trying to fit a image into a certain width.if(desiredWidth > srcWidth) desiredWidth = srcWidth;// Calculate the correct inSampleSize/scale value. This helps reduce memory use. It should be a power of 2// from: https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966int inSampleSize = 1;while(srcWidth / 2 > desiredWidth){ srcWidth /= 2; srcHeight /= 2; inSampleSize *= 2;}float desiredScale = (float) desiredWidth / srcWidth;// Decode with inSampleSizeoptions.inJustDecodeBounds = false;options.inDither = false;options.inSampleSize = inSampleSize;options.inScaled = false;options.inPreferredConfig = Bitmap.Config.ARGB_8888;Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(STRING_PATH_TO_FILE, options);// ResizeMatrix matrix = new Matrix();matrix.postScale(desiredScale, desiredScale);Bitmap scaledBitmap = Bitmap.createBitmap(sampledSrcBitmap, 0, 0, sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(), matrix, true);sampledSrcBitmap = null;// SaveFileOutputStream out = new FileOutputStream(NEW_FILE_PATH);scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);scaledBitmap = null; EDIT: After continual work on this I have found that the images still aren't 100% perfect. I'll make an update if I can improve it. Update: After revisting this, I found this question on SO and there was an answer that mentioned the inScaled option. This helped with the quality as well so I added updated the answer above to include it. I also now null the bitmaps after they are done being used. Also, as a side note, if you are using these images in a WebView, make sure you take this post into consideration. Note: you should also add a check to make sure the width and height are valid numbers (not -1). If they are, it will cause the inSampleSize loop to become infinite.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4231817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445348/']}
jdg_84691
stackexchange
llm_judgeable_groundtruth_similarity
28184466
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 need to generate a JSON from a list of objects. To do it I am using the following code, but I have two problems: The order of entries get changes It adds \ before all " when I show the JSON. JSONObject jsonObj = new JSONObject();for (Row row : rows) { jsonObj.put(row.getCode(),row.getValue());}myJson.put(jsonObj.toString());System.err.println("myJson:" + myJson.toString()); Output myJson:["{\"1234445\":\"Jack"}"] Thanks to Sotirios Delimanolis , after removing .toString() from jsonObj the first problem has been solved. Now provide the response and nothing else.
the reason this doesnt work is that you are creating a NEW instance of GameViewController and then you're calling gameOver on that. What you really want to do is reference your existing GameViewController theres a few ways to do this, I'll give you one example. add a viewController property to your GameScene class class GameScene { // we need to make sure to set this when we create our GameScene var viewController: GameViewController! in your GameViewController file // after GameScene is instantiatedgameScene.viewController = self now we have a reference to viewController, lets use it in our GameScene class // somewhere in GameSceneself.viewController.gameOver()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28184466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3470841/']}
jdg_84692
stackexchange
llm_judgeable_groundtruth_similarity
348043
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using Ansible-2.0 on linux machine and I wish to do change DNS on remote machine using ansible as below: ---# tasks file for test- name: Change dns become: yes become_user: admin replace: dest: /etc/resolv.conf regexp: '192.168.1.24' replace: '8.8.8.8' Output: $ ansible-playbook -i "mn," test.yml TASK [test : Change dns] *******************************************************fatal: [mn]: FAILED! => {"changed": false, "failed": true, "msg": "The destination directory (/etc) is not writable by the current user."}PLAY RECAP *********************************************************************mn : ok=1 changed=0 unreachable=0 failed=1 On remote machine, admin is as sudo user and here I don't want to change sudo setting on remote machine, Is there any method to pass password using task(script), not using command line. Now provide the response and nothing else.
you should configure admin as a remote_user , not become_user . The become_user option sets to which user you would su to execute certain task. In other words, your playbook should look like: ---- hosts: somehosts remote_user: admin roles: ....#tasks file---# tasks file for test- name: Change dns become: yes replace: dest: /etc/resolv.conf regexp: '192.168.1.24' replace: '8.8.8.8' That way the admin user will be used to establish your ssh session, but for the Change dns task will be used sudo . Also, if admin requires password for sudo, you will have to run your playbook like this: ansible-playbook -i mn test.yml -K The -K switch will prompt you for the sudo password for admin .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/348043', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/138125/']}
jdg_84693
stackexchange
llm_judgeable_groundtruth_similarity
12514664
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 the PL/R procedural language in a PostgreSQL 9.2 database. I have installed the plr language and I am trying to add it to a database. When I run the command CREATE EXTENSION plr; I get the following error: ERROR: language "C" does not existSTATEMENT: CREATE EXTENSION plr;ERROR: language "C" does not exist When I list the available languages in the database with select * from pg_language; I get lanname | lanowner | lanispl | lanpltrusted | lanplcallfoid | laninline | lanvalidator | lanacl ----------+----------+---------+--------------+---------------+-----------+--------------+-------- internal | 10 | f | f | 0 | 0 | 2246 | c | 10 | f | f | 0 | 0 | 2247 | sql | 10 | f | t | 0 | 0 | 2248 | plpgsql | 10 | t | t | 12514 | 12515 | 12516 | (4 rows) So there is a language c but it is not in capital letters (not sure if that makes a difference). I am wondering why the plr extension does not find the C procedural language? Now provide the response and nothing else.
You are probably running into this change in PostgreSQL 9.2 (quoting the release notes here ): No longer forcibly lowercase procedural language names in CREATE FUNCTION (Robert Haas) While unquoted language identifiers are still lowercased, strings and quoted identifiers are no longer forcibly down-cased. Thus for example CREATE FUNCTION ... LANGUAGE 'C' will no longer work; it must be spelled 'c', or better omit the quotes. It's also reflected in the manual for CREATE FUNCTION lang_name The name of the language that the function is implemented in. Can be SQL , C , internal , or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes. Quoting the language name has been discouraged since at least version 7.3 (maybe longer), but old habits die hard, obviously. Removing the quotes around 'C' fixes the problem, arriving at: LANGUAGE c or LANGUAGE C . PL/R wasn't ready for PostgreSQL 9.2 in that respect, judging from the project page . Feedback from Joe Conway Joe Conway left an answer that got deleted because it should be a comment. I paste it here for the general public who can't see deleted answers: I got the message, just haven't had the time to do a new PL/R release. Look for it by December, but in the meantime the manual workaround noted above is pretty simple.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12514664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/933245/']}
jdg_84694
stackexchange
llm_judgeable_groundtruth_similarity
78734
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to calculate a 48 point FFT using an N-point FFT library function which only supports lengths that are a power of 2. Is it possible to calculate a 48-point FFT using a 32-point FFT and 16-point FFT? If not, what is the most efficient way of implementing a 48 point FFT? Now provide the response and nothing else.
If not, what is the most efficient way of implementing a 48 point FFT? Three 16 point FFTs plus one set of 3 point "Butterflies". Matlab example %% Do a 48 point FFT, this is NOT efficient but shows the principlen = 48;nFFT = 16;x0 = randn(n,1); % test vectorfx0 = fft(x0); % referencex1 = reshape(x0,3,nFFT)'; % reshape into 3 N-16 vectorsfx1 = fft(x1); % 3 FFTs 16 points eachfx2 = [fx1; fx1; fx1]; % periodic repetition for easy butterfly codeW = exp(-1i*2*pi*(0:n-1)'/n); % twiddle factor, N = 48% execute a 3 point "butterfly"fy = fx2(:,1) + fx2(:,2).*W + fx2(:,3).*W.^2;% calculate and print errord = (fy-fx0);fprintf('Relative Error = %6.2fdB \n',20*log10(sum(abs(d))./sum(abs(fx0))));
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/78734', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/4353/']}
jdg_84695
stackexchange
llm_judgeable_groundtruth_similarity
510055
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 need to make multiple divs move from right to left across the screen and stop when it gets to the edge. I have been playing with jQuery lately, and it seem like what I want can be done using that. Does anyone have or know where I can find an example of this? Now provide the response and nothing else.
You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin. Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence. To read up on this, check out this thread (from my very first Stackoverflow post no less)! Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/510055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_84696
stackexchange
llm_judgeable_groundtruth_similarity
353086
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: Following REST principles, I would want to create a GET method for my API that make a search using some criteria and return the results to the client. The problem is that the criteria can have up to 14 parameters, one of them is a list of complex objects, so... I don't even know if it possible to encode/decode these complexobjects to/from url parameters. I didn't calculate how long the url could get but I'm sure it will belarge enough and maybe reach the url length limit? Also, the search should show the results in "real time", I mean, every time the user changes something from the search form he should be able to see the new results without pressing any "search" button. Could you clarify me these points and what would be your advice to create a restful search method with a lot of parameters? update: now that I have more experience, I've realized that having to do a search function with A LOT of parameters for a web app is actually something that designates bad design and bad requirements, and @Neil answer has the point. So my advice is do what you can within the scope. Nevertheless, the @Laiv answer is still good for less extreme cases, so take it into account too. Now provide the response and nothing else.
Before you read my answer, I would like to say that I agreed with @Neil. We have to pick our battles. We usually want to do our best, but sometimes there's too little room for discussion and we have to make decisions against our will. Anyways, in Neil's answer, I miss one more thing. Documentation . Just to ensure that developers know that POST requests to /search are safe. That said. 1. Give GET a chance Consider the GET option first. Check out this question URL's max length . Evaluate whether your longest query string is longer than 2000 characters. If it doesn't, and you don't expect it to be, go with GET . It might seem ugly but it has all the advantages derived from the method' semantics (idempotence, safe and caching). And bookmarking. 1.1 Try encoding the query string For example, in base 64. Even javascript supports base 64 encodings . This's how it works: Build the JSON with all the filters and normalise it. Parse it to string Encode it Send the encoded JSON as request param ( /search?q=SGVsbG8gV29ybGQh.... ). On the server-side, decode q . Deserialize the JSON string Previously, make the longest possible JSON string, encode it and take the length. Evaluate if the encoded string fits in the URL. I have implemented the following snippet on Fiddle.js for you to test. (I hope it still works) 1 Base 64 encodes are deterministic and reversible, so there's no chance for collisions. With encoded queries, we could also save searches in the DB, bookmark the URL too, share links, etc. And, of course, we don't have to escape/unescape the string (something I dislike). 1.2 Try with aliases Reading this blog about how to design REST APIs, I remembered one more alternative. Aliases for common queries . I find these to be interesting for the next reasons Shorten the query string length. It makes the API cleaner and user-friendly GET /tickets/?status=closed&closedAt=xxx vs GET /tickets/recently-closed/ Combinable with more aliases or more request parameters. GET /tickets/?status=closed&closedAt=xxx&within=30min vs GET /tickets/recently-closed/?within=30min We can combine aliases with encoded query strings GET /tickets/?status=closed&closedAt=xxx&within=30min vs GET /tickets/recently-closed/?q=SGVsbG8g... 1: I have used JSON, but we could use other formats as soon as we can deserialize these on the server-side.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/353086', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/262178/']}
jdg_84697
stackexchange
llm_judgeable_groundtruth_similarity
24671
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Shouldn't reaching an octet be any atom's "goal"? However, I've recently learned about cases that are either expanding octets, or have lesser than "enough" electrons for an octet abiding. e.g.: S in sulfur hexafluoride (Expanding octet into $\text{3d}$) Source B in boron trifluoride (It's "hextet", instead of octet) Source However, both $\ce{SnCl2}$ and $\ce{SnCl4}$ are existent. The latter is explainable with octet, but not the former. Surprisingly, $\ce{SnCl2}$ is more stable! How? Why is the phenomenon happening? Dave pointed out that the octet nonabidingness is happening in the vapor phase. So I redirect the question to ask about the vapor phase; since that's what I'm looking for. Now provide the response and nothing else.
$\ce{SF6}$ does not expand it octet by way of using 3d orbitals. It is often taught that way, particularly in introductory classes. A better description involves treating it as a hypercoordinated molecule. See these earlier answers for an explanation of how hypercoordination can be applied. When finished you should be able to apply the concept to $\ce{SF6}$. reference 1 reference 2 $\ce{BF3}$ is electron deficient and reacts rapidly with molecules containing lone pairs of electrons (amines, oxygen containing compounds, etc.) to stabilize the octet configuration. It has also been observed that the $\ce{B-F}$ bond length is somewhat shorter than expected. This has been explained by invoking resonance structures such as and To whatever degree these types of resonance structures contribute to the true description of $\ce{BF3}$ they help explain the shortened bond length and also achieve an octet around the central boron. A similar explanation can be applied to $\ce{SnCl2}$, drawing a resonance structure with a $\ce{Sn=Cl}$ double bond creates an octet around the central tin atom. To whatever degree such resonance structures contribute to the real description of $\ce{SnCl2}$, they will help satisfy the octet electronic configuration around the central tin atom.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/24671', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7448/']}
jdg_84698
stackexchange
llm_judgeable_groundtruth_similarity
59743
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 many possible combinations of the variables a,b,c,d,e are possible if I know that: a+b+c+d+e = 500 and that they are all integers and >= 0, so I know they are finite. Now provide the response and nothing else.
@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose a as 1 and b as 2 , then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing a as 2 and b as 1 . (The number of such coincidences explodes as the numbers grow.) The traditional way to attack such a problem is dynamic programming : build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of n variables add up to k ?" is the sum of the solutions to "how many combinations of n-1 variables add up to j ?" with 0 <= j <= k ). public static long getCombos( int n, int sum ) { // tab[i][j] is how many combinations of (i+1) vars add up to j long[][] tab = new long[n][sum+1]; // # of combos of 1 var for any sum is 1 for( int j=0; j < tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i < tab.length; ++i ) { for( int j=0; j < tab[i].length; ++j ) { // # combos of (i+1) vars adding up to j is the sum of the # // of combos of i vars adding up to k, for all 0 <= k <= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k <= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum];} $ time java Combos2656615626real 0m0.151suser 0m0.120ssys 0m0.012s
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1815/']}
jdg_84699
stackexchange
llm_judgeable_groundtruth_similarity
38247
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 heard at some point (without seeing a proof) that every countable, compact space $X$ is homeomorphic to a countable successor ordinal with the usual order topology. Is this true? Perhaps someone can offer a sketch of the proof or suggest a topology/ordinal text which treats countable spaces in depth. I also wonder if these spaces are metrizable or if they can be embedded into $\mathbb{R}$. By the way, I'm assuming $X$ is Tychonoff but perhaps this can be reduced to a weaker separation axiom. Edit: Just to clarify and avoid erroneous future editing,"countable compact space" means "compact space, whose underlying set is countable." This is different from "countably compact space." Now provide the response and nothing else.
I believe that you are looking for ideas from the Cantor Bendixson theorem . The main idea of the proof is the Cantor-Bendixson derivative . Given a closed set $X$, the derived set $X'$ consists of all limit points of $X$. That is, one simply throws out the isolated points. Continuing in a transfinite sequence, one constructs $X_\alpha$ as follows: $X_0=X$, the original set. $X_{\alpha+1}=(X_\alpha)'$, the set of limit points of $X_\alpha$. $X_\lambda=\bigcap_{\alpha\lt\lambda}X_\alpha$, for limit ordinals $\lambda$. Thus, $X_1$ consists of the limit points of $X$, and $X_2$ consists of the limits-of-limits, and so on. The set $X_\omega$ consists of points that are $n$-fold limits for any particular finite $n$, and $X_{\omega+1}$ consists of limits of those kind of points, and so on. The process continues transfinitely until a set is reached which has no isolated points; that is, until a perfect set is reached. The Cantor Bendixon rank of a set is the smallest ordinal $\alpha$ such that $X_\alpha$ is perfect. The concept is quite interesting historically, since Cantor had undertaken this derivative before he developed his set theory and the ordinal concept. Arguably, it is this derivative concept that led Cantor to his transfinite ordinal concept. It is easy to see that the ordinal $\omega^\alpha+1$ under the order topology has rank $\alpha+1$, and one can use this to prove a version of your desired theorem. The crucial ingredients you need are the Cantor Bendixson rank of your space and the number of elements in the last nonempty derived set. From this, you can constuct the ordinal $(\omega^\alpha+1)\cdot n$ to which your space is homeomorphic. Meanwhile, every countable ordinal is homeomorphic to a subspace of $\mathbb{Q}$, and is metrizable. The compact ordinals are precisely the successor ordinals (plus 0). Update 5/11/2011. This brief article by Cedric Milliet contains a proof of the Mazurkiewicz-Sierpiński theorem (see Stefan Mazurkiewicz and Wacław Sierpiński, Contribution à la topologie desensembles dénombrables, Fundamenta Mathematicae 1, 17–27, 1920), as follows: Theorem 4. Every countable compactHausdorff space is homeomorphic to some well-ordered set with the order topology. The article proves more generally that any two countable locally compact Hausdorff spaces $X$ and $Y$ of same Cantor-Bendixson rank and degree are homeomorphic. This is proved by transfinite induction on the rank, and the proof is given on page 4 of the linked article.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/38247', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2423/']}
jdg_84700
stackexchange
llm_judgeable_groundtruth_similarity
27205345
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 this record in the database which is used to hold multiple values.I want to know what is this format called so that I know how to deal with it? a:4:{s:5:"child";a:1:{s:0:"";a:1:{s:3:"rss";a:1:{i:0;a:6:{s:4:"data";s:1:" ";s:7:"attribs";a:1:{s:0:"";a:1:{s:7:"version";s:3:"2.0";}}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";s:5:"child";a:1:{s:0:"";a:1:{s:7:"channel";a:1:{i:0;a:6:{s:4:"data";s:29:" ";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";s:5:"child";a:5:{s:0:"";a:8:{s:5:"title";a:1:{i:0;a:5:{s:4:"data";s:5:"yoast";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:4:"link";a:1:{i:0;a:5:{s:4:"data";s:16:"http://yoast.com";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:11:"description";a:1:{i:0;a:5:{s:4:"data";s:17:"tweaking websites";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:13:"lastbuilddate";a:1:{i:0;a:5:{s:4:"data";s:31:"fri, 30 mar 2012 09:19:49 +0000";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:8:"language";a:1:{i:0;a:5:{s:4:"data";s:5:"en-us";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:9:"generator";a:1:{i:0;a:5:{s:4:"data";s:39:"http://wordpress.org/?v=3.4-alpha-19827";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:5:"image";a:1:{i:0;a:6:{s:4:"data";s:5:" ";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";s:5:"child";a:1:{s:0:"";a:6:{s:5:"title";a:1:{i:0;a:5:{s:4:"data";s:5:"yoast";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:3:"url";a:1:{i:0;a:5:{s:4:"data";s:69:"http://yoast.com/wp-content/themes/yoast-v2/images/yoast-logo-rss.png";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:4:"link";a:1:{i:0;a:5:{s:4:"data";s:16:"http://yoast.com";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:5:"width";a:1:{i:0;a:5:{s:4:"data";s:3:"144";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:6:"height";a:1:{i:0;a:5:{s:4:"data";s:3:"103";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:11:"description";a:1:{i:0;a:5:{s:4:"data";s:17:"tweaking websites";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}}}}}s:4:"item";a:20:{i:0;a:6:{s:4:"data";s:15:" ";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";s:5:"child";a:7:{s:0:"";a:7:{s:5:"title";a:1:{i:0;a:5:{s:4:"data";s:42:"7 ways to increase sales by creating trust";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:4:"link";a:1:{i:0;a:5:{s:4:"data";s:58:"http://feedproxy.google.com/~r/joostdevalk/~3/1ssu1jmtutq/";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:8:"comments";a:1:{i:0;a:5:{s:4:"data";s:69:"http://yoast.com/7-ways-to-increase-sales-by-creating-trust/#comments";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:7:"pubdate";a:1:{i:0;a:5:{s:4:"data";s:31:"mon, 26 mar 2012 13:09:54 +0000";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:8:"category";a:2:{i:0;a:5:{s:4:"data";s:22:"usability & conversion";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}i:1;a:5:{s:4:"data";s:28:"conversion rate optimization";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:4:"guid";a:1:{i:0;a:5:{s:4:"data";s:25:"http://yoast.com/?p=45457";s:7:"attribs";a:1:{s:0:"";a:1:{s:11:"ispermalink";s:5:"false";}}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:11:"description";a:1:{i:0;a:5:{s:4:"data";s:778:"<p>the key to conversing a visitor into a client is the creation of trust. your product can be the greatest thing on earth or the dullest office supply ever, both can be sold online when your visitor knows you are the best supplier for that product or service. we often advise on how to gain [...]</p><p><a href="http://yoast.com/7-ways-to-increase-sales-by-creating-trust/">7 ways to increase sales by creating trust</a> is a post by <a rel="author" href="http://yoast.com/author/michiel/">michiel heijmans</a> on <a href="http://yoast.com">yoast - tweaking websites</a>.a good wordpress blog needs good hosting, you don't want your blog to be slow, or, even worse, down, do you? check out my thoughts on <a href="http://yoast.com/wordpress-hosting/">wordpress hosting</a>!</p>";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}}s:32:"http://purl.org/dc/elements/1.1/";a:1:{s:7:"creator";a:1:{i:0;a:5:{s:4:"data";s:16:"michiel heijmans";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}}s:40:"http://purl.org/rss/1.0/modules/content/";a:1:{s:7:"encoded";a:1:{i:0;a:5:{s:4:"data";s:6576:"<p>the key to conversing a visitor into a client is the creation of trust. your product can be the greatest thing on earth or the dullest office supply ever, both can be sold online when your visitor knows you are the best supplier for that product or service.</p><p>we often advise on how to gain trust in our <a title="website review" href="http://yoast.com/hire-me/website-review/">website reviews</a>, and i've compiled a list of some of the advice we've given over time. of course, trust can be earned in more ways than this, but we'll give you these seven to start with.</p><h2>1. use clear and normal language</h2><p>this is an often overseen issue that causes a lot of misgrief with your visitors. you should speak their language, not drown them in a sea of technical specs you don't even understand yourself. use a clear and direct style of writing. keep your audience in mind. do not focus on telling them what you want to tell them, focus on providing as many arguments as possible why their quality of life improves after buying that specific product.</p><h2>2. testimonials</h2><p>do not brag about your products yourself. if your products or services are really that good, i'm sure you'll find someone else that can do the bragging for you. make sure your visitor understand that the testimonial is written by an actual customer, by listing at least name and company and if the customer agrees, even a picture of him. video seems to be the next big thing in testimonials, by the way. in my opinion, that video testimonial should be accompanied by a written excerpt:</p><div id="attachment_45461" class="wp-caption alignright" style="width: 590px"><a href="http://cdn.yoast.com/wp-content/uploads/2012/03/testimonials-cloversites.com_.png"><img class="size-large wp-image-45461" title="testimonials as seen on cloversites.com" src="http://cdn2.yoast.com/wp-content/uploads/2012/03/testimonials-cloversites.com_-590x472.png" alt="testimonials as seen on cloversites.com" width="580" height="464" /></a><p class="wp-caption-text">testimonials as seen on cloversites.com</p></div><h2>3. verified signs</h2><p>everyone can create a verified sign, so don't let those verified signs fool you. but the majority of your visitors actually believe that you are the 'most appreciated hairdresser of mississippi' or the 'best plummer 2006'. man, i hate those signs. but when the signs are from well-known companies, they really do add value to a webshop:</p><div id="attachment_45459" class="wp-caption alignright" style="width: 590px"><a href="http://cdn2.yoast.com/wp-content/uploads/2012/03/verified-signs-dx.com_.png"><img class="size-large wp-image-45459" title=""verified" signs" src="http://cdn2.yoast.com/wp-content/uploads/2012/03/verified-signs-dx.com_-590x76.png" alt=""verified" signs" width="580" height="74" /></a><p class="wp-caption-text">"verified" signs</p></div><p>by investing in the guidelines of the right verification companies â the webshop shows that it has been keeping the customer in mind when setting up the website.</p><h2>4. pictures</h2><p>if you recognize the woman on this picture, please call the following toll-free number...:</p><p><a href="http://cdn3.yoast.com/wp-content/uploads/2012/03/picture-stock.png"><img class="alignright size-large wp-image-45460" title="stock photography" src="http://cdn2.yoast.com/wp-content/uploads/2012/03/picture-stock-590x314.png" alt="stock photography" width="580" height="308" /></a></p><p>you can do better than that stock photo. listing actual pictures of yourself and/or your employees pushes conversion due to recognition and identification.</p><h2>5. list your physical address</h2><p>this one is really simple: people want to know there is a place to go to in case of problems (if any). having an actual store next to your webshop works even better, especially if a lot of your customers are relatively local.</p><p>in the netherlands <a href="http://digitalstreet.nl/">digitalstreet.nl</a> made this concept into a huge success, even though they're located in the south-west of the netherlands (quite near to where we are), people come from all over the netherlands because they'd rather buy the product in the store. there are more stories like that, but even if you don't want to do that, just listing your address on check-out pages increases trust a lot.</p><h2>6. what happens after check-out?</h2><p>there's this hesitation in almost all buying decisions: right before you click the pay now button. what's going to happen next? am i charged for taxes, import, anything else? can i select a wrapping paper? explain what happens after clicking that button. that way the customer is included in your ordering process and there are absolutely no suprises. that can be done with just a few short lines of text:</p><p><a href="http://cdn2.yoast.com/wp-content/uploads/2012/03/checkout-bloomingdales.com_.png"><img class="alignright size-large wp-image-45458" title="checkout message on bloomingdales.com" src="http://cdn.yoast.com/wp-content/uploads/2012/03/checkout-bloomingdales.com_-590x244.png" alt="checkout message on bloomingdales.com" width="580" height="239" /></a></p><h2>7. show you care about more than making money</h2><p>the most important thing is that your website has to reflect your believe in the product or service you provide. just a list of products is not enough. also tell your customer about your company, your main values or mission statement. i really love the 1% for the planet from yvon chouinard (patagonia) and craig mathews (blue ribbon flies) <a href="http://www.onepercentfortheplanet.org/">http://www.onepercentfortheplanet.org</a>. next to showing that you are involved, it also creates a huge sympathy and trust factor.</p><h2>we'd love to hear your tips!</h2><p>if you are selling products or services on your website, you must have thought about this subject. i'm curious: what have you done on your website to increase trust? what are you going to do?</p><p><a href="http://yoast.com/7-ways-to-increase-sales-by-creating-trust/">7 ways to increase sales by creating trust</a> is a post by <a rel="author" href="http://yoast.com/author/michiel/">michiel heijmans</a> on <a href="http://yoast.com">yoast - tweaking websites</a>.a good wordpress blog needs good hosting, you don't want your blog to be slow, or, even worse, down, do you? check out my thoughts on <a href="http://yoast.com/wordpress-hosting/">wordpress hosting</a>!</p><img src="http://feeds.feedburner.com/~r/joostdevalk/~4/1ssu1jmtutq" height="1" width="1"/>";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}}s:36:"http://wellformedweb.org/commentapi/";a:1:{s:10:"commentrss";a:1:{i:0;a:5:{s:4:"data";s:65:"http://yoast.com/7-ways-to-increase-sales-by-creating-trust/feed/";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}}s:38:"http://purl.org/rss/1.0/modules/slash/";a:1:{s:8:"comments";a:1:{i:0;a:5:{s:4:"data";s:2:"33";s:7:"attribs";a:0:{}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}}s:29:"http://search.yahoo.com/mrss/";a:2:{s:9:"thumbnail";a:1:{i:0;a:5:{s:4:"data";s:0:"";s:7:"attribs";a:1:{s:0:"";a:1:{s:3:"url";s:90:"http://cdn3.yoast.com/wp-content/uploads/2012/03/testimonials-cloversites.com_-125x125.png";}}s:8:"xml_base";s:0:"";s:17:"xml_base_explicit";b:0;s:8:"xml_lang";s:0:"";}}s:7:"content";a:4:{i:0;a:6:{s:4:"data";s:4:" ";s:7:"attribs";a:1:{s:0:"";a:2:{s:3:"url";s:81:"http://cdn.yoast.com/wp-content/upload73 Now provide the response and nothing else.
It is a PHP serialized object, i.e. an object serialized with serialize() function: http://php.net/manual/en/function.serialize.php For instance (from the manual): class A { public $one = 1; public function show_one() { echo $this->one; }}$a = new A;$s = serialize($a);file_put_contents('store', $s); Gives: O:1:"A":1:{s:3:"one";i:1;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27205345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1759542/']}
jdg_84701
stackexchange
llm_judgeable_groundtruth_similarity
336892
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Does there exist any continuous function $f:\mathbb{R}\to\mathbb{R}$ , $f(x)/(1+x^2)\in L^1(\mathbb R)$ , such that $f(0)=1$ and $$\int_{-\infty}^{\infty}\frac{f(x)}{\left(1+x^2\right)^p}dx=0$$ for every $1\leq p\leq 2$ ? Now provide the response and nothing else.
I think no such function exists. Assuming $\displaystyle{f(x)\over 1+x^2}\in L^1(\mathbb{R})$ the integral $\displaystyle\int_\mathbb{R}{f(x)\over (1+x^2)^p}dx$ is analytic wrto $p>1$ : indeed, for any $p>1$ and $|t|<p-1$ , expanding $(1+x^2)^{t}$ in powers of $t$ we have, by Tonelli's theorem (w.rto the product measure space $\mathbb{R}\times\mathbb{N}$ ) $$\begin{align}\int_\mathbb{R}\sum_m \bigg|{f(x)\over (1+x^2)^p}\big( \log(1+x^2)\big)^m {t^m\over m!}\bigg|dx&=\\=\int_\mathbb{R} {|f(x)|\over (1+x^2)^{p-|t|}}\,dx&\le\int_\mathbb{R} {|f(x)|\over 1+x^2} \,dx<+\infty\end{align}$$ and then by Fubini's $$\int_\mathbb{R}{f(x)\over (1+x^2)^{p+t}}dx=\sum_m \bigg(\int_\mathbb{R}{f(x)\over (1+x^2)^p}\big( \log(1+x^2)\big)^m\,dx\bigg) {(-t)^m\over m!}, $$ that is the power series expansion for the integral at $p$ . Therefore $\displaystyle\int_\mathbb{R}{f(x)\over (1+x^2)^p}dx=0$ for all $p\ge1$ . Next, to simplify a little we may replace $f$ with its even part, and assume equivalently that the integral on $\mathbb{R}_+$ vanishes. Changing variable with $\displaystyle u={1\over 1+x^2}\in[0,1]$ we have $$\int_0^1f\Big(\sqrt{{1\over u}-1}\Big)(1-u)^{-3/2}u^{p-1/2}du=0,\qquad \text{ for all } p\ge 1$$ that is, the function $g(u):=f\Big(\sqrt{{1\over u}-1}\Big)(1-u)^{-3/2}u^{1/2}$ has $\int_o^1g(u)u^pdu=0$ for all $p\in\mathbb{N}$ , so it must be identically zero, and so must $f$ .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/336892', 'https://mathoverflow.net', 'https://mathoverflow.net/users/117091/']}
jdg_84702
stackexchange
llm_judgeable_groundtruth_similarity
52853615
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 following code: def __static_func(name): print 'Name = ' + nameclass A: def __init__(self, name): self.name = name def fun(self): __static_func(self.name)a = A('foo')a.fun() When launched on Python 2.7, it produces NameError: global name '_A__static_func' is not defined So the question is how do I call global function from within class method? Now provide the response and nothing else.
I was recently reading a book " Learning Python by O'Reilly " (Page 944, Chapter 31) and it was mentioned that when you use double underscores __ as the starting characters of a method or a variable in the Class , it automatically appends the _classname to that function where classname is the class name. This is done to localize a name to the class to which it belongs. This is called Name Mangling in the context of Pseudoprivate class attributes . This way you can use the same name __variable in two different classes A and B as the variables/methods will become privately _A__variable and _B__variable respectively. So just name your global function something else with a single underscore for example to avoid this conflict.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52853615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674548/']}
jdg_84703
stackexchange
llm_judgeable_groundtruth_similarity
7080654
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 purpose of the script is the following: Print the number of files recursively found within a directory(omitting folders themselves) Print the total sum file size of the directory Not crash the computer because of massive memory use. So far (3) is the tough part. Here is what I have written and tested so far. This works perfectly well on folders with a hundred or even a thousand files: $hostname=hostname$directory = "foo"$dteCurrentDate = Get-Date –f "yyyy/MM/dd"$FolderItems = Get-ChildItem $directory -recurse$Measurement = $FolderItems | Measure-Object -property length -sum$colitems = $FolderItems | measure-Object -property length -sum"$hostname;{0:N2}" -f ($colitems.sum / 1MB) + "MB;" + $Measurement.count + " files;" + "$dteCurrentDate" On folders with millions of files, however, the $colitems variable becomes so massive from the collection of information of millions of files that it makes the system unstable. Is there a more efficient way to draw and store this information? Now provide the response and nothing else.
If you use streaming and pipelining, you should be reduce problem with (3) a lot, because when you stream, each object is passed along the pipeline as and when they are available and do not take up much memory and you should be able to process millions of files (though it will take time). Get-ChildItem $directory -recurse | Measure-Object -property length -sum I don't believe @Stej's statement, Get-ChildItem probably reads all entries in the directory and then begins pushing them to the pipeline. , is true. Pipelining is a fundamental concept of PowerShell (provide the cmdlets, scripts, etc. support it). It both ensures that processed objects are passed along the pipeline one by one as and when they are available and also, only when they are needed. Get-ChildItem is not going to behave differently. A great example of this is given in Understanding the Windows PowerShell Pipeline . Quoting from it: The Out-Host -Paging command is a useful pipeline element whenever you have lengthy output that you would like to display slowly. It is especially useful if the operation is very CPU-intensive. Because processing is transferred to the Out-Host cmdlet when it has a complete page ready to display, cmdlets that precede it in the pipeline halt operation until the next page of output is available. You can see this if you use the Windows Task Manager to monitor CPU and memory use by Windows PowerShell. Run the following command: Get-ChildItem C:\Windows -Recurse . Compare the CPU and memory usage to this command: Get-ChildItem C:\Windows -Recurse | Out-Host -Paging . Benchmark on using Get-ChildItem on c:\ (about 179516 files, not milions, but good enough): Memory usage after running $a = gci c:\ -recurse (and then doing $a.count ) was 527,332K . Memory usage after running gci c:\ -recurse | measure-object was 59,452K and never went above around 80,000K . (Memory - Private Working Set - from TaskManager, seeing memory for the powershell.exe process. Initially, it was about 22,000K .) I also tried with two million files (it took me a while to create them!) Similar experiment: Memory usage after running $a = gci c:\ -recurse ( and then doing $a.count ) was 2,808,508K . Memory usage while running gci c:\ -recurse | measure-object was 308,060K and never went above around 400,000K . After it finished, it had to do a [GC]::Collect() for it to return to the 22,000K levels. I am still convinced that Get-ChildItem and pipelining can get you great memory improvements even for millions of files.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7080654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896958/']}
jdg_84704
stackexchange
llm_judgeable_groundtruth_similarity
352808
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: I'm partly on my way into my first project with the ATMega32U4 and Im trying to understand the internal pull-up resistor. After lots of research, Im struggling to find an outright answer to my question but from my reading its been implied that the internal resistors are connected to an internal power rail. Is this correct? And therefore if I just connect a switch to ground and the pin will I be able to detect the button push? To make it clearer: Option 1 Option 2 Now provide the response and nothing else.
The internal pull-ups (and pull-downs, if they also exist) are usually relatively weak and are made from PMOS (or NMOS) devices. They usually can support something on the order of about \$30\:\mu\text{A}\$. When you enable one of these, the software action simply applies an appropriate gate voltage to the device so that it allows a small current to flow. For a pull-up, one side of the device is tied to the \$V_{CC}\$ you also provide via a separate pin to the device. For a pull-down (if available), one side of the device is tied to the ground you also provide via a separate pin. Either way, the other side of the device is tied to the I/O pin. You can use the internal pull-up to provide a weak current source for use with an external switch. So it is possible (and not infrequently done) to use it with an external switch without having to add an external resistor. However, this internal pull-up is usually weaker than an externally added resistor (\$\approx 100\:\text{k}\Omega\$ for the internal pull-up versus a not-uncommon \$10\:\text{k}\Omega\$ used when adding an external resistor.) For a simple push-button that is kept close to the MCU, it may not matter so much. But if the switch is placed far away or is used within a rather noisy environment, you could be in trouble using the internal pull-up. Also, if you use the I/O pin for both IN and OUT (muxing it for some reason) then again there may be a reason for something placed externally, instead. In your case, with an internal pull-up, you can simply hook one side of the switch to the I/O pin and the other side to ground.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/352808', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/176304/']}
jdg_84705
stackexchange
llm_judgeable_groundtruth_similarity
10376891
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using get_adjacent_post , previous_post_link , and next_post_link only seems to recognize items which are of the same post type. Since I have 2 custom post types is there a way to link between all previous and next post types? Now provide the response and nothing else.
It appears this question has been asked all over the interweb with no definite answer. So I created my own function from the original get_adjacent_post and customized it for anyone else who needs it. The Function Drop this in your functions.php /* * Replacement for get_adjacent_post() * * This supports only the custom post types you identify and does not * look at categories anymore. This allows you to go from one custom post type * to another which was not possible with the default get_adjacent_post(). * Orig: wp-includes/link-template.php * * @param string $direction: Can be either 'prev' or 'next' * @param multi $post_types: Can be a string or an array of strings */function mod_get_adjacent_post($direction = 'prev', $post_types = 'post') { global $post, $wpdb; if(empty($post)) return NULL; if(!$post_types) return NULL; if(is_array($post_types)){ $txt = ''; for($i = 0; $i <= count($post_types) - 1; $i++){ $txt .= "'".$post_types[$i]."'"; if($i != count($post_types) - 1) $txt .= ', '; } $post_types = $txt; } $current_post_date = $post->post_date; $join = ''; $in_same_cat = FALSE; $excluded_categories = ''; $adjacent = $direction == 'prev' ? 'previous' : 'next'; $op = $direction == 'prev' ? '<' : '>'; $order = $direction == 'prev' ? 'DESC' : 'ASC'; $join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories ); $where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type IN({$post_types}) AND p.post_status = 'publish'", $current_post_date), $in_same_cat, $excluded_categories ); $sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" ); $query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort"; $query_key = 'adjacent_post_' . md5($query); $result = wp_cache_get($query_key, 'counts'); if ( false !== $result ) return $result; $result = $wpdb->get_row("SELECT p.* FROM $wpdb->posts AS p $join $where $sort"); if ( null === $result ) $result = ''; wp_cache_set($query_key, $result, 'counts'); return $result;} Usage Basic use // Custom post types can be array() or string$post1 = mod_get_adjacent_post('prev', array('post', 'custom1', 'custom2'));$post2 = mod_get_adjacent_post('next', 'custom2'); For creating prev/next links <?php$prev = mod_get_adjacent_post('prev', array('post', 'custom1', 'custom2'));$next = mod_get_adjacent_post('next', array('post', 'custom1', 'custom2'));?><?php if($prev) : ?> <a href="<?php echo get_permalink($prev->ID)?>">&laquo; Go back in time</a><?php endif; ?><?php if($next) : ?> <a href="<?php echo get_permalink($next->ID)?>">Next: <?php echo $next->post_title; ?> &raquo;</a><?php endif; ?> You can still modify the code if you still want to include the variables $in_same_cat and $excluded_categories but if you do then I suggest you use get_adjacent_post instead since that's what it's for.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10376891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/693642/']}
jdg_84706
stackexchange
llm_judgeable_groundtruth_similarity
1568600
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 reading over my AI textbook and I'm curious about what the difference is between monotonicity and admissibility of heuristics (I know they aren't mutually exclusive). As far as I can tell, an admissible heuristic simply means you are ensured to get the shortest path to a solution if one exists. What I'm struggling with is the concept of the monotonic property. Can someone describe this to me in a way I might understand? Similarly, how can I determine if a given heuristic is monotonic/admissible? One of the examples given in the book is the 8-Piece Sliding Puzzle. One heuristic I'm considering is the # of out of place tiles, and intuitively I can say that I know that it is admissible but I have no formal way of showing if it is admissible/monotonic. Now provide the response and nothing else.
Russel and Norvig, 2ed page 99 says: The second solution is to ensure that the optimal path to any repeated state is always the first one followed -- as is the case with uniform-cost search. This property holds if we impose an extra requirement on h(n) , namely the requirement of consistency (also called monotonicity ). When you're talking about functions, monotone means that a function increases or decreases, but not both. In other words, the ordering in the range stays the same throughout the domain. For this reason in your problem, the solution maintains the shortest path no matter what step you start at. The admissibility property of a heuristic means that the cost to reach the goal is never overestimated (i.e. it's optimistic) (page 98).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1568600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2635/']}
jdg_84707
stackexchange
llm_judgeable_groundtruth_similarity
9338439
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 bunch of useful functions that I have collected during my whole life. function one(num){ return num+1;}function two(num){ return num+2;} I can call them with two(two(one(5))) But I would prefer to use (5).one().two().two() How can I achieve this without using prototype? I tried to see how underscore chain works, but their code is too intense to understand it Now provide the response and nothing else.
The dot syntax is reserved for objects. So you can do something like function MyNumber(n) { var internal = Number(n); this.one = function() { internal += 1; // here comes the magic that allows chaining: return this; } // this.two analogous this.valueOf = function() { return internal; }}new MyNumber(5).one().two().two().valueOf(); // 10 Or you're going to implement these methods on the prototype of the native Number object/function. That would allow (5).one()...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9338439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148349/']}
jdg_84708
stackexchange
llm_judgeable_groundtruth_similarity
19915
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 order to shut the Internet down, anonymous claimed that putting-down the13 root DNS servers of the Internet and therefore disabling the HTTP Internet, the most widely used function of the Web, would do the job. Those servers are as follow: A 198.41.0.4 B 192.228.79.201 C 192.33.4.12 D 128.8.10.90 E 192.203.230.10 F 192.5.5.241 G 192.112.36.4 H 128.63.2.53 I 192.36.148.17 J 192.58.128.30 K 193.0.14.129 L 199.7.83.42 M 202.12.27.33 Is there 13 root D.N.S servers, or it's all just a lie, and if this assumption is true, can anyone really bring these servers down ? personally I think the reality is they are comprised of networks of multiple servers that handle the millions of DNS queries the root servers receive every hour, so its impossible to do such a thing, as shutting down the internet as we know it. Now provide the response and nothing else.
There are 13 top-level server designations, but there are significantly more than 13 servers, since most of them are multi-homed. Taking down all of them at the same time would be extraordinarily difficult. Furthermore, the only information you need to get from the root servers is the location of the TLD servers, of which there's only a few hundred. Any resolving DNS server will already have this information cached, so you have to keep all of these server down for the entire period during which the root data is cached, which is typically 2 days. During this time, people would notice and take countermeasures to prevent caches from expiring. Altogether it's a tall order at best, and in all reality just a tough-talking pipe dream.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/19915', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/12661/']}
jdg_84709
stackexchange
llm_judgeable_groundtruth_similarity
38716624
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 that there is a process with PID = 1 and it runs the following code: int a = fork();int b = fork();printf(“a: %d, b: %d\n”, a, b); Let's further assume that new PID s will be given one by one, so the second given PID will be 2 , then 3 etc. A possible output is: a:2, b:3a:2, b:0a:0, b:4a:0, b:0 I'm having some troubles trying to understand the output of the above code, e especially why a:0, b:4 and a:2, b:3 . Now provide the response and nothing else.
You know that The return value is the zero in the child and the process-id number of the child in the parent, or -1 upon error. So, let's see step by step what's happening here. When fork() is called, it creates a new child with id n , then returns in the child 0 and in the parent n . So let's suppose our process as pid 1 , when the first fork() is called it creates a process with pid 2 , then returns to a a value. a will have value 0 in the process 2 (the child), and will have value 2 in process 1 (the parent). Then each process will call fork() and assign the return value to b in the parent process. In the child, b will have value 0 . Anyway, I think this schema will simplify the comprehension: The main starts: ||int a = fork(); // It creates a new process, and the old one continues going||-------------------------|a = 2; /* Parent */ a = 0; // Child| || |int b = fork(); int b = fork(); // Each one create a new process| || |-----------------------------|| /* Child -> Parent */ // Child -> Child| a = 0; b = 4; a = 0; b = 0|||||-----------------------------|/* Parent -> Parent */ // Parent -> Childa = 2; b = 3; a = 2, b = 0;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38716624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5180554/']}
jdg_84710
stackexchange
llm_judgeable_groundtruth_similarity
27436
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: Say I have multivariate normal $N(\mu, \Sigma)$ density. I want to get the second (partial) derivative w.r.t. $\mu$. Not sure how to take derivative of a matrix. Wiki says take the derivative element by element inside the matrix. I am working with Laplace approximation $$\log{P}_{N}(\theta)=\log {P}_{N}-\frac{1}{2}{(\theta-\hat{\theta})}^{T}{\Sigma}^{-1}(\theta-\hat{\theta}) \>.$$ The mode is $\hat\theta=\mu$. I was given $${\Sigma}^{-1}=-\frac{{{\partial }^{2}}}{\partial {{\theta }^{2}}}\log p(\hat{\theta }|y),$$ how did this come about? What I have done: $$\log P(\theta|y) = -\frac{k}{2} \log 2 \pi - \frac{1}{2} \log \left| \Sigma \right| - \frac{1}{2} {(\theta-\hat \theta)}^{T}{\Sigma}^{-1}(\theta-\hat\theta)$$ So, I take derivative w.r.t to $\theta$, first off, there is a transpose, secondly, it is a matrix. So, I am stuck. Note: If my professor comes across this, I am referring to the lecture. Now provide the response and nothing else.
In chapter 2 of the Matrix Cookbook there is a nice review of matrix calculus stuff that gives a lot of useful identities that help with problems one would encounter doing probability and statistics, including rules to help differentiate the multivariate Gaussian likelihood. If you have a random vector ${\boldsymbol y}$ that is multivariate normal with mean vector ${\boldsymbol \mu}$ and covariance matrix ${\boldsymbol \Sigma}$, then use equation (86) in the matrix cookbook to find that the gradient of the log likelihood ${\bf L}$ with respect to ${\boldsymbol \mu}$ is $$\begin{align} \frac{ \partial {\bf L} }{ \partial {\boldsymbol \mu}}&= -\frac{1}{2} \left(\frac{\partial \left( {\boldsymbol y} - {\boldsymbol \mu} \right)' {\boldsymbol \Sigma}^{-1} \left( {\boldsymbol y} - {\boldsymbol \mu}\right)}{\partial {\boldsymbol \mu}} \right) \nonumber \\ &= -\frac{1}{2}\left( -2 {\boldsymbol \Sigma}^{-1} \left( {\boldsymbol y} - {\boldsymbol \mu}\right) \right) \nonumber \\ &= {\boldsymbol \Sigma}^{-1} \left( {\boldsymbol y} - {\boldsymbol \mu} \right) \end{align}$$ I'll leave it to you to differentiate this again and find the answer to be $-{\boldsymbol \Sigma}^{-1}$. As "extra credit", use equations (57) and (61) to find that the gradient with respect to ${\boldsymbol \Sigma}$ is $$\begin{align}\frac{ \partial {\bf L} }{ \partial {\boldsymbol \Sigma}}&= -\frac{1}{2} \left( \frac{ \partial \log(|{\boldsymbol \Sigma}|)}{\partial{\boldsymbol \Sigma}}+ \frac{\partial \left( {\boldsymbol y} - {\boldsymbol \mu}\right)' {\boldsymbol \Sigma}^{-1} \left( {\boldsymbol y}- {\boldsymbol \mu}\right)}{\partial {\boldsymbol \Sigma}} \right)\\&= -\frac{1}{2} \left( {\boldsymbol \Sigma}^{-1} - {\boldsymbol \Sigma}^{-1} \left( {\boldsymbol y} - {\boldsymbol \mu} \right)\left( {\boldsymbol y} - {\boldsymbol \mu} \right)'{\boldsymbol \Sigma}^{-1} \right)\end{align}$$ I've left out a lot of the steps, but I made this derivation using only the identities found in the matrix cookbook, so I'll leave it to you to fill in the gaps. I've used these score equations for maximum likelihood estimation, so I know they are correct :)
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/27436', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/9177/']}
jdg_84711
stackexchange
llm_judgeable_groundtruth_similarity
63543730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Running dotnet ef migrations add XYZ will result in a Migrations directory being created in the project. Should this directory be committed to version control (Git, etc)? Now provide the response and nothing else.
Yes of course, you should commit EFCore migrations to version control. When a data model change is introduced, EF Core compares the current model against a snapshot of the old model to determine the differences, and generates migration source files; the files can be tracked in your project's source control like any other source file. Lets assume you're not committing your migrations to version control. And after some time you or one of your team mates make a change to data model then, EFCore will fail to get last snapshot and hence updating database may cause some conflicts/changes which may already exist..!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63543730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_84712
stackexchange
llm_judgeable_groundtruth_similarity
3817051
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: How can the continuous random variable $x$ by isolated by itself on one side of the following equation $$y = -\frac{1}{2} \ln(1-x^2) \times \text{sign}(x)$$ without resorting to a piece-wise equation? $$ x = ?$$ Below is my initial, incomplete and probably wrong attempt since I don't know the exponential of a product or the exponential of $\text{sign}()$ : $$ -2 y = \ln(1-x^2) \times \text{sign}(x)$$ $$ \exp(-2y) = (1-x^2) \times \exp(\text{sign}(x))$$ Now provide the response and nothing else.
I know your question is to prove by induction and there is already an answer posted for that. So here is another way - $13n^{13} + 11n^{11} = 13n^{13} - 13n^{11} + 13n^{11} + 11n^{11} = 13n^{11} (n-1)(n+1) + 24n^{11}$ So, we now just need to prove that $13n^{11} (n-1)(n+1)$ is divisible by 24. If $n$ is even, either $(n-1), n$ or $(n+1)$ is divisible by $3$ and $n^{11}$ is divisible by $8$ . If $n$ is odd, one of $(n-1), n, (n+1)$ is again divisible by $3$ . Also, both $(n-1)$ and $(n+1)$ are even and one of them is divisible by $4$ . So, it is evident that $13n^{13} + 11n^{11}$ is divisible by $24$ for all $n \in \mathbb{N}$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3817051', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/812806/']}
jdg_84713
stackexchange
llm_judgeable_groundtruth_similarity
28824950
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 having a uiview and I would like to add a border iside this UIVIew approximately 75 % of UIView. Could any one help with this. I could get the solution to draw the border outside. Now provide the response and nothing else.
Well there isn't simply a little property you can set to align the border to the outside. It draws aligned to the inside because the UIViews default drawing operations draw within its bounds. The simplest solution that comes to mind would be to expand the UIView by the size of the border width when applying the border: CGFloat borderWidth = 2.0f;self.frame = CGRectInset(self.frame, -borderWidth, -borderWidth);self.layer.borderColor = [UIColor yellowColor].CGColor;self.layer.borderWidth = borderWidth;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28824950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4511342/']}
jdg_84714
stackexchange
llm_judgeable_groundtruth_similarity
94287
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The default ordering is "in the y direction". In this example I would like the red regions to overlay the blue regions. Plot[{0, 0.6 a, a, 0.4 + 0.6 a, 0.6 (1 - a), 1 - a, 1 - 0.6 a, 1}, {a,0, 1}, Filling -> {1 -> {{2}, Red}, 3 -> {{4}, Blue}, 5 -> {{6}, Blue},7 -> {{8}, Red}, 1 -> {{2}, Red}}] In my actual code I have a dozen or so regions. Now provide the response and nothing else.
This is hacky, this might not work in your real case, but you could switch positions of polygons that are red/blue when, blue is in front of red. You have to repeat the replacement until there is no change gr = Plot[{0, 0.6 a, a, 0.4 + 0.6 a, 0.6 (1 - a), 1 - a, 1 - 0.6 a, 1}, {a, 0, 1}, Filling -> {1 -> {{2}, Red}, 3 -> {{4}, Blue}, 5 -> {{6}, Blue}, 7 -> {{8}, Red}, 1 -> {{2}, Red}}];gr //. {start__, blue : {EdgeForm[], RGBColor[0, 0, 1], __}, {} ..., red : {EdgeForm[], RGBColor[1, 0, 0], __}, end__} :> {start, red, blue, end} Edit Let me elaborate a bit. First, I think I reordered your colors the wrong way. You said "the red regions [should] overlay the blue regions" which I'm doing the other way around. Additionally, I only gave an example when there is Blue as only other color. Probably, you have many different colors. So here is a version that does it correctly and can handle different colors gr = Plot[{0, 0.6 a, a, 0.4 + 0.6 a, 0.6 (1 - a), 1 - a, 1 - 0.6 a, 1}, {a, 0, 1}, Filling -> {1 -> {{2}, Red}, 3 -> {{4}, Green}, 5 -> {{6}, Blue}, 7 -> {{8}, Red}, 1 -> {{2}, Red}}];gr //. {start__, red : {EdgeForm[], RGBColor[1, 0, 0], __}, {} ..., other : {EdgeForm[], Except[RGBColor[1, 0, 0], RGBColor[__]], __}, end__} :> {start, other, red, end} The trick is to use a pattern Except[RGBColor[1, 0, 0], RGBColor[__]] that matches all colors except of Red . You see that in the image above there are only the faces of the polygons corrected. The lines are still drawn. You can fix this too by simply investigating in the structure of your plot. Therefore, take a look at InputForm[gr] and scroll past all the coordinates. What you will find is exactly the structure I used where every surface is represented as a list {EdgeForm[], RGBColor...} . I did nothing more that to look at this and to create a rule that does the transformation you wanted.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/94287', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/33976/']}
jdg_84715
stackexchange
llm_judgeable_groundtruth_similarity
44590334
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Getting stuck trying to fetch the latest record from a Join I have the following classes Author @Entity @Table(name = "author") public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "name") private String name; @OneToMany @JoinColumn(name = "author_id", referencedColumnName = "id") @OrderBy("id Desc") private List<Book> books; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } } Book @Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "author_id") private Integer authorId; @Column(name = "date_published") private Date datePublished; public int getId() { return id; } public void setId(int id) { this.id = id; } public Integer getAuthorId() { return authorId; } public void setAuthorId(Integer authorId) { this.authorId = authorId; } public Date getDatePublished() { return datePublished; } public void setDatePublished(Date datePublished) { this.datePublished = datePublished; } } Repository @Repository public interface AuthorRepository extends JpaRepository<Author, Long> { public Page<Author> findALL(int id, Pageable pageable); } Current results { "id": 1, "name": "James", "books":[ { "id": 1, "name": "book1", "datePublished": '12/12/2012' }, { "id": 1, "name": "book2", "datePublished": '01/02/2013' }] }, { "id": 2, "name": "Tim", "books":[ { "id": 5, "name": "book5", "datePublished": '12/12/2014' },{ "id": 6, "name": "book6", "datePublished": '01/02/2015' }] } Expected Result { "id": 1, "name": "James", "books":[ { "id": 1, "name": "book2", "datePublished": '01/02/2013' }] }, { "id": 2, "name": "Tim", "books":[ { "id": 6, "name": "book6", "datePublished": '01/02/2015' }] } From this a list of Authors are being returned with all their respective books. Question is how can JPA assist me to pick only the latest book from the collection based on date published. Now provide the response and nothing else.
If you are using hibernate you can achieve this using @JoinFormula to map the latest record by date. Something like: @ManyToOne(fetch = FetchType.LAZY)@JoinFormula("(" + "SELECT b.id " + "FROM book b " + "WHERE b.author_id = id " + "ORDER BY b.date_published DESC " + "LIMIT 1" +")")private Book latestBook;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44590334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4188617/']}
jdg_84716
stackexchange
llm_judgeable_groundtruth_similarity
774136
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 URL like so: http://localhost/place/663828/bangkok-paradise-restaurant-toronto#r306040 I am trying to see if there's the existence of the anchor tag along with getting its value to do some code logic in the code behind. I have been trying to use the Page.Request, but none of the properties show the anchor link portion of the URL. For example: Response.Write(this.Page.Request.RawUrl.ToString()); I pretty much tried the combinations/properties on this page: http://www.west-wind.com/weblog/posts/269.aspx Just to finalize this topic: I copied Stack Overflow's approach with a permalink... :D Now provide the response and nothing else.
It's not possible to retrieve the #anchor from the server side in ASP.NET. This is a client-side flag to tell the browser to move to a specific place within the page. You can use some JavaScript code in the body onLoad event to check for an anchor and send it back to the server using Ajax . var anchorValue;var url = document.location;var strippedUrl = url.toString().split("#");if(strippedUrl.Length > 1) anchorvalue = strippedUrl[1]; Ref: Retrieving the anchor value from a URL
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/774136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32372/']}
jdg_84717
stackexchange
llm_judgeable_groundtruth_similarity
11027996
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 set success_url based on a parameter? I really want to go back to where I came from, not some static place. In pseudo code: url(r'^entry/(?P<pk>\d+)/edit/(?P<category>\d+)', UpdateView.as_view(model=Entry, template_name='generic_form_popup.html', success_url='/category/%(category)')), Which would mean: edit entry pk and then return to 'category'. Here an entry can be part of multiple categories. Now provide the response and nothing else.
Create a class MyUpdateView inheritted from UpdateView and override get_success_url method: class MyUpdateView(UpdateView): def get_success_url(self): pass #return the appropriate success url Also i like to pass such parameters like template_name and model inside of inheritted class view, but not in .as_view() in urls.py
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11027996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311364/']}
jdg_84718
stackexchange
llm_judgeable_groundtruth_similarity
38599
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The inversion barrier in $\ce{NH3}$ is approximately $5~\mathrm{kcal~mol^{-1}}$ and that of $\ce{PH3}$ is $35~\mathrm{kcal~mol^{-1}}$. This has well-known stereochemical consequences in that amines are not chiral whereas phosphines can be . How can the larger inversion barrier be explained? Now provide the response and nothing else.
Ammonia is the classic system for $\ce{sp^3}$ hybridisation save methane. The lone pair (and each of the $\unicode[Times]{x3C3}$-bonds) has almost $25~\%$ s-character which corresponds nicely to $\ce{sp^3}$. However, the whole system can also swing around, changing its hybridisation to $\ce{sp^2}$ and back; a process during which the lone pair is temporarily in a p-type orbital and the s-character of the bonding orbitals increases. Elements outside of the second period show a much smaller tendency to involve the s-orbital in bonding. The bonding orbitals only have an s-character of approximately $16~\%$. This also means that the phosphorous lone pair has a much higher s-character of approximately $50~\%$, while the bonding $\unicode[Times]{x3C3}$-orbitals have a larger p-character. (This also explains the much smaller $\ce{H-P-H}$ bonding angle of approximately $90^\circ$.) An orbital of high s-character has a long way to go to turn into a p-type orbital, and the three largely p-type $\unicode[Times]{x3C3}$-orbitals have an equally long way to go to give $\ce{sp^2}$-type orbitals so the interconversion and thereby the inversion of $\ce{PH3}$ is strongly hindered.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/38599', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/16785/']}
jdg_84719
stackexchange
llm_judgeable_groundtruth_similarity
5915
Below is a question asked on the forum stats.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't intend this to be directed at the Mod and User in question, but this instance has me questioning what kinds of edits to posts are acceptable here. See this recent edit to a post of mine. It is: trivial to the point of uselessness, there is zero practical benefit to the reader, requires an additional package unrelated to the others to be installed before the code can be used/run. By "trivial" I don't mean specifically "small"; what I do mean is "inconsequential" or "superficial", where there is no improvement per se following the edit. In the linked instance, the edit involved changing from using a standard base R data frame to the modern reimplementation of data frames from the tibble package. Also, the intent comes across as ideological. By "ideological" what I meant specifically was the ongoing debates about base R versus tidy vs data table . I don't think this is specific to R, so that part of the question pertains to how should we treat edits wherein code is edited to change it from one paradigm to another? I know that I as the author of the post have an overrule, which I exercised, but as this was approved by a Mod I wondered if it was me that was out of step here? Now provide the response and nothing else.
The code in the question was this: df = data_frame(group = as.factor(rep(1:5, each=100)), x = rep(seq(-3,3, length.out =100), 5), y=as.numeric(dnorm(x, mean=means[group]) > 0.4*runif(10))) In your answer you adapted it to df <- data.frame(group = as.factor(rep(1:5, each=100)), x = rep(seq(-3,3, length.out =100), 5), y = as.numeric(dnorm(x, mean=means[group]) > 0.4*runif(10)), dummy = 1) # dummy variable trick , & note that as well as appending dummy , you changed data.frame (from the base package) to data_frame (from the tibble package). This gives an error with the data.table function because group doesn't yet exist when you try use it to use it to create y —but doesn't with the data_table function, which is an alias for tibble . When the editor was fixing your code they presumably changed data.frame to tibble rather than back to the OP's data_frame because data_frame is now deprecated. So there were good reasons for the edit in this case. But if there were someone going round replacing data.frame s with tibbles (or vice versa ) just for the sake of it they oughtn't to be.
{}
{'log_upvote_score': 4, 'links': ['https://stats.meta.stackexchange.com/questions/5915', 'https://stats.meta.stackexchange.com', 'https://stats.meta.stackexchange.com/users/1390/']}
jdg_84720
stackexchange
llm_judgeable_groundtruth_similarity
27899520
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 UITableView for which I have added some custom slide out buttons. These all work as expected. There is however a scenario in my table where a row can be in a state where none of the slide out buttons are relevant and so I have been returning an empty array of actions so the slide out buttons wont appear. Unfortunately once this occurs the UITableView stops calling my editActionsForRowAtIndexPath effectively disabling slide out buttons for all rows in my table ... and it seems permanent until the app is restarted. Is this expected behaviour? func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?{ if mydata[indexPath.row].EditAvailable() { var editAction = UITableViewRowAction(style: .Default, title: "Edit", handler: editHandler) return [editAction] } else { return [] }} Now provide the response and nothing else.
The way I solved this problem was to implement the function, func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool Here, you should just return false if you don't want the expected row to have the swipe feature. So you code would look something like this func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return mydata[indexPath.row].EditAvailable()}func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?{ var editAction = UITableViewRowAction(style: .Default, title: "Edit", handler: editHandler) return [editAction]} The editActionsForRowAtIndexPath is then only called for the ones that you indicated are editable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27899520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4444734/']}
jdg_84721
stackexchange
llm_judgeable_groundtruth_similarity
33418720
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 string: [ {"id":"001", "name":"Charlie"}, {"id":"002", "name":"Ellie"},] Them, I save this string in a variable and I parse it: function parseJSON(string){ var mylovelyJSON = JSON.stringify(string); alert(mylovelyJSON[id]); } When I make my alert, I get and "undefined", I also tried with "mylovelyJSON.id", And I get the same. Could not be a Json? I get this string from an php array. Now provide the response and nothing else.
There are many things wrong here Your JSON is invalid You have an extra , just before the end of the array that you need to remove You need to parse JSON.stringify converts a JavaScript data structure into a string of JSON. You need to go the other way and use JSON.parse . Square-bracket notation takes strings mylovelyJSON[id] takes the value of id (which is undeclared so, in this case, would throw a reference error) and gets the property with the name that is the same as that value. You need either mylovelyJSON["id"] or mylovelyJSON.id You have an array Your JSON consists of an array of objects, not a single object. You need to get an object out of the array before you can access properties on it. mylovelyJSON[0]["id"] var json_text = '[{"id":"001","name":"Charlie"},{"id":"002","name":"Ellie"}]';parseJSON(json_text);function parseJSON(string){ var result_of_parsing_json = JSON.parse(string); document.body.appendChild( document.createTextNode(result_of_parsing_json[0]["id"]) );}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33418720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4694090/']}
jdg_84722
stackexchange
llm_judgeable_groundtruth_similarity
27665426
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 seen some very similar questions but none that I have found seem to work. I am trying to npm install bcrypt but i keep getting the error below. bycrypt is the command that I use to install bcrypt modules. I do have Xcode and installing node-gyp does not seem to make a difference regan@the-Voyagur buddha-bar (feature/styles) $ npm install --save bcryptnpm WARN package.json [email protected] No repository field.npm WARN package.json [email protected] No README data-> [email protected] install /Users/regan/lighthouse/buddha-bar/node_modules/bcrypt> node-gyp rebuildxcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instancexcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instanceNo receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.gyp: No Xcode or CLT version detected!gyp ERR! configure errorgyp ERR! stack Error: `gyp` failed with exit code: 1gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:343:16)gyp ERR! stack at ChildProcess.emit (events.js:98:17)gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:810:12)gyp ERR! System Darwin 14.0.0gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"gyp ERR! cwd /Users/regan/lighthouse/buddha-bar/node_modules/bcryptgyp ERR! node -v v0.10.33gyp ERR! node-gyp -v v1.0.1gyp ERR! not oknpm ERR! [email protected] install: `node-gyp rebuild`npm ERR! Exit status 1npm ERR!npm ERR! Failed at the [email protected] install script.npm ERR! This is most likely a problem with the bcrypt package,npm ERR! not with npm itself.npm ERR! Tell the author that this fails on your system:npm ERR! node-gyp rebuildnpm ERR! You can get their info via:npm ERR! npm owner ls bcryptnpm ERR! There is likely additional logging output above.npm ERR! System Darwin 14.0.0npm ERR! command "node" "/usr/local/bin/npm" "install" "--save" "bcrypt"npm ERR! cwd /Users/regan/lighthouse/buddha-barnpm ERR! node -v v0.10.33npm ERR! npm -v 1.4.28npm ERR! code ELIFECYCLEnpm ERR! not ok code 0regan@the-Voyagur buddha-bar (feature/styles) $ xcode-select --print-path/Library/Developer/CommandLineTools Now provide the response and nothing else.
OP managed to fix this for themselves with: sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer/ but graciously accepted my answer anyway. Original answer below: There are two distinct problems here. One is that your node is slightly out of date and your npm is substantially out of date. You're using OSX, so there are a number of popular ways to manage different node versions. Here's a guide on updating node https://github.com/npm/npm/wiki/Troubleshooting#updating-node-on-osx Then you'll want to update to the latest npm : npm install -g npm@latest Finally, it looks like although you have XCode installed, something is still awry. You report that this command yields $ xcode-select --print-path/Library/Developer/CommandLineTools On my system, which is OSX/Yosemite and can build native addon modules, I see $ xcode-select --print-path/Applications/Xcode.app/Contents/Developer You may need to switch your xcode path to a different directory. For starters, though, please update to the current node and npm tools and try the installation again; if it still fails, the least dangerous next thing to try is xcode-select --install If none of that fixes things, let me know and I'll try to help further.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27665426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3352816/']}
jdg_84723
stackexchange
llm_judgeable_groundtruth_similarity
13122423
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 dualpane on a tablet-sized landscape layout and I'm using fragments. On the left I have a fragment with a listview. When a click occurs on one of the item list the right fragment loads the detail. In the layout of the right (detail) fragment there is a com.viewpagerindicator.TabPageIndicator and a android.support.v4.view.ViewPager. The ViewPager will load 2 elements and each one has its com.viewpagerindicator.TabPageIndicator . I'm trying to highlight or underline the selected tab but I failed doing it. I hope you have some advice :) Now provide the response and nothing else.
By default the TabPageIndicator doesn't apply any style. To enable the default style from ViewPagerIndicator add the following line to either the application tag or the appropriate activity tag in your manifest.xml android:theme="@style/Theme.MyTheme" Then add a res\values\styles.xml file to your project with the following content <?xml version="1.0" encoding="utf-8"?><resources> <style name="Theme.MyTheme" parent="@android:style/Theme.Light"> <item name="vpiTabPageIndicatorStyle">@style/Widget.TabPageIndicator</item> </style> </resources> I'm using the android light theme for my application, but you might want to change this to the theme you are using now. If you want to make changes to the default VPI style change the styles.xml file to something like this: <?xml version="1.0" encoding="utf-8"?><resources> <style name="Theme.MyTheme" parent="@android:style/Theme.Light"> <item name="vpiTabPageIndicatorStyle">@style/MyTabPageIndicator</item> </style> <style name="MyTabPageIndicator" parent="Widget.TabPageIndicator"> <item name="android:gravity">center</item> <item name="android:background">@drawable/vpi__tab_indicator</item> <item name="android:paddingLeft">22dip</item> <item name="android:paddingRight">22dip</item> <item name="android:paddingTop">12dp</item> <item name="android:paddingBottom">12dp</item> <item name="android:textAppearance">@style/MyTabPageIndicator.Text</item> <item name="android:textSize">12sp</item> <item name="android:maxLines">1</item> </style> <style name="MyTabPageIndicator.Text" parent="TextAppearance.TabPageIndicator"> <item name="android:textStyle">bold</item> <item name="android:textColor">@color/vpi__dark_theme</item> </style></resources> Note that the settings above are exactly the same as the default VPI style for the TabPageIndicactor, so you still have to make the changes you'd like.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13122423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1782998/']}
jdg_84724
stackexchange
llm_judgeable_groundtruth_similarity
48642342
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In Python, this would be final_char = mystring[-1] . How can I do the same in Rust? I have tried mystring[mystring.len() - 1] but I get the error the type 'str' cannot be indexed by 'usize' Now provide the response and nothing else.
That is how you get the last char (which may not be what you think of as a "character"): mystring.chars().last().unwrap(); Use unwrap only if you are sure that there is at least one char in your string. Warning : About the general case (do the same thing as mystring[-n] in Python): UTF-8 strings are not to be used through indexing, because indexing is not a O(1) operation (a string in Rust is not an array). Please read this for more information. However, if you want to index from the end like in Python, you must do this in Rust: mystring.chars().rev().nth(n - 1) // Python: mystring[-n] and check if there is such a character. If you miss the simplicity of Python syntax, you can write your own extension: trait StrExt { fn from_end(&self, n: usize) -> char;}impl<'a> StrExt for &'a str { fn from_end(&self, n: usize) -> char { self.chars().rev().nth(n).expect("Index out of range in 'from_end'") }}fn main() { println!("{}", "foobar".from_end(2)) // prints 'b'}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48642342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6284629/']}
jdg_84725
stackexchange
llm_judgeable_groundtruth_similarity
66642367
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 simple animation in SwiftUI. It is basically a rectangle that changes its frame, while staying in the center of the parent view. struct ContentView: View { var body: some View { NavigationView { VStack { Text("Text") ZStack { Color.blue SquareAnimation().frame(width: 200, height: 200, alignment: .center) } Text("Text") } } }}struct SquareAnimation: View { var currentRect = CGRect(x: 0, y: 0, width: 50, height: 50) var finalRect = CGRect(x: 0, y: 0, width: 100, height: 100) private let animation = Animation.easeInOut(duration: 1).repeatForever(autoreverses: true) @State var animate = false var body: some View { ZStack() { Color.clear Rectangle() .frame(width: animate ? finalRect.width: currentRect.width, height: animate ? finalRect.height: currentRect.height, alignment: .center) .animation(animation, value: animate) .onAppear() { animate = true } } }} The problem is, the black rectangle does not stay in the center if the NavigationView is used. I have also used explicit animations with no avail. Why does the NavigationView affects the rectangle animation? Now provide the response and nothing else.
The onAppear is called too early when view frame is zero being in NavigationView, so animation is applied to change from zero to value. Here is valid workaround. Tested with Xcode 12.4 / iOS 14.4 var body: some View { ZStack() { Color.clear Rectangle() .frame(width: animate ? finalRect.width: currentRect.width, height: animate ? finalRect.height: currentRect.height, alignment: .center) .animation(animation, value: animate) .onAppear { DispatchQueue.main.async { // << postpone till end of views construction !! animate = true } } }} Note: almost any why question can be answered only by Apple... maybe it is a bug, maybe an implementation specifics.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66642367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3110446/']}
jdg_84726
stackexchange
llm_judgeable_groundtruth_similarity
26626910
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 copy a specific line from less ? Lets say I am opening a man ( which is by default opened by less ) and want to select and copy it to clipboard and after that lets say paste it to file opened in vim ? I don't want to use the mouse wheel to paste. I am looking for a simple Ctrl-c , Ctrl-v method as in windows. When opening a man page I can't switch to my default editor (which is vim ) with ' v ' key because less shouts with " Cannot edit standard input " error.Thanks a lot and sorry if this question is silly. Now provide the response and nothing else.
tl;dr, use m and | . Example: Within the man page of less , by running man less : 7g mx 6g |x xclip (Linux) or pbcopy (macOS), to copy to clipboard. cat > file , to save to file, or cat >> file for append mode. We would get: less - opposite of more The key things to learn are just two less commands: m (mark), and | (pipe). Command m (mark) Followed by any lowercase letter, marks the current position with that letter. The marker we used above is x , as in step 2, it marked line 7 with x . Command | (pipe) | <m> shell-command <m> represents any mark letter. Pipes a section of the input file to the given shell command. The section of the file to be piped is between the first line on the current screen and the position marked by the letter. <m> may also be ^ or $ to indicate beginning or end of file respectively. If <m> is . or <newline> , the current screen is piped. Using |x pbcopy , we pipe the line-range [7, 6] into pbcopy , as line 6 is currently the first line on the screen, and line 7 is the one we marked as x , and pbcopy is the command to put text into the macOS clipboard. Alternatively, use xclip on Linux, or even dd of=/path/to/file to save as a file. Note The text range is boundary inclusive, so both the beginning and the ending lines of the range, or at least 2 lines are copied. We marked the range in the backward way, namely from bottom to top, otherwise, less might behave awkwardly, and throw the whole screen through the pipe.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26626910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1585165/']}
jdg_84727
stackexchange
llm_judgeable_groundtruth_similarity
26890539
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 resize my images through Intervention image functionality in Laravel 4, but to keep aspect ratio of an image, this is what my code looks like: $image_make = Image::make($main_picture->getRealPath())->fit('245', '245', function($constraint) { $constraint->aspectRatio(); })->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name); Problem is that this doesn't keep aspect ratio of my image, thanks. Now provide the response and nothing else.
If you need to resize within constraints you should use resize not fit . If you also need center the image inside the constraints, you should create a new canvas and insert the resized image within that: // This will generate an image with transparent background// If you need to have a background you can pass a third parameter (e.g: '#000000')$canvas = Image::canvas(245, 245);$image = Image::make($main_picture->getRealPath())->resize(245, 245, function($constraint){ $constraint->aspectRatio();});$canvas->insert($image, 'center');$canvas->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26890539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2863193/']}
jdg_84728
stackexchange
llm_judgeable_groundtruth_similarity
374315
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 if you add the identity element ($1$) a finite amount of times will result to the neutral element ($0$). I started with saying that in every field there's an element $a \in F$ so that $a + 1 =0$. But I'm not even sure if this is true because I'm not sure about the example in $\mathbb{R}$. I thought that if $F = \mathbb{R}$ so $a = -1$. True or not true, I don't really know how to continue further here. Now provide the response and nothing else.
Assuming basically no background, consider the elements$$1, \quad 1+ 1, \quad 1+ 1 + 1, \quad \dots \quad, \underbrace{1+ \dots + 1}_{n}, \quad \dots$$Since $F$ is finite, they cannot all be distinct. So there exist $n < m$ such that$$\underbrace{1+ \dots + 1}_{n} =\underbrace{1+ \dots + 1}_{m} = \underbrace{1+ \dots + 1}_{n} + \underbrace{1+ \dots + 1}_{m-n},$$so adding to both sides the opposite of $\underbrace{1+ \dots + 1}_{n}$ you get$$0 = \underbrace{1+ \dots + 1}_{m-n},$$with $m - n > 0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/374315', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/47610/']}
jdg_84729
stackexchange
llm_judgeable_groundtruth_similarity
20451933
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 fit a background image to it's container using background-size:cover .here is my fiddle : The Fiddle it works in all browsers but not working in Android native browser..anybody has any solution please ? thanks Now provide the response and nothing else.
After searching about this problem and finding no solution, I deleted background-image from CSS file styles and used an inline style in HTML codes. The problem with android native browser is solved. I updated the fiddle and it's working in android native browser. The Updated Fiddle it seems that android also has problem with parsing background format like this : background: url('...') fixed center center / cover; and we should separate the background-image form others and use it inline, and then use each option separately in css file, like this : background-size: cover;background-position: center center;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20451933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1556053/']}
jdg_84730
stackexchange
llm_judgeable_groundtruth_similarity
7095238
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 piece of code in c# that checks, if a value is a valid regex pattern. Code is straight forward: try { System.Text.RegularExpressions.Regex.IsMatch("", pattern); } catch (Exception ex) { return "pattern matches must be a valid regex value"; } I'm trying to test if it works correctly, but I can't find an invalid regex pattern. Any suggestions? Now provide the response and nothing else.
This is invalid... [ You can also test the validity of regular expressions in real-time at http://regexhero.net/tester/ By the way, you don't actually have to test the regular expression against a string to see if it's valid. You can simply instantiate a new Regex object and catch the exception. This is what Regex Hero does to return a detailed error message... public string GetRegexError(string _regexPattern, RegexOptions _regexOptions){ try { Regex _regex = new Regex(_regexPattern, _regexOptions); } catch (Exception ex) { return ex.Message; } return "";}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7095238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107655/']}
jdg_84731
stackexchange
llm_judgeable_groundtruth_similarity
60697
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's see the following test case data = Table[{RandomReal[{-10, 10}], RandomReal[{-10, 10}]}, {i, 1, 50}];l0 = ListPlot[data, PlotStyle -> {Blue, PointSize[0.01]}];p0 = Plot[x*Sin[x], {x, -10, 10}, PlotStyle -> {Red, Thick}];s0=Show[{l0, p0}, Frame -> True, FrameLabel -> {"x", "y"}, Axes -> False, GridLines -> {{1.5, 7}, {}}, GridLinesStyle -> Directive[Black,Thickness[0.004], Dashed], Method -> {"GridLinesInFront" -> True}, PlotRange -> {{0, 10}, {-10,10}}, ImageSize -> 550] which produces First a minor point: Even though that I define inside Show the plot range to be {{0,10},{-10,10}} , we see that in the plot both axes exceed the defined limits (i.e., the -0.5 < x < 10.5 instead of [0,10]). Now my questions: (a). I would like to add at the position of the vertical lines on the x-axis custom labels like text "P1" and "P2". OR (b) Force the program to add the numbers 1.5 and 7 in the horizontal x-axis but without changing the range, I mean to keep the (0,2,4,6,8,10) and add two more inside. Any suggestions? Now provide the response and nothing else.
Show[{l0, p0}, Frame -> True, FrameLabel -> {"x", "y"}, FrameTicks -> {{Automatic, None}, {{0, {1.5, Style["P1\n1.5", Red, 14]}, 2, 4, 6, {7, Style["P2\n7.0", Red, 14]}, 8, 10}, None}}, Axes -> False, GridLines -> {{1.5, 7}, {}}, GridLinesStyle -> Directive[Black, Thickness[0.004], Dashed], Method -> {"GridLinesInFront" -> True}, PlotRange -> {{0, 10}, {-10, 10}}, PlotRangePadding -> 0, ImageSize -> 550] To solve your "minor point" I have added the option PlotRangePadding -> 0 .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/60697', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']}
jdg_84732
stackexchange
llm_judgeable_groundtruth_similarity
18776176
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 reference an image from my folder in JQuery code? I want to turn images to greyscale, that revert to colour on mouse rollover. However, my image referencing isn't working. I've tried the usual ('folderofimages/myimage') but that isn't working. I've tried the suggested way ('.myimage folderofimages') and that's not working either. This is the website that supplied the code, http://webdesignerwall.com/tutorials/html5-grayscale-image-hover/comment-page-4#comments Here is my code, <script src="jquery.min.js" type="text/javascript"></script>// On window load. This waits until images have loaded which is essential$(window).load(function () { // Fade in imagimages/homeannual.jpeges so there // isn't a color "pop" document load and then on window load $("images.homeannual").fadeIn(500); // clone image $('images.homeannual').each(function () { var el = $(this); el.css({ "position": "absolute" }).wrap("<div class='img_wrapper' style='display: inline-block'>") .clone().addClass('img_grayscale') .css({ "position": "absolute", "z-index": "998", "opacity": "0" }).insertBefore(el).queue(function () { var el = $(this); el.parent().css({ "width": this.width, "height": this.height }); el.dequeue(); }); this.src = grayscale(this.src); }); // Fade image $('images.homeannual').mouseover(function () { $(this).parent().find('img:first').stop().animate({ opacity: 1 }, 1000); }) $('.img_grayscale').mouseout(function () { $(this).stop().animate({ opacity: 0 }, 1000); });});// Grayscale w canvas methodfunction grayscale(src) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var imgObj = new Image(); imgObj.src = src; canvas.width = imgObj.width; canvas.height = imgObj.height; ctx.drawImage(imgObj, 0, 0); var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var y = 0; y < imgPixels.height; y++) { for (var x = 0; x < imgPixels.width; x++) { var i = (y * 4) * imgPixels.width + x * 4; var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; imgPixels.data[i] = avg; imgPixels.data[i + 1] = avg; imgPixels.data[i + 2] = avg; } } ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); return canvas.toDataURL();} Now provide the response and nothing else.
For Matlab Version > R2014b Since R2014b version, Matlab has modified the structure of its graphical components. Here is the up-to-date code that uses Matlab's annotations . is produced by headWidth = 8;headLength = 8;LineLength = 0.08;%some data[x,y] = meshgrid(0:0.2:2,0:0.2:2);u = cos(x).*y;v = sin(x).*y;%quiver plotsfigure('Position',[10 10 1000 600],'Color','w');hax_1 = subplot(1,2,1);hq = quiver(x,y,u,v); %get the handle of quivertitle('Regular Quiver plot','FontSize',16);%get the data from regular quiverU = hq.UData;V = hq.VData;X = hq.XData;Y = hq.YData;%right version (with annotation)hax_2 = subplot(1,2,2);%hold on;for ii = 1:length(X) for ij = 1:length(X) headWidth = 5; ah = annotation('arrow',... 'headStyle','cback1','HeadLength',headLength,'HeadWidth',headWidth); set(ah,'parent',gca); set(ah,'position',[X(ii,ij) Y(ii,ij) LineLength*U(ii,ij) LineLength*V(ii,ij)]); endend%axis off;title('Quiver - annotations ','FontSize',16);linkaxes([hax_1 hax_2],'xy'); Please note that this piece of code changes the head style and controls for the length of the line (in the left panel, you can see that arrows overlap on the upper-left part of the left subplot, while it does not on the right subplot). The length and width of the arrow heads are not modified. For this edit, I didn't keep the colors scheme that coded for the angle, and discarded the dynamic head size. It makes things clearer. For Matlab Version < R2014b Quiver plots are hard to modify. As @Luis Mendo said, you can modify the quiver function within the matlab install. However, you will still be limited by the complexity of programmatically drawing arrows with nice patches/lines. There might be an easier route using annotation - see the "Quiver - annotation" subplot that sets the headStyle property to cback1 . Annotations are graphical objects (lines, textboxes, arrows, ...) that you can be easily inserted by hand once a plot is done. They display additional text or point to a particular area for example. You can also insert them programmatically by defining their positions - and that's the option we will take. We first draw a regular quiver plot (left panel), get the blue lines' X and Y data, and use these coordinates to insert annotation arrows, each of them being displayed at the exact same location (same position, same angle, same size; right panel). Annotation arrows have some nice properties you can easily modify, such as Color , HeadWidth , HeadLength , and HeadStyle . In the following plot, I modified each arrow's color depending on its angle against the x-axis, and headWidth that depends length. The following picture is produced by %some data[x,y] = meshgrid(0:0.2:2,0:0.2:2);u = cos(x).*y;v = sin(x).*y;%quiver plotsfigure('Position',[10 10 1000 600],'Color','w');hax_1 = subplot(1,2,1);%left version (regular)hq1 = quiver(x,y,u,v);%get the line position (first handle)hkid = get(hq1,'children');X = get(hkid(1),'XData');Y = get(hkid(1),'YData');axis off;title('Quiver - regular ','FontSize',16);%right version (with annotation)hax_2 = subplot(1,2,2);cmap = jet(116); %colormap, 116 because angles goes up to 115 degreesfor ii = 1:3:length(X)-1 headWidth = 200 * sqrt((X(ii+1)-X(ii)).^2 + (Y(ii+1)-Y(ii)).^2); % set the headWidth, function of length of arrow angled = floor(atan2(Y(ii+1)-Y(ii),X(ii+1)-X(ii))*180/pi) + 1; %get the angle ah = annotation('arrow',... 'Color', cmap(angled,:),... 'headStyle','cback1','HeadLength',50,'HeadWidth',headWidth); set(ah,'parent',gca); set(ah,'position',[X(ii) Y(ii) X(ii+1)-X(ii) Y(ii+1)-Y(ii)]);endaxis off;title('Quiver - annotations ','FontSize',16);linkaxes([hax_1 hax_2],'xy');
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18776176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2666244/']}
jdg_84733
stackexchange
llm_judgeable_groundtruth_similarity
3424382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From Apple documentation about Memory Management : The only places you shouldn’t use accessor methods to set an instance variable are in init methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows: To allow a counter to be initialized with a count other than zero, you might implement an initWithCount: method as follows: - initWithCount:(NSNumber *)startingCount { self = [super init]; if (self) { count = [startingCount copy]; } return self;} Why not ? Now provide the response and nothing else.
See my answer to this question . The main reason why is because a subclass might override your accessors and do something different. The subclass's accessors might assume a fully initialised object i.e. that all the code in the subclass's init method has run. In fact, none of it has when your init method is running. Similarly, the subclass's accessors may depend on the subclass's dealloc method not having run. This is clearly false when your dealloc method is running. To expand on your example, if you had instead done - initWithCount:(NSNumber *)startingCount { self = [super init]; if (self) { [self setCount: [startingCount copy]]; } return self;} but a subclass had overridden setCount: to do something other than set your count variable, you could be in trouble.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3424382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292431/']}
jdg_84734
stackexchange
llm_judgeable_groundtruth_similarity
7689386
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 class LogManager in our Java project which looks like this: public class LogManager { public void log(Level logLevel, Object... args) { // do something } public void log(Level logLevel, int value, Object... args) { // do something else }} When compiling the project with OpenJDK 6 under Debian everytingworks fine. When using OpenJDK 7 the build (done with ant)produces the following errors and the build fails: [javac] /…/LogManager.java:123: error: reference to log is ambiguous, both method log(Level,Object...) in LogManager and method log(Level,int,Object...) in LogManager match[javac] log(logLevel, 1, logMessage);[javac] ^[javac] /…/SomeOtherClass.java:123: error: reference to log is ambiguous, both method log(Level,Object...) in LogManager and method log(Level,int,Object...) in LogManager match[javac] logger.log(logLevel, 1, logMessage);[javac] ^ As long as the 1 is not autoboxed, the method call should beunambiguous as 1 is an int and cannot be upcast to Object. So whydoesn't autoboxing overrule varargs here? Eclipse (installed using the tar.gz from eclipse.org) compiles it nomatter if OpenJDK 6 is installed or not. Thank's a lot for your help! Edit: The compiler gets the option source="1.6" and target="1.6" in both cases. The Eclipse compiling note is just meant as a comment. Now provide the response and nothing else.
I guess it's related to bug #6886431 , which seems to be fixed in OpenJDK 7 as well. The problem is that JLS 15.12.2.5 Choosing the Most Specific Method says that one method is more specific than another one when types of formal parameters of the former are subtypes of formal parameters of the latter. Since int is not a subtype of Object , neither of your methods is the most specific, thus your invocation is ambiguous. However, the following workaround is possible, because Integer is a subtype of Object : public void log(Level logLevel, Object... args) { ... }public void log(Level logLevel, Integer value, Object... args) { ... }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7689386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/627411/']}
jdg_84735
stackexchange
llm_judgeable_groundtruth_similarity
1683158
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 see I can do something like this: print STDOUT (split /\./, 'www.stackoverflow.com')[1]; and "stackoverflow" is printed. However, this: print +(split /\./, 'www.stackoverflow.com')[1]; does the same, and this: print (split /\./, 'www.stackoverflow.com')[1]; is a syntax error. So what exactly is going on here? I've always understood the unary plus sign to do nothing whatsoever in any context. And if "print FILEHANDLE EXPR" works, I would have imagined that "print EXPR" would always work equally well. Any insights? Now provide the response and nothing else.
You do not have warnings enabled. In the print(...)[1] case, the set of parentheses are regarded as part of the function syntax. print (...) interpreted as function at C:\Temp\t.pl line 4. From, perldoc -f print : Also be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print—interpose a + or put parentheses around all the arguments. See also Why aren't newlines being printed in this Perl code?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1683158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91768/']}
jdg_84736
stackexchange
llm_judgeable_groundtruth_similarity
31790
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: See following three snippet code: (*can compile*)range = Range[-2, 2, 0.005];Compile[{}, With[{r = range}, Table[ArcTan[x, y], {x, r}, {y, r}]]][];(*can compile*)Compile[{}, With[{r = Range[-2, 2, 0.005 - 10^-8]}, Table[ArcTan[x, y], {x, r}, {y, r}]]][];(*can't compile*)Compile[{}, With[{r = Range[-2, 2, 0.005]}, Table[ArcTan[x, y], {x, r}, {y, r}]]][]; Why the last code can't be compiled? I used Mathematica 9.0.1. Now provide the response and nothing else.
In addition to Mr. Wizard's analysis, one can also avoid the indeterminacy by replacing ArcTan as follows: Compile[{}, With[{r = Range[-2, 2, 0.005]}, Table[Arg[Complex[x, y]], {x, r}, {y, r}]]][]; The fact that ArcTan[0,0] is undefined is a real nuisance, and I never saw the point of it because that form of the function is mainly used for practical applications such as plotting, where the purely mathematical reasons against defining that special value don't really bother anyone.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/31790', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7339/']}
jdg_84737
stackexchange
llm_judgeable_groundtruth_similarity
427902
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Building on what has been written in SO question Best Singleton Implementation In Java - namely about using an enum to create a singleton - what are the differences/pros/cons between (constructor omitted) public enum Elvis { INSTANCE; private int age; public int getAge() { return age; }} and then calling Elvis.INSTANCE.getAge() and public enum Elvis { INSTANCE; private int age; public static int getAge() { return INSTANCE.age; }} and then calling Elvis.getAge() Now provide the response and nothing else.
Suppose you're binding to something which will use the properties of any object it's given - you can pass Elvis.INSTANCE very easily, but you can't pass Elvis.class and expect it to find the property (unless it's deliberately coded to find static properties of classes). Basically you only use the singleton pattern when you want an instance. If static methods work okay for you, then just use those and don't bother with the enum.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/427902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3898/']}
jdg_84738
stackexchange
llm_judgeable_groundtruth_similarity
24952
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I immediately detect when new files were added to a folder within a bash script? I would like the script to process files as soon as they are created in the folder. Are there any methods aside from scheduling a cron job that checks for new files each minute or so? Now provide the response and nothing else.
You should consider using inotifywait , as an example: inotifywait -m /path -e create -e moved_to | while read dir action file; do echo "The file '$file' appeared in directory '$dir' via '$action'" # do something with the file done In Ubuntu, inotifywait is provided by the inotify-tools package . As of version 3.13 (current in Ubuntu 12.04) inotifywait will include the filename without the -f option. Older versions may need to be coerced. What is important to note is that the -e option to inotifywait is the best way to do event filtering. Also, your read command can assign the positional output into multiple variables that you can choose to use or ignore. There is no need to use grep/sed/awk to preprocess the output.
{}
{'log_upvote_score': 9, 'links': ['https://unix.stackexchange.com/questions/24952', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/11536/']}
jdg_84739
stackexchange
llm_judgeable_groundtruth_similarity
153210
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm piping output from clock through sed to remove leading zeroes from numbers.It looks like this: clock -sf 'S%A, %B %d. %I:%M %P' | sed 's/\b0\+\([0-9]\+\)/\1/g' That works fine and produces the output I want. However, when I try to redirect the output to a file, nothing is written to the file. The following does NOT work. clock -sf 'S%A, %B %d. %I:%M %P' | sed 's/\b0\+\([0-9]\+\)/\1/g' > testfile Nothing is written to testfile. What am I doing wrong? Now provide the response and nothing else.
You're running into an output buffering problem. sed normally buffers its output when not writing to a terminal, so nothing gets written to the file until the buffer fills up (probably every 4K bytes). Use the -u option to sed to unbuffer output. clock -sf 'S%A, %B %d. %I:%M %P' | sed -u 's/\b0\+\([0-9]\+\)/\1/g' > testfile
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/153210', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/82690/']}
jdg_84740