qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
**What paradox?** All ships are 100% automatic (it doesn't matter if it they are or not, it's just easier for the explanation). The moment my ship detects the enemy ship, it fires the weapon. The very moment the circuits activate the weapon, my enemy is hit. Ditto for my enemy, which did the same to me. Where's the paradox? If my ship detected the enemy ship first, the enemy ship won't get a shot off. If the enemy ship detected my ship first, I won't get a shot off. If we detected each other simultaneously, neither of us will be around to argue about whether or not there was a paradox. **But I want a rule!** I literally can think of only one scenario where a paradox can occur. Your detonation can occur ***before*** the weapon is activated. In that case, the paradox of your ship destroying another ship, but you were destroyed before you activated your weapon, could occur. **Rule:** don't do that. Regardless the range you wish to give your weapon, no detonation can occur before the weapon is activated. In other words, time travel in your universe is causal. No paradox can occur because no effect can occur without the cause that brought the effect about. *And why do you want your rule? Because if you didn't then all it would take is one drunken sailor ordered to fire the weapon to look at his friend and say, "watch, this will be funny" and not push the button to rip all of space and time apart. You don't want that. Nobody wants that. Well, psychopaths might want that. But we're not psychopaths, right? RIGHT?*
I think the paradox can be resolved by adding a necessary delay: mass prevents time travel. The mass of the firing ship means the weapon needs to travel a bit before it can start traveling backwards, and the mass of the target ship likewise causes the weapon to reenter normal time a short distance away. Just tune the effect so the arrival time is too small to allow a response and the weapon will largely function like you want. The mass of the weapon itself isn't relevant, as the whole thing will time travel. The relative masses of the two ships is also not important, as the departure delay for one ship;s weapon will equal the arrival delay for the other ship's weapon, so the total trip is functionally symmetrical in both directions (less massive ships would have a slight advantage in departure time, but an equal disadvantage in arrival time). So simultaneous shots will both arrive, as the two shots will have time to travel before their source is destroyed. Near simultaneous shots will also result in both ships being destroyed, due to the delays. Super massive ships (I'm thinking planetoid mass) would have enough arrival delay to respond with point weapons, but the cost to make, move, and maintain such a ship would be prohibitive. Likewise, the time travel feature of the weapon isn't usable too close to a planet, or more likely inside a solar system at all. Maybe outer reaches are low mass enough. Battle fields with asteroids or debris or whatever would require carefully aimed shots to avoid having the weapon knocked out of time travel too soon.
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
Suppose that [Novikov's self-consistency principle](https://en.wikipedia.org/wiki/Novikov_self-consistency_principle) applies. In this scenario, there are two outcomes that are each self-consistent: ship A destroys ship B before ship B fires, or ship B destroys ship A before ship A fires. Which of these outcomes actually occurs is a matter of random quantum mechanical probability, determined by a sum-over-histories wavefunction result that I suspect may be infeasible to calculate for any semi-realistic scenario at this scale.
The flight time of the weapon is instantaneous, in effect. It's just as if the two ships were literally touching nose-to-nose. It is asked about what happens if "the ships fired at the same time." Same thing happens as would happen were they nose to nose, I suppose. Either "the same time" really means plus or minus a few seconds or milliseconds, and one ship is destroyed before it can fire, or, if it is truly instantaneous, it depends on whether the weapons are such that they can complete firing while being destroyed.
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
**there is no Paradox** As written in the question > > Then your shot travels back in time 5 minutes as it closes the distance > > > the shot doesn't begin its trajectory 5 min back and then travels to the enemy. Instead it travels back in time by moving toward the enemy. So i agree with ivo's comment and mostly with JBH' answer except for his proposed paradox. Because the shot isn't send back in time but travels backwards while moving there is no way to detect it before it hits. It would just seem to materialize into the enemy ship. It seems to me that this is just a "teleportation weapon" in effect. You press a button, and in that instant your projectile hits. No time to dodge or even realize something is closing in, so no chance for dodging and the resulting paradox. (To be fair this is a jab at the other proposed answers, because they use it as an example of the loop that can result when the shot is **send back in time and then travels** toward the enemy.) On a timeline it would seem to work like this: T0 You spot the enemy. T0 You fire and see the enemy getting hit. In full: T-5 The enemy reflects the light you see at T0, your projectile hits. T-4 Your shot has traversed 80% of the distance and moved 4 min backwards in time. T-3 Your shot has traversed 60% of the distance and moved 3 min backwards in time. T-2 Your shot has traversed 40% of the distance and moved 2 min backwards in time. T-1 Your shot has traversed 20% of the distance and moved 1 min backwards in time. T0 You spot the enemy. T0 You fire and see the enemy getting hit.
Whoever hits first gets to control the timeline. ================================================ If ship A hits ship B first, then ship B can't fire at ship A. Therefore, their temporal projectile vanishes, and they do no harm. Example. 1. Ship A's projectile goes back in time and Ship A and B fly unaware. 2. Ship A and Ship B see each other. 3. Both ships prepare to fire back in time, but Ship A fires first. 4. Ship B explodes immediately from the back in time projectile.
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
**there is no Paradox** As written in the question > > Then your shot travels back in time 5 minutes as it closes the distance > > > the shot doesn't begin its trajectory 5 min back and then travels to the enemy. Instead it travels back in time by moving toward the enemy. So i agree with ivo's comment and mostly with JBH' answer except for his proposed paradox. Because the shot isn't send back in time but travels backwards while moving there is no way to detect it before it hits. It would just seem to materialize into the enemy ship. It seems to me that this is just a "teleportation weapon" in effect. You press a button, and in that instant your projectile hits. No time to dodge or even realize something is closing in, so no chance for dodging and the resulting paradox. (To be fair this is a jab at the other proposed answers, because they use it as an example of the loop that can result when the shot is **send back in time and then travels** toward the enemy.) On a timeline it would seem to work like this: T0 You spot the enemy. T0 You fire and see the enemy getting hit. In full: T-5 The enemy reflects the light you see at T0, your projectile hits. T-4 Your shot has traversed 80% of the distance and moved 4 min backwards in time. T-3 Your shot has traversed 60% of the distance and moved 3 min backwards in time. T-2 Your shot has traversed 40% of the distance and moved 2 min backwards in time. T-1 Your shot has traversed 20% of the distance and moved 1 min backwards in time. T0 You spot the enemy. T0 You fire and see the enemy getting hit.
Seems to ME that it's really contingent on the mechanic by which you decide time "actually" functions. Even Einstein and Hawking kinda "settled" into the whole infinite parallel universe thing for lack of better means to reconcile these sort of incongruities. Fact is, for you to have cause and effect, action/reaction, determinism/consequence, there's ALWAYS a sequence of events. And there's one thing nearly all those theoretical physicists DO agree on: time is relative from the point of view of the observer. So my suggestion would be reductionism: break the sequence of events down into smaller and smaller chunks and ultimately there's no paradox. Yes, it's possible one party is retroactively "deleted" from the timeline. Whereupon, for the frame of reference of their opponent, they never fired. They ceased before it could become a conflict. And since their opponent, too is submerged in the same stream of time, they, perforce, would be unable to perceive any sort of potential paradox. Or, take the string theory approach and assuming every choice bifurcates into every possible choice, and obviate the potential for it entirely. Personally, I think the mechanic by which the characters could have perceived an event taking place that was subsequently balefire'd out of existence *yet they still remember it* would/could/***should*** be harder to explain than the nitty gritty of the temporal torpedo... but maybe that's just me.
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
Frame challenge --------------- A time-travel paradox is by definition an inconsistency that cannot be resolved. This is why people think it's so important to avoid them: because it is logically impossible to resolve a paradox if one arises. Thus, there is no "logically consistent" way for this to happen. You are going to have to invent some new rule that defies ordinary logic. As the author, you can do this! As the author, you cannot decide whether your audience will buy it. We like to think that one of the best ways to ensure that audiences will accept our narratives is if we stick within the bounds of conventional reason. But works like Star Wars and Star Trek do all kinds of things that are patently absurd, and that has not stopped countless people from enjoying them.
The flight time of the weapon is instantaneous, in effect. It's just as if the two ships were literally touching nose-to-nose. It is asked about what happens if "the ships fired at the same time." Same thing happens as would happen were they nose to nose, I suppose. Either "the same time" really means plus or minus a few seconds or milliseconds, and one ship is destroyed before it can fire, or, if it is truly instantaneous, it depends on whether the weapons are such that they can complete firing while being destroyed.
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
Frame challenge --------------- A time-travel paradox is by definition an inconsistency that cannot be resolved. This is why people think it's so important to avoid them: because it is logically impossible to resolve a paradox if one arises. Thus, there is no "logically consistent" way for this to happen. You are going to have to invent some new rule that defies ordinary logic. As the author, you can do this! As the author, you cannot decide whether your audience will buy it. We like to think that one of the best ways to ensure that audiences will accept our narratives is if we stick within the bounds of conventional reason. But works like Star Wars and Star Trek do all kinds of things that are patently absurd, and that has not stopped countless people from enjoying them.
I think the paradox can be resolved by adding a necessary delay: mass prevents time travel. The mass of the firing ship means the weapon needs to travel a bit before it can start traveling backwards, and the mass of the target ship likewise causes the weapon to reenter normal time a short distance away. Just tune the effect so the arrival time is too small to allow a response and the weapon will largely function like you want. The mass of the weapon itself isn't relevant, as the whole thing will time travel. The relative masses of the two ships is also not important, as the departure delay for one ship;s weapon will equal the arrival delay for the other ship's weapon, so the total trip is functionally symmetrical in both directions (less massive ships would have a slight advantage in departure time, but an equal disadvantage in arrival time). So simultaneous shots will both arrive, as the two shots will have time to travel before their source is destroyed. Near simultaneous shots will also result in both ships being destroyed, due to the delays. Super massive ships (I'm thinking planetoid mass) would have enough arrival delay to respond with point weapons, but the cost to make, move, and maintain such a ship would be prohibitive. Likewise, the time travel feature of the weapon isn't usable too close to a planet, or more likely inside a solar system at all. Maybe outer reaches are low mass enough. Battle fields with asteroids or debris or whatever would require carefully aimed shots to avoid having the weapon knocked out of time travel too soon.
235,943
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be. For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago. While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
2022/09/22
[ "https://worldbuilding.stackexchange.com/questions/235943", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/57832/" ]
Whoever hits first gets to control the timeline. ================================================ If ship A hits ship B first, then ship B can't fire at ship A. Therefore, their temporal projectile vanishes, and they do no harm. Example. 1. Ship A's projectile goes back in time and Ship A and B fly unaware. 2. Ship A and Ship B see each other. 3. Both ships prepare to fire back in time, but Ship A fires first. 4. Ship B explodes immediately from the back in time projectile.
Seems to ME that it's really contingent on the mechanic by which you decide time "actually" functions. Even Einstein and Hawking kinda "settled" into the whole infinite parallel universe thing for lack of better means to reconcile these sort of incongruities. Fact is, for you to have cause and effect, action/reaction, determinism/consequence, there's ALWAYS a sequence of events. And there's one thing nearly all those theoretical physicists DO agree on: time is relative from the point of view of the observer. So my suggestion would be reductionism: break the sequence of events down into smaller and smaller chunks and ultimately there's no paradox. Yes, it's possible one party is retroactively "deleted" from the timeline. Whereupon, for the frame of reference of their opponent, they never fired. They ceased before it could become a conflict. And since their opponent, too is submerged in the same stream of time, they, perforce, would be unable to perceive any sort of potential paradox. Or, take the string theory approach and assuming every choice bifurcates into every possible choice, and obviate the potential for it entirely. Personally, I think the mechanic by which the characters could have perceived an event taking place that was subsequently balefire'd out of existence *yet they still remember it* would/could/***should*** be harder to explain than the nitty gritty of the temporal torpedo... but maybe that's just me.
31,887,289
I have a database with 150,000 records and I need to match its FULL column value or records, with some parts of the string. \*\* > > As i want to check if the **STRING** contains the **COLUMN** records and NOT! > if the COLUMN contains the string > > > \*\* *(Example below)* For testing purposes Lets say the database has a ***TABLE*** , 1 ***COLUMN*** and 1 record as the records are similar to this: > > * **come to me** > > > and i need to match it with this ***@STRING*** > > * She wants to **come to me** now > > > I want to execute something similar to :*(but this doesn't work of course)* ``` SELECT * from TABLE where @STRING like '%'+COLUMN+'%' ``` I can't seem to solve this with SQL the usage of PHP is possible but prefer if the solution is with SQL but if the solution with PHP is available please propose it *and note that the database has over 150,000 records*
2015/08/07
[ "https://Stackoverflow.com/questions/31887289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1276429/" ]
``` SELECT * from TABLE where LOCATE(COLUMN, @STRING)>0; ``` LOCATE(a,b) returns a number giving the character location of a in b, or returns 0. See [Mysql LOCATE()](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_locate) The docs discuss that LOCATE() is only case sensitive when one of the strings is a 'binary string'. That probably doesn't affect your use case, though if it became an issue you could CONVERT() the binary strings to a locale and use LOWER() to get lower case. [MySQL String Functions](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html)
The dynamic like syntax for mysql is ``` SELECT * from TABLE where @STRING like CONCAT('%',COLUMN,'%') ```
5,492,987
I have a deep recursive process that outputs a list when it finds a solution to the problem, but this list is created very deep recursively. This is the code: ``` (define (dfs start target) (define (dfs-helper start target path new-links final-path) (display final-path) (newline) (if (null? final-path) (if (or (null? new-links) (member start path)) '() (first-not-null (lambda (x) (if (= start target) (dfs-helper x target path '() (append path (list start))) (dfs-helper x target (append path (list start)) (get-neighbors x) final-path))) (get-neighbors start)) ) final-path ) ) (dfs-helper start target '() (get-neighbors start) '()) ) ``` (I alologize for the strange formatting) Anyway, this outputs the following: ``` ... () () (1 7 20 15 22 23 39 40 49 41 31 25 17 18 9 19 26 36 27 12 11 10 3 13 14 21 28 37 43 53 44 52 51 42 50 54 57 58 61 62 60 63) 7 ``` It's that second from the last line that I need. As you can see, when I display 'final-path' I get what I want, but for some reason (I think because of all the recursive calls) the actual variable at the end is just 7, not the list of all the numbers I want. How can I get my code to output that second from the last line, so I can manipulate the list it returns?
2011/03/30
[ "https://Stackoverflow.com/questions/5492987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668750/" ]
Oog... this code can be a bunch simpler. Let me make some suggestions. First, defining the helper inside of the parent function is not helping you; it makes it impossible to test independently; move it outside. Next, it's not clear to me why you have two arguments, "path" and "final-path"; a one-line purpose statement would be *really* helpful here. Part of this is deciding what your function is supposed to return on failure. Finally, you *really really* need some test cases that show what the thing is supposed to produce for simple inputs. I realize that it's entirely possible that you're looking for a "quick fix"; I should tell you that a solution that throws a mutable variable on top of the other stuff going on would certainly not a get a good grade in my class... Apologies in advance for my supercilious tone :).
rather than displaying `final-path` with a newline as a print-out where you can't get to it, create a list as a member of your `dfs` object. Then append onto that list member, and process that list on the return of `dfs`. For instance: ``` (define (dfs start target) (define return-list '()) ;;add a return list here that you will process later (define (dfs-helper start target path new-links final-path) ;;(display final-path) (newline) (set! return-list (cons final-path return-list)) ;;so you are now "building up" the return list (if (null? final-path) (if (or (null? new-links) (member start path)) '() (first-not-null (lambda (x) (if (= start target) (dfs-helper x target path '() (append path (list start))) (dfs-helper x target (append path (list start)) (get-neighbors x) final-path))) (get-neighbors start)) ) final-path ) ) (dfs-helper start target '() (get-neighbors start) '()) ;;process the return-list value to get the values you're wanting from it ... ;;I'm guessing there is something specific you're looking for, i.e., you can ;;filter out all the empty-list elements, single-value elements, etc. ) ```
50,241,866
I am trying to load test a HTTP URL(Dynamic) using Locust.io. I already have the python scripts that will make a GET call to the URL. The challenge i am facing is, the urls and the number of users are dynamic and are read from a CSV file. For example, Here is how the input of the load testing will look like: Input.csv: ``` ============ URLs No of users to simulate ============================================= URL 1 1000 URL 2 5000 URL 3 2000 URL 4 1000 ``` Each url in the CSV is unique and the number of users to simulate change for every url. i would like to use the locust load testing in distributed mode. For example, Locust master will read URL 1 and send it to Slave 1 to simulate 1000 users. and then pick URL2 and send it to Slave 2 to simulate 5000 users. how do i achieve this using locust? can someone throw some light?
2018/05/08
[ "https://Stackoverflow.com/questions/50241866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6447078/" ]
Apparently, there is already someone who has done it. The library is on GitHub: <https://github.com/mhr3/gcp-container-builder-node> and available via npm: <https://www.npmjs.com/package/gcp-container-builder> The usage was not clear to me at first, but this is how I am using it now: ``` var build = Object.create(null); build.steps = [{ name: 'gcr.io/cloud-builders/gsutil', args: ['cp', 'gs://some_bucket/some_file.json', '/workspace/some_file.json'] }] // more build steps, converting the file, uploading it, etc. builder.createBuild(build, function(err, resp) { console.log(err); console.log(resp); }); ```
The procedure you propose require three different steps: Google Cloud Storage → Cloud Functions → API call. According to the requirements you exposed, could be better to use [Container Builder’s Build Triggers](https://cloud.google.com/container-builder/docs/running-builds/automate-builds). You upload the files to Google Cloud Source Repository and create a trigger. Everytime you upload a change to the repository, Container Builder will build the image automatically. This way you avoid using cloud functions, the API call and Node.js. This will reduce the procedure to only one step, which reduces the complexity and increases the reliability.
50,853,528
I'm using Guzzle for HTTP Requests/Responses in my PHP project. I'm sending the following request : ``` GET https://graph.microsoft.com/v1.0/me/events('[some_id]') ``` which, in Postman, returns something that looks like this : ``` { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('...')/events/$entity", "@odata.etag": "W/\"...==\"", "id": "...", "createdDateTime": "2018-06-14T08:03:44.5688916Z", "lastModifiedDateTime": "2018-06-14T08:03:44.7407671Z", "changeKey": "...==", "categories": [], "originalStartTimeZone": "UTC", "originalEndTimeZone": "UTC", "iCalUId": "...", "reminderMinutesBeforeStart": 15, "isReminderOn": true, "hasAttachments": false, "subject": "Created ?", "bodyPreview": "", "importance": "normal", "sensitivity": "normal", "isAllDay": false, "isCancelled": false, "isOrganizer": true, "responseRequested": true, "seriesMasterId": null, "showAs": "busy", "type": "singleInstance", "webLink": "https://outlook.office365.com/owa/?itemid=...%3D&exvsurl=1&path=/calendar/item", "onlineMeetingUrl": null, "recurrence": null, "responseStatus": { "response": "organizer", "time": "0001-01-01T00:00:00Z" }, "body": { "contentType": "html", "content": "" }, "start": { "dateTime": "2018-06-15T10:00:00.0000000", "timeZone": "UTC" }, "end": { "dateTime": "2018-06-15T13:30:00.0000000", "timeZone": "UTC" }, "location": { "displayName": "", "locationType": "default", "uniqueIdType": "unknown", "address": {}, "coordinates": {} }, "locations": [], "attendees": [], "organizer": { "emailAddress": { "name": "...", "address": "..." } } } ``` So I build my request like this : ``` $client = new Client(); $header = array( "Authorization" => "Bearer ".$token ); $url = "https://graph.microsoft.com/v1.0/me/events('" .$idEvent. "')"; $request = new Request("GET", $url, $header, ""); try { $eventInfos = $client->send($request); } catch (GuzzleException $e) { var_dump($e->getMessage()); } ``` But when I var\_dump($eventInfos), I get a GuzzleHttp\Psr7\Request object. What is the correct way to get the JSON I was expecting please ?
2018/06/14
[ "https://Stackoverflow.com/questions/50853528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7600807/" ]
You have to extract the body of from the response. Try this, ``` $client = new Client(); $header = array( "Authorization" => "Bearer ".$token ); $url = "https://graph.microsoft.com/v1.0/me/events('" .$idEvent. "')"; $request = new Request("GET", $url, $header, ""); try { $eventInfos = $client->send($request); $response = (string)$eventInfos->getBody(); } catch (GuzzleException $e) { var_dump($e->getMessage()); } ```
Also, you can use `getContents()` to get the response. ``` $request->getBody()->getContents() ```
29,030,762
I am looking to do a comparison of a string to and enumeration. I have written a sample code of what I am attempting. Since a String and and Enumerated type are different, how do I go about doing this properly in Ada? ``` WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE ColorTest IS TYPE StopLightColor IS (red, yellow, green); response : String (1 .. 10); N : Integer; BEGIN Put("What color do you see on the stoplight? "); Get_Line (response, N); IF response IN StopLightColor THEN Put_Line ("The stoplight is " & response(1..n)); END IF; END ColorTest; ```
2015/03/13
[ "https://Stackoverflow.com/questions/29030762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297683/" ]
First instantiate [`Enumeration_IO`](http://www.ada-auth.org/standards/12rm/html/RM-A-10-10.html) for `StopLightColor`: ``` package Color_IO is new Ada.Text_IO.Enumeration_IO(StopLightColor); ``` Then you can do either of the following: * Use `Color_IO.Get` to read the value, catching any `Data_Error` that arises, as shown [here](https://stackoverflow.com/a/43152826/230513) for a similar instance of `Enumeration_IO`. * Use `Color_IO.Put` to obtain a `String` for comparison to `response`. As an aside, `Stoplight_Color` might be a more consistent style for the enumerated type's identifier.
Another possibility: ``` Get_Line (response, N); declare Color : StopLightColor; begin Color := StopLightColor'Value(response(1..N)); -- if you get here, the string is a valid color Put_Line ("The stoplight is " & response(1..N)); exception when Constraint_Error => -- if you get here, the string is not a valid color (also could -- be raised if N is out of range, which it won't be here) null; end; ```
29,030,762
I am looking to do a comparison of a string to and enumeration. I have written a sample code of what I am attempting. Since a String and and Enumerated type are different, how do I go about doing this properly in Ada? ``` WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE ColorTest IS TYPE StopLightColor IS (red, yellow, green); response : String (1 .. 10); N : Integer; BEGIN Put("What color do you see on the stoplight? "); Get_Line (response, N); IF response IN StopLightColor THEN Put_Line ("The stoplight is " & response(1..n)); END IF; END ColorTest; ```
2015/03/13
[ "https://Stackoverflow.com/questions/29030762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2297683/" ]
First instantiate [`Enumeration_IO`](http://www.ada-auth.org/standards/12rm/html/RM-A-10-10.html) for `StopLightColor`: ``` package Color_IO is new Ada.Text_IO.Enumeration_IO(StopLightColor); ``` Then you can do either of the following: * Use `Color_IO.Get` to read the value, catching any `Data_Error` that arises, as shown [here](https://stackoverflow.com/a/43152826/230513) for a similar instance of `Enumeration_IO`. * Use `Color_IO.Put` to obtain a `String` for comparison to `response`. As an aside, `Stoplight_Color` might be a more consistent style for the enumerated type's identifier.
Answering your actual question: Ada doesn't allow you to compare values of different types directly, but luckily there is a way to convert an enumerated type to a string, which always works. For any enumerated type `T` there exists a function: ``` function T'Image (Item : in T) return String; ``` which returns a string representation of the enumerated object passed to it. Using that, you can declare a function, which compares a string and an enumerated type: ``` function "=" (Left : in String; Right : in Enumerated_Type) return Boolean is begin return Left = Enumerated_Type'Image (Right); end "="; ``` If you want to do a case-insensitive comparison, you could map both strings to lower case before comparing them: ``` function "=" (Left : in String; Right : in Enumerated_Type) return Boolean is use Ada.Characters.Handling; begin return To_Lower (Left) = To_Lower (Enumerated_Type'Image (Right)); end "="; ```
56,323,044
I got the filter in Vue. Template: ``` <b-button v-if="filterFilled()" @click="clearFilter"> Clear </b-button> ``` Data: ``` data () { return { filter: { price_from: '', price_to: '', surface_from: '', surface_to: '', floor: '', type: '', structure: '', }, } }, ``` And my method where I check is filter dirty: ``` filterFilled(){ return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from || this.filter.floor || this.filter.type || this.filter.structure) }, ``` This works fine, but my question is, **does it exists better way to ask if object has filled props?**
2019/05/27
[ "https://Stackoverflow.com/questions/56323044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10867656/" ]
I've tracked the problem down to something in swatch-renderer.js. The V2.3 version has the following line at 517: ``` value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : ''; ``` The version V2.3.1 has changed this to the following: ``` value = optionConfig[id].hasOwnProperty('value') ? $('<i></i>').text(optionConfig[id].value).html() : ''; ``` and the value is then used in the following statement to put the text into the html: ``` html += '<div class="' + optionClass + ' text" ' + attr + '>' + (value ? value : label) + '</div>'; ``` I used alert() to see the content of value before and after each variant of this statement as well as its type. Before it's undefined, after it's null for both variants yet changing this back to the old version resolves the problem! That's probably because before in V2.3 it's of type object whereas in V2.3.1 it's of type string (and presumably has the value "null"!). I'll be honest, my knowledge of javascript is fairly limited. Does this look like an error? If so, what would be the best way to fix it (I presume test for the sting "null")?
1. Stores > Attributes > Product > Edit and save the text swatch values 2. php bin/magento indexer:reindex
56,323,044
I got the filter in Vue. Template: ``` <b-button v-if="filterFilled()" @click="clearFilter"> Clear </b-button> ``` Data: ``` data () { return { filter: { price_from: '', price_to: '', surface_from: '', surface_to: '', floor: '', type: '', structure: '', }, } }, ``` And my method where I check is filter dirty: ``` filterFilled(){ return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from || this.filter.floor || this.filter.type || this.filter.structure) }, ``` This works fine, but my question is, **does it exists better way to ask if object has filled props?**
2019/05/27
[ "https://Stackoverflow.com/questions/56323044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10867656/" ]
I've tracked the problem down to something in swatch-renderer.js. The V2.3 version has the following line at 517: ``` value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : ''; ``` The version V2.3.1 has changed this to the following: ``` value = optionConfig[id].hasOwnProperty('value') ? $('<i></i>').text(optionConfig[id].value).html() : ''; ``` and the value is then used in the following statement to put the text into the html: ``` html += '<div class="' + optionClass + ' text" ' + attr + '>' + (value ? value : label) + '</div>'; ``` I used alert() to see the content of value before and after each variant of this statement as well as its type. Before it's undefined, after it's null for both variants yet changing this back to the old version resolves the problem! That's probably because before in V2.3 it's of type object whereas in V2.3.1 it's of type string (and presumably has the value "null"!). I'll be honest, my knowledge of javascript is fairly limited. Does this look like an error? If so, what would be the best way to fix it (I presume test for the sting "null")?
Please update Product Attribute "Admin" Columns From Backend. Then perform Reindexing. [![Product Attribute - Edit ](https://i.stack.imgur.com/qPrGk.png)](https://i.stack.imgur.com/qPrGk.png)
56,323,044
I got the filter in Vue. Template: ``` <b-button v-if="filterFilled()" @click="clearFilter"> Clear </b-button> ``` Data: ``` data () { return { filter: { price_from: '', price_to: '', surface_from: '', surface_to: '', floor: '', type: '', structure: '', }, } }, ``` And my method where I check is filter dirty: ``` filterFilled(){ return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from || this.filter.floor || this.filter.type || this.filter.structure) }, ``` This works fine, but my question is, **does it exists better way to ask if object has filled props?**
2019/05/27
[ "https://Stackoverflow.com/questions/56323044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10867656/" ]
Please update Product Attribute "Admin" Columns From Backend. Then perform Reindexing. [![Product Attribute - Edit ](https://i.stack.imgur.com/qPrGk.png)](https://i.stack.imgur.com/qPrGk.png)
1. Stores > Attributes > Product > Edit and save the text swatch values 2. php bin/magento indexer:reindex
17,866,723
Suppose I have a file (newlines marked as ^n): ``` aaaa^n bbbb^n cccc^n ``` Is there a simple command to backfill whitespace to the rightmost portion of the block (probably using a visual selection); I often see questions about removing leading whitespace, but in this case I want leading whitespace normed to the longest non-whitespace character in the block, like below: ``` aaaa ^n bbbb^n cccc ^n ```
2013/07/25
[ "https://Stackoverflow.com/questions/17866723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/992834/" ]
Probaly the easiest way would be to do ``` set virtualedit=all ``` Go to the top left of the block you want to select. Use a Blockwise visual selection (`<C-V>`) and select the the lines you want. Then hit `$` to extend the visual block to the end of the line. Then yank the selection with `y` Then type `gvp` to past what you yanked lines back onto it self. (`gv` reselects the last visual block). When you are done this will extend all lines to be the length of the longest line + 1. The reason this works. When you are using a virtual edit the visual selection is extends each line to the length the longest when putting it into the register. This will add an extra space to the end which is easily fixable with with `:%s/ $//`
You can do it in a single `:substitute`, although it does get a little involved: ``` :'<,'>s/$/\=repeat(' ', max(map(getline(line("'<"),line("'>")),'strdisplaywidth(v:val)'))-strdisplaywidth(getline('.')))/ ``` This command applies to the Visual selection. If you need more control over the range, consider wrapping the substitute in a function that accepts a [`range`](http://vimdoc.sourceforge.net/htmldoc/eval.html#function-range-example). How does it work? * `\=` in the replacement string lets you evaluate an expression: see [`:h sub-replace-expression`](http://vimdoc.sourceforge.net/htmldoc/change.html#sub-replace-expression). * The replacement is a number of padding space characters: `repeat(' ', ...)`. * The exact number of space characters is determined as the difference between + the maximum line length in the selection, `max(map(getline(start,end), 'strdisplaywidth(v:val)'))`, and + the width of the current line, `strdisplaywidth(getline('.'))`. Note that [`strdisplaywidth()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#strdisplaywidth%28%29) is not available in older Vims, but it is necessary to handle both tabs and spaces in the line correctly. (Use `strlen()` as a cheap substitute.)
57,260,045
So I have 2 dataframes, from different sizes, `df1 = (578, 81)` and `df2 = (1500, 59)`, all lines on `df1 exists in df2`, and all columns in `df2 exists in df1`, my problem is, I have a value that i want to update in df1 based on `6 conditions`, so to update the `column X`, the values at columns `X1, X2, Y1, Y2, Z1 and Z2` must be equal on both DataFrames. On java I would do somenthing like: ``` for(i=0;i<df1.length;i++){ for(k=0;k<df2.length;k++){ if(df1[i][1]==df2[k][1] && df1[i][2]==df2[k][2] ...){ df1[i][0] = df2[k][0]; } } ```
2019/07/29
[ "https://Stackoverflow.com/questions/57260045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2366113/" ]
You can easily use `numpy.where`. And i think it should work best in this case too. Let's say you have the following DataFrames ``` import pandas as pd df1=pd.DataFrame({'X':[1,3,4,6,5], 'X1':[2,3,4,6,3], 'Y1':[4,2,1,51,3], 'Z1':[2,3,4,1,5]}) df2=pd.DataFrame({'L':[2,3,4,1,4], 'X2':[2,3,4,6,5], 'Y2':[4,3,4,6,3], 'Z2':[2,2,1,51,3]}) ``` And you want to change the value of X based on the conditions if `X1==X2 & Y1==Y2 & Z1==Z2` . Also lets say the value you want to update is from column L in this case. You can use `numpy.where` like this ``` df1['X']=np.where((df1['X1']==df2['X2'])&(df1['Y1']==df2['Y2'])&(df1['Z1']==df2['Z2']),df2['L'],,df1['X']) ``` It would only change the first row as the conditions only gets satisfied there. This function is changing the values to `df2['L']` if it meets the condition and keeping the original values if the conditions are not met. Read more about [np.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) **Update: The dataframes in the question are not equal. It doesn't matter if they don't have equal columns but the rows should be equal for the sake of comparison. Below is the example in which the two data frames are not equal and how `numpy.where` is performed in that case.** ``` import pandas as pd import numpy as np df1=pd.DataFrame({'X':[1,3,4,6,5], 'X1':[2,3,4,6,3], 'Y1':[4,3,1,51,3], 'Z1':[2,3,4,1,5]}) df2=pd.DataFrame({'L':[2,3,4,1,4,5,1], 'X2':[2,3,4,6,5,2,3], 'Y2':[4,3,4,6,3,8,7], 'Z2':[2,3,1,51,3,9,9], 'R2':[2,5,1,2,7,3,9]}) #make both the dataframes equal for i in range(len(df2)-len(df1)): df1=df1.append(pd.Series(),ignore_index=True) df1['X']=np.where((df1['X1']==df2['X2'])&(df1['Y1']==df2['Y2'])&(df1['Z1']==df2['Z2']),df2['L'],df1['X']) #drop those null values which have been appended above to get back to original df1=df1.dropna(how='all') ```
Do the 6 columns make a row unique? If so, I would use merge: ``` columns_join= ['col1', 'col2', 'col3', 'col4', 'col5', 'col6'] columns_update= ['upd1', 'upd2', 'upd3'] df_merged= df_to_update[columns_join].merge(df_source[columns_join + columns_update], on=columns_join, how='left', suffixes=['', '_src'], indicator='_join_ind') for col in columns_update: df_to_update.loc[df_merged['_join_ind']=='both', col]= df_merged[col + '_src'] # now df_to_update contains the result ``` If the 6 fields do not identify a row (could result in more rows), you would need to make the merged result unique afterwards, but in that case, your Java version would also just always result in the values of the last row. In that case you can use `DataFrame.grouby` and e.g. `last` as the aggregation function. EDIT: in case you need to apply an aggregation, it's probably best to apply the aggregation to the dataframe you take the values. To aggregate it accordingly using the last value of each group and merge it afterwards, just replace the line with the `.merge` above by: ``` df_agg= df_source.groupby(columns_join)[columns_update].aggregate('last') df_merged= df_to_update[columns_join].merge(df_source[columns_join + columns_update], left_on=columns_join, right_index=True, how='left', suffixes=['', '_src'], indicator='_join_ind') ```
7,733,581
What is the fastest way to lookup the index of a value in sorted vector in MATLAB? That is, is there a fast `find(vector == myNumber, 1, 'first')` for when vector is sorted? I have a large matrix (200,000 x 4) of locations each with a unique integer ID recorded in the first column. I want to find the right the location of a known ID but thousands of searches can take me a little bit to find.
2011/10/11
[ "https://Stackoverflow.com/questions/7733581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4670/" ]
If you use ismembc2, the loc output should give you what you need. See this for more details: <http://www.mathworks.com/support/solutions/en/data/1-9NIE1N/index.html?product=ML&solution=1-9NIE1N>
I do not know if it is faster but you may want to try ``` result=vector(vector(:,1)==myNumber,:) ``` `result` will contain the 4 elements row for which vector `first column == myNumber`
7,733,581
What is the fastest way to lookup the index of a value in sorted vector in MATLAB? That is, is there a fast `find(vector == myNumber, 1, 'first')` for when vector is sorted? I have a large matrix (200,000 x 4) of locations each with a unique integer ID recorded in the first column. I want to find the right the location of a known ID but thousands of searches can take me a little bit to find.
2011/10/11
[ "https://Stackoverflow.com/questions/7733581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4670/" ]
If you use ismembc2, the loc output should give you what you need. See this for more details: <http://www.mathworks.com/support/solutions/en/data/1-9NIE1N/index.html?product=ML&solution=1-9NIE1N>
There are a number of submissions for this on FEX: <http://www.mathworks.com/matlabcentral/fileexchange/?term=binary+search+vector>
7,733,581
What is the fastest way to lookup the index of a value in sorted vector in MATLAB? That is, is there a fast `find(vector == myNumber, 1, 'first')` for when vector is sorted? I have a large matrix (200,000 x 4) of locations each with a unique integer ID recorded in the first column. I want to find the right the location of a known ID but thousands of searches can take me a little bit to find.
2011/10/11
[ "https://Stackoverflow.com/questions/7733581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4670/" ]
There are a number of submissions for this on FEX: <http://www.mathworks.com/matlabcentral/fileexchange/?term=binary+search+vector>
I do not know if it is faster but you may want to try ``` result=vector(vector(:,1)==myNumber,:) ``` `result` will contain the 4 elements row for which vector `first column == myNumber`
23,875,849
I need to create a reorderable ListView in a Windows Phone 8.1 app created using WinRT. The XAML is the following (it binds to an ObservableDictionary in the codebehind): ``` <Grid Margin="24"> <ListView x:Name="MainListView" CanDragItems="True" CanReorderItems="True" AllowDrop="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" > <ListView.ItemTemplate> <DataTemplate> <Border Padding="24" Margin="16" Background="CadetBlue"> <TextBlock Text="{Binding}" /> </Border> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> ``` The ListView does nothing when I try to reorder the items (it looks like the "reordering mode" is not activated). When I run this sample in Windows 8.1 (the XAML is shared) it works as expected. According to the [documentation](http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.listviewbase.canreorderitems.aspx) Windows Phone 8.1 should be supported. Is this functionality supported on the phone (and the documentation wrong) or do I need to do something special for the phone?
2014/05/26
[ "https://Stackoverflow.com/questions/23875849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404764/" ]
For WP you need to set [ListViewBase.ReorderMode](http://msdn.microsoft.com/elibrary/windows/apps/windows.ui.xaml.controls.listviewbase.reordermode.aspx) This is what works for me - no idea which properties are really necessary; ReorderMode is set in code behind: ``` <ListView x:Name="fooListView" ItemsSource="{Binding barlist, Mode=OneWay}" SelectionMode="None" AllowDrop="True" CanDragItems="True" IsSwipeEnabled="True" /> ``` The ListViewBase.Reorder property is available *only* for Windows Phone, so if you have the XAML in a Shared part of a universal app, you need to set it using conditional compile like so: ``` #if WINDOWS_PHONE_APP MainListView.ReorderMode = ListViewReorderMode.Enabled; #endif ```
It appears that the property `CanReorderItems` is not supported on Windows Phone 8.1. (I tried a simple example, and it does not work, and I could not find any combination that made it work as it does on Windows 8.1.)
112,819
I'm somewhat new to meta, but I figured I would report this. When I voted down, it went down by 2 (from 3 to 1). Then it reverted itself back because it didn't allow the downvote because of a cap or something.
2011/11/18
[ "https://meta.stackexchange.com/questions/112819", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/171024/" ]
Had you previously voted the same post up? It's not uncommon for people to: 1. vote up 2. later realize the answer is wrong 3. try to cancel the upvote by pressing the downvote button 4. see the vote count flicker while the vote is being processed 5. find that the vote is "locked in" because the original vote was cast a long time ago The reason for what you're seeing is that going from upvote to downvote is a change of `score + 1` to `score - 1`, a net change of two. (The correct way to undo an upvote is to click the upvote button again, but that wouldn't help if it's been so long that the vote is locked.)
When you vote, an updated score is returned by the ajax post. It's possible someone voted in between the time you loaded the page and the time you voted, and I think JavaScript will revert the number back to what it was rather than using the updated score. Not positive on that last part though.
66,242
In [Bereshit 13:1](http://www.chabad.org/library/bible_cdo/aid/8208#showrashi=true), Negev is meant to mean the *south of the Land of Israel* (according to Rashi), because Abraham was going from Egypt to Israel and otherwise wouldn't make sense. > > וַיַּעַל אַבְרָם מִמִּצְרַיִם הוּא וְאִשְׁתּוֹ וְכָל אֲשֶׁר לוֹ וְלוֹט עִמּוֹ **הַנֶּגְבָּה** > > And Abram came up from Egypt, he and his wife and all that was his, and Lot with him, *to the south*. > > > . . . But in Bereshit 13:3, Negev means just *south* (also according to Rashi), because Abraham was going from the south of Israel to the North. > > וַיֵּלֶךְ לְמַסָּעָיו **מִנֶּגֶב** וְעַד בֵּית אֵל עַד הַמָּקוֹם אֲשֶׁר הָיָה שָׁם אָהֳלֹה בַּתְּחִלָּה בֵּין בֵּית אֵל וּבֵין הָעָי > > And he went on his journeys, *from the south* and until Beth el, until the place where his tent had been previously, between Beth el and between Ai. > > > How can *Negev* change meanings like this?
2015/12/13
[ "https://judaism.stackexchange.com/questions/66242", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/11052/" ]
It does not change meanings. A word is used in context. In English for example, we speak of "the South" to mean the southern portion of the eastern United States even though someone may be in Mexico when using the term. Similarly here we speak of the "South" relative to Yerushalayim when speaking about different parts of the country of Yisrael. Thus, the answer to your question is "yes".
Negev actually means "the dry area" (NGV root means "dry")which is in the southern part of Eretz Yisrael. "Negbah" means "to the dry area," not a cardinal direction. "Minegev" in the later verse means "from the dry area." (In any event, it is not switching meanings. In the first instance the "heh" at the end of the noun means "to" that area. The mem in front of the noun means from that area. So it is not a contradiction. But you also asked if it was a cardinal direction. It is not.) Similarly, "yamah" doesn't mean "to the west", rather it means "to the sea." Both of these would be used in relation to Eretz Yisrael but not other lands. A more cardinal-like direction would be "maaravah" meaning "towards where the sun sets." Of course that's west. "Kedmah" means "to the east" because it is in the direction of where Avraham was "mi'kedem,"(beforehand) In other contexts, "to the east" would be said "mizrachah shemesh" (towards where the sun rises) which is more like a cardinal direction. Finally, I believe I saw it in Rav Hirsch's commentary, but "tzafonah" would mean"towards where things are hidden" since, in Eretz Yisrael, being above the equator, the sun always remains on the southern part of the sky. So the northern wall of a building (for instance) never gets direct sunlight, it is always tzafun/(hidden) in shadows. I don't recall why "daromah" means "to the south," but I imagine it also has to do with the sun and would be more like a cardinal direction.
32,984,482
I have 3 SQL tables as below: Table 1 ``` ItemId Name ---------- A aa B bb ``` Table 2 ``` ItemId Category ---------- A 1 A 2 A 3 B 1 ``` Table 3 ``` ItemId Dep ---------- A D1 B D2 B D3 ``` I need result as this ``` ItemId Name Category Dep ------------------------ A aa 1 D1 2 3 B bb 1 D2 D3 ``` Is there any way to get this result without looping tables?
2015/10/07
[ "https://Stackoverflow.com/questions/32984482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745066/" ]
You can first `JOIN` the tables on `ItemId` and then use `ROW_NUMBER` and `RANK` for formatting. *I suggest you do the display format in the client side* [**SQL Fiddle**](http://sqlfiddle.com/#!6/a1105/2/0) ``` WITH CTE AS( SELECT t1.ItemId, t1.Name, t2.Category, t3.Dep, Rn_Cat = ROW_NUMBER() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t2.Category), Rn_Dep = ROW_NUMBER() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t3.Dep), Rnk_Cat = RANK() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t2.Category), Rnk_Dep = RANK() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t3.Dep) FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.ItemId = t1.ItemId LEFT JOIN Table3 t3 ON t3.ItemId = t1.ItemId ) SELECT ItemId = CASE WHEN Rn_Cat = 1 THEN ItemId ELSE '' END, Name = CASE WHEN Rn_Cat = 1 THEN Name ELSE '' END, Category = CASE WHEN Rn_Cat = Rnk_Cat THEN CONVERT(VARCHAR(10), Category) ELSE '' END, Dep = CASE WHEN Rn_Dep = Rnk_Dep THEN CONVERT(VARCHAR(10), Dep) ELSE '' END FROM CTE ```
May be Using `UNION` [Fiddle Here](http://sqlfiddle.com/#!6/a1105/11) ``` WITH CTE AS( SELECT t2.ItemId,t1.Name,t2.Category,t3.Dep, Rank() over(Partition by t1.ItemId,t1.Name order by t2.Category,t3.Dep) as rn from Table1 t1 join Table2 t2 on t1.ItemId=t2.ItemId join Table3 t3 on t1.ItemId=t3.ItemId ) SELECT ItemId,Name,Category,Dep,Rn FROM CTE where rn=1 union SELECT '','',Category,Dep,Rn FROM CTE where rn>1 ```
32,984,482
I have 3 SQL tables as below: Table 1 ``` ItemId Name ---------- A aa B bb ``` Table 2 ``` ItemId Category ---------- A 1 A 2 A 3 B 1 ``` Table 3 ``` ItemId Dep ---------- A D1 B D2 B D3 ``` I need result as this ``` ItemId Name Category Dep ------------------------ A aa 1 D1 2 3 B bb 1 D2 D3 ``` Is there any way to get this result without looping tables?
2015/10/07
[ "https://Stackoverflow.com/questions/32984482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745066/" ]
You can first `JOIN` the tables on `ItemId` and then use `ROW_NUMBER` and `RANK` for formatting. *I suggest you do the display format in the client side* [**SQL Fiddle**](http://sqlfiddle.com/#!6/a1105/2/0) ``` WITH CTE AS( SELECT t1.ItemId, t1.Name, t2.Category, t3.Dep, Rn_Cat = ROW_NUMBER() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t2.Category), Rn_Dep = ROW_NUMBER() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t3.Dep), Rnk_Cat = RANK() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t2.Category), Rnk_Dep = RANK() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t3.Dep) FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.ItemId = t1.ItemId LEFT JOIN Table3 t3 ON t3.ItemId = t1.ItemId ) SELECT ItemId = CASE WHEN Rn_Cat = 1 THEN ItemId ELSE '' END, Name = CASE WHEN Rn_Cat = 1 THEN Name ELSE '' END, Category = CASE WHEN Rn_Cat = Rnk_Cat THEN CONVERT(VARCHAR(10), Category) ELSE '' END, Dep = CASE WHEN Rn_Dep = Rnk_Dep THEN CONVERT(VARCHAR(10), Dep) ELSE '' END FROM CTE ```
this will probably work: ``` ;with cte_t1 as ( select 'A' as ItemId, 'aa' as Name union select 'B' as ItemId, 'bb' as Name ), cte_t2 as ( select 'A' AS ItemId, 1 as Category union select 'A' AS ItemId, 2 as Category union select 'A' AS ItemId, 3 as Category union select 'B' AS ItemId, 1 as Category ), cte_t3 as ( select 'A' AS ItemId, 'D1' as Dep union select 'B' AS ItemId, 'D2' as Dep union select 'B' AS ItemId, 'D3' as Dep ), cte_t4 as ( SELECT T1.ItemId, t1.Name, T2.Category, T3.Dep, ROW_NUMBER() over(order by T1.ItemId, T2.Category) RowNumber FROM cte_t1 t1 inner join cte_t2 t2 on t1.ItemId = t2.ItemId inner join cte_t3 t3 on t1.ItemId = t3.ItemId and t2.ItemId = t3.ItemId ) select case when a.ItemId = b.ItemId then '' else a.ItemId end as ItemId, case when a.Name = b.Name then '' else a.Name end as Name, case when a.Category = b.Category then '' else cast(a.Category as varchar(100)) end as Category, case when a.Dep = b.Dep then '' else a.Dep end as Dep from cte_t4 a left join cte_t4 b on a.RowNumber-1= b.RowNumber ```
32,984,482
I have 3 SQL tables as below: Table 1 ``` ItemId Name ---------- A aa B bb ``` Table 2 ``` ItemId Category ---------- A 1 A 2 A 3 B 1 ``` Table 3 ``` ItemId Dep ---------- A D1 B D2 B D3 ``` I need result as this ``` ItemId Name Category Dep ------------------------ A aa 1 D1 2 3 B bb 1 D2 D3 ``` Is there any way to get this result without looping tables?
2015/10/07
[ "https://Stackoverflow.com/questions/32984482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745066/" ]
You can first `JOIN` the tables on `ItemId` and then use `ROW_NUMBER` and `RANK` for formatting. *I suggest you do the display format in the client side* [**SQL Fiddle**](http://sqlfiddle.com/#!6/a1105/2/0) ``` WITH CTE AS( SELECT t1.ItemId, t1.Name, t2.Category, t3.Dep, Rn_Cat = ROW_NUMBER() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t2.Category), Rn_Dep = ROW_NUMBER() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t3.Dep), Rnk_Cat = RANK() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t2.Category), Rnk_Dep = RANK() OVER(PARTITION BY t1.ItemId, t1.Name ORDER BY t3.Dep) FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.ItemId = t1.ItemId LEFT JOIN Table3 t3 ON t3.ItemId = t1.ItemId ) SELECT ItemId = CASE WHEN Rn_Cat = 1 THEN ItemId ELSE '' END, Name = CASE WHEN Rn_Cat = 1 THEN Name ELSE '' END, Category = CASE WHEN Rn_Cat = Rnk_Cat THEN CONVERT(VARCHAR(10), Category) ELSE '' END, Dep = CASE WHEN Rn_Dep = Rnk_Dep THEN CONVERT(VARCHAR(10), Dep) ELSE '' END FROM CTE ```
Using this code - ``` SELECT table1.ItemID, table1.Name, table2.Category, table3.Dep FROM table1, table2, table3 WHERE table1.ItemID = table2.ItemID AND table1.ItemID = table3.ItemID; ``` produces this output - ``` +--------+------+----------+-----+ | ItemID | Name | Category | Dep | +--------+------+----------+-----+ | A | aa | 1 | D1 | | A | aa | 2 | D1 | | A | aa | 3 | D1 | | B | bb | 1 | D2 | | B | bb | 1 | D3 | +--------+------+----------+-----+ ``` Is this what you are after, or do you wish to display a blank space for every repeat of a value?
7,574,303
I have problems localizing a django-nonrel project, which is deployed to GAE. Because of GAE I have to put everything into my project folder, so it looks like something like this ``` project + django + dbindexer + registration + myapp ... + locale + templates ``` I have strings to localize in `templates` directory, and in the `myapp` directory. When I run `python manage.py makemessages -l en --ignore django\*` from the project dir it crawl through **all** the directories of the project, including django, so I get a quite big po file. My strings from the templates are there, along with all of the strings from django directory. after --ignore ( or just -i ) I tried to pu `django` `django/*` , but nothing changed. Any ideas?
2011/09/27
[ "https://Stackoverflow.com/questions/7574303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686223/" ]
**./manage.py help makemessages** ``` -i PATTERN, --ignore=PATTERN Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more. ``` I have just tested it, and this command successfully ignored my application: ./manage.py makemessages -l da -i "django\*" But beware that before you test it, you should delete the old .po file, as I think it will not automatically remove the translation lines from your previous makemessages execution.
The problem is with the pattern - maybe the shell was expanding it for you. In general - it is good to avoid path separators (whether / or \) in the pattern. If you need to always pass specific options to the `makemessages` command, you could consider your own wrapper, like this one, which I use myself: ``` from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command class Command(BaseCommand): help = "Scan i18n messages without going into externals." def handle(self, *args, **options): call_command('makemessages', all=True, extensions=['html', 'inc'], ignore_patterns=['externals*']) ``` This saves you typing, and gives a common entry point for scanning messages across the project (your translator colleague will not destroy translations by missing out some parameter). Don't delete the old `.po` file, once you have cleared it from the totally unwanted (i.e. - those from 'django' directory) messages. This allows gettext to recycle old unused messages, once they are used again (or simmilar ones, which will be marked as `#, fuzzy`. **Edit** - as mt4x noted - the wrapper above doesn't allow for passing the options to the wrapped command. This is easy to fix: ``` from django.core.management import call_command from django.core.management.commands.makemessages import ( Command as MakeMessagesCommand ) class Command(MakeMessagesCommand): help = "Scan i18n messages without going into externals." def handle(self, *args, **options): options['all'] = True options['extensions'] = ['html', 'inc'] if 'ignore_patterns' not in options: options['ignore_patterns'] = [] options['ignore_patterns'] += ['externals*'] call_command('makemessages', **options) ``` Thus - you can fix what needs to be fixed, and flex the rest. And this needs not be blind override like above, but also some conditional edit of the parameters passed to the command - appending something to a list or only adding it when it's missing.
48,645,435
I'm working on my first app with a facebook login, and am unable to get a segue to trigger once I'm logged in. The facebook login triggers just fine and logs me in, then I'm dumped back to the login VC. Here's where I'm triggering the segue: ``` func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) { switch result { case .failed(let error): print(error) break case .success(_,_,_): print("login succeeded!") self.performSegue(withIdentifier: "SearchVC", sender: self.user) case .cancelled: print("Canceled!") } } ``` Here are my other FB Login methods: ``` func facebookButtonClicked(sender: UIButton) { let loginManager = LoginManager() loginManager.logIn(readPermissions: [.publicProfile], viewController: self) { loginResult in switch loginResult { case .failed(let error): print(error) case .cancelled: print("User cancelled login") case .success(let grantedPermissions, let declinedPermissions, let accessToken): print("Logged in") self.getFBUserData() } } } func getFBUserData() { if FBSDKAccessToken.current() != nil { FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"]).start(completionHandler: { (connection, result, error) -> Void in if error == nil { self.userData = result as! [String : AnyObject] print(result!) print(self.userData) } }) } } ``` My Segue: ``` override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SearchVC", let searchVC = segue.destination as? SearchVC { searchVC.user = sender as? User ?? User() } } ``` In my App Delegate: ``` func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func applicationWillResignActive(_ application: UIApplication) { FBSDKAppEvents.activateApp() } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool { return SDKApplicationDelegate.shared.application(app, open: url, options: options) } func applicationDidBecomeActive(application: UIApplication) { // Call the 'activate' method to log an app event for use // in FB analytics and advertising reporting. AppEventsLogger.activate(application) // ... } ``` The segue is wired in IB with an identifier of "SearchVC" Edit: I initially tried performing the segue in the completion block of FBSDKGraphRequest, but it doesn’t trigger there either I’m not asking how to perform a segue as the suggested duplicate question indicates
2018/02/06
[ "https://Stackoverflow.com/questions/48645435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7771253/" ]
You should call [performSegue](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621413-performsegue) method in `FBSDKGraphRequest` completion. ``` func getFBUserData(){ if((FBSDKAccessToken.current()) != nil){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"]).start(completionHandler: { (connection, result, error) -> Void in if (error == nil){ self.userData = result as! [String : AnyObject] print(result!) print(self.userData) self.performSegue(withIdentifier: "SearchVC", sender: self) } }) } } } ```
The project was bugged. I had another segue that wasn't executing code as well as a few other miscellaneous blocks here and there. Deleting my `LoginVC` file and recreating it solved all issues
26,880,867
I am having a problem with adding homes with HMHomeManager. I can call the function `add` well, but HMHomeManager does not return ``` func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } ``` I am sure I already assigned the delegate of homeManager. Below is my code: ``` class ViewController: UIViewController, HMHomeManagerDelegate { var manager: HMHomeManager required init(coder aDecoder: NSCoder) { manager = HMHomeManager() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. manager.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions @IBAction func home1Pressed(sender: UIButton) { manager.addHomeWithName("Home12", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } @IBAction func home2Pressed(sender: UIButton) { manager.addHomeWithName("Home23", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } // MARK: - HMHomeManagerDelegate func homeManagerDidUpdateHomes(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManagerDidUpdatePrimaryHome(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didRemoveHome home: HMHome!) { println("\(__FUNCTION__)") } } ``` Note that: when I first run this code, `homeManagerDidUpdateHomes` is called which proves to me that homeManager.delegate=self is correct In this code, after I pressed button1 (`home1Pressed` triggered) and button2 (`home1Pressed` triggered), `home12` and `home23` are created. I know this because next time I run this code, the output is: ``` homeManagerDidUpdateHomes homes: [[ name = Home1, primary : Yes ], [ name = Home12, primary : No ], [ name = Home23, primary : No ]] ``` But Why `homeManager(manager: HMHomeManager!, didAddHome home: HMHome!` is not called when I pressed button1 and button2? I cannot figure it out, for 2 days. Thanks,
2014/11/12
[ "https://Stackoverflow.com/questions/26880867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3463682/" ]
Did you remember to enable HomeKit in Capabilities? ![enter image description here](https://i.stack.imgur.com/ZTsCj.png)
I get the same error. As a workaround, I am getting the homeManagerDidUpdatePrimaryHome callback. I filed a bug for this during the beta, which was closed as a duplicate, but I guess it needs to be refiled. homeManagerDidUpdatePrimaryHome is working, but that really only helps with the first home. I re-reported this to Apple.
26,880,867
I am having a problem with adding homes with HMHomeManager. I can call the function `add` well, but HMHomeManager does not return ``` func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } ``` I am sure I already assigned the delegate of homeManager. Below is my code: ``` class ViewController: UIViewController, HMHomeManagerDelegate { var manager: HMHomeManager required init(coder aDecoder: NSCoder) { manager = HMHomeManager() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. manager.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions @IBAction func home1Pressed(sender: UIButton) { manager.addHomeWithName("Home12", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } @IBAction func home2Pressed(sender: UIButton) { manager.addHomeWithName("Home23", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } // MARK: - HMHomeManagerDelegate func homeManagerDidUpdateHomes(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManagerDidUpdatePrimaryHome(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didRemoveHome home: HMHome!) { println("\(__FUNCTION__)") } } ``` Note that: when I first run this code, `homeManagerDidUpdateHomes` is called which proves to me that homeManager.delegate=self is correct In this code, after I pressed button1 (`home1Pressed` triggered) and button2 (`home1Pressed` triggered), `home12` and `home23` are created. I know this because next time I run this code, the output is: ``` homeManagerDidUpdateHomes homes: [[ name = Home1, primary : Yes ], [ name = Home12, primary : No ], [ name = Home23, primary : No ]] ``` But Why `homeManager(manager: HMHomeManager!, didAddHome home: HMHome!` is not called when I pressed button1 and button2? I cannot figure it out, for 2 days. Thanks,
2014/11/12
[ "https://Stackoverflow.com/questions/26880867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3463682/" ]
Quoting from Apple Dev Forum discussions: This is not a bug but yeah, it should be better documented. All HomeKit's delegates will only get invoked when there are changes in HomeKit database that are not caused by the app or doesn't have a direct connection to your completion handler (Like Synced from iCloud, another HomeKit app added a room then user switched to your app)
I get the same error. As a workaround, I am getting the homeManagerDidUpdatePrimaryHome callback. I filed a bug for this during the beta, which was closed as a duplicate, but I guess it needs to be refiled. homeManagerDidUpdatePrimaryHome is working, but that really only helps with the first home. I re-reported this to Apple.
26,880,867
I am having a problem with adding homes with HMHomeManager. I can call the function `add` well, but HMHomeManager does not return ``` func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } ``` I am sure I already assigned the delegate of homeManager. Below is my code: ``` class ViewController: UIViewController, HMHomeManagerDelegate { var manager: HMHomeManager required init(coder aDecoder: NSCoder) { manager = HMHomeManager() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. manager.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions @IBAction func home1Pressed(sender: UIButton) { manager.addHomeWithName("Home12", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } @IBAction func home2Pressed(sender: UIButton) { manager.addHomeWithName("Home23", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } // MARK: - HMHomeManagerDelegate func homeManagerDidUpdateHomes(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManagerDidUpdatePrimaryHome(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didRemoveHome home: HMHome!) { println("\(__FUNCTION__)") } } ``` Note that: when I first run this code, `homeManagerDidUpdateHomes` is called which proves to me that homeManager.delegate=self is correct In this code, after I pressed button1 (`home1Pressed` triggered) and button2 (`home1Pressed` triggered), `home12` and `home23` are created. I know this because next time I run this code, the output is: ``` homeManagerDidUpdateHomes homes: [[ name = Home1, primary : Yes ], [ name = Home12, primary : No ], [ name = Home23, primary : No ]] ``` But Why `homeManager(manager: HMHomeManager!, didAddHome home: HMHome!` is not called when I pressed button1 and button2? I cannot figure it out, for 2 days. Thanks,
2014/11/12
[ "https://Stackoverflow.com/questions/26880867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3463682/" ]
Did you remember to enable HomeKit in Capabilities? ![enter image description here](https://i.stack.imgur.com/ZTsCj.png)
This is an iOS bug (tested with 8.3). 21097472 HomeKit API - HMHomeManagerDelegate didAddHome is not called
26,880,867
I am having a problem with adding homes with HMHomeManager. I can call the function `add` well, but HMHomeManager does not return ``` func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } ``` I am sure I already assigned the delegate of homeManager. Below is my code: ``` class ViewController: UIViewController, HMHomeManagerDelegate { var manager: HMHomeManager required init(coder aDecoder: NSCoder) { manager = HMHomeManager() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. manager.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions @IBAction func home1Pressed(sender: UIButton) { manager.addHomeWithName("Home12", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } @IBAction func home2Pressed(sender: UIButton) { manager.addHomeWithName("Home23", completionHandler: { (home:HMHome!, error:NSError!) -> Void in if error != nil { println("error: \(error)") } else { println("no error") } }) } // MARK: - HMHomeManagerDelegate func homeManagerDidUpdateHomes(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManagerDidUpdatePrimaryHome(manager: HMHomeManager!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didAddHome home: HMHome!) { println("\(__FUNCTION__)") } func homeManager(manager: HMHomeManager!, didRemoveHome home: HMHome!) { println("\(__FUNCTION__)") } } ``` Note that: when I first run this code, `homeManagerDidUpdateHomes` is called which proves to me that homeManager.delegate=self is correct In this code, after I pressed button1 (`home1Pressed` triggered) and button2 (`home1Pressed` triggered), `home12` and `home23` are created. I know this because next time I run this code, the output is: ``` homeManagerDidUpdateHomes homes: [[ name = Home1, primary : Yes ], [ name = Home12, primary : No ], [ name = Home23, primary : No ]] ``` But Why `homeManager(manager: HMHomeManager!, didAddHome home: HMHome!` is not called when I pressed button1 and button2? I cannot figure it out, for 2 days. Thanks,
2014/11/12
[ "https://Stackoverflow.com/questions/26880867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3463682/" ]
Quoting from Apple Dev Forum discussions: This is not a bug but yeah, it should be better documented. All HomeKit's delegates will only get invoked when there are changes in HomeKit database that are not caused by the app or doesn't have a direct connection to your completion handler (Like Synced from iCloud, another HomeKit app added a room then user switched to your app)
This is an iOS bug (tested with 8.3). 21097472 HomeKit API - HMHomeManagerDelegate didAddHome is not called
8,500,229
I'm using VS 2010 + latest VsVim. Looks like Vim `Ctrl`+`R` does not work in VsVim. Is that true? VS handled `Ctrl`+`R`, saying: `(Ctrl+R) was pressed. Waiting for second key of chord...` Is there any way to make this work?
2011/12/14
[ "https://Stackoverflow.com/questions/8500229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/351950/" ]
VsVim allows you to control whether `Ctrl`+`r` is handled by Visual Studio or VsVim itself. At the bottom of a source file (e.g. \*.cs) you should see the VsVim command line and an Options button. Clicking the Options button will give you a menu that lists various keyboard shortcuts and allows you to choose which application should handle them.
Yes. There is an Option button in after the VsVim command line. But even if I choose to VsVim to handle Ctrl+R, VS is still handling Ctrl+R and complains: '(Ctrl+R) was pressed. Waiting for second key of chord...' I just tried to change this setting and let VS handle Ctrl+R, then change it back to VsVim. But still can't redo a previously undoed editting.
64,176,646
I am receiving Pandas DataFrame from an upstream component that has a large number of columns (~20000), all of them have dtypes `float64` and most of the entries are `NaN` (this is *bag of words* encoded document). Example: ``` 1 2.0 NaN 1.0 NaN NaN NaN 1.0 NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 3 NaN NaN 1.0 NaN 4.0 NaN 1.0 NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ``` I need to convert this dataframe to dense `int`s for further processing (`int8` is sufficient in this case). I know that in Pandas, you can convert and fill the missing values like this ``` df.fillna(0).astype(np.int8) ``` The problem is that as soon as the code starts filling the missing values, it very quickly overflows the memory and crashes. At the moment, I am saving the Dataframe on disk and processing it with another script, line-by-line (converting floats to ints and replacing NaNs with 0s), which is then read again by Pandas as `int8` (`pd.read_csv("preprocessed.csv", dtype=np.int8)`). The result (dataframe containing `int8` values) fits into memory. My question - Is there some efficient way of doing this transformation in Pandas (converting `float64` into `int8` while replacing NaNs with 0s) without overflowing memory? (both original and desired dataframes fit into memory, it is just that the above-mentioned Pandas code doesn't)
2020/10/02
[ "https://Stackoverflow.com/questions/64176646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9518890/" ]
You seem to have a limit on the memory. In which case, try not to chain the operation. That is: ``` df = df.fillna(0) df = df.astype('int8') ``` Or use `apply` on the rows if you have less rows than columns: ``` df = df.apply(lambda x: x.fillna(0).astype('int8'), axis=1) ``` However, Since most of the cells in the csv file are the empty string, I think you might be better of doing: ``` df = pd.read_csv('file.csv', dtype='str') ```
Do the conversion in blocks instead of all at once * start with heavy dataframe A * create a new dataframe B * copy range from A to new dataframe C (choose block size to not overrun memory) * convert range in C to desired type (can be combined with former step) * delete old range in A * join C to A * repeat until all ranges are converted
24,903,112
Hi i have been developing simple school project, in that i want send the mail to startmark entry if the enrolments of the student get completed. i have tables allotment ``` *section_id *user_id ``` user ``` *user_id *email ``` enrolment controller ``` def update unless params[:students] && params[:section_id] && !params[:is_academic].nil? send_back GlobalUtils.false_response_hash and return end section = Section.find( params[:section_id] ) Mailers.mark_entry_notification(section).deliver send_back( response_hash, :scope_3 ) end mailers.rb def mark_entry_notification(section) section_id = section.id array_user_id=[] Allotment.each do |allot| array_user_id << allot.user_id.where(allot.section_id = section_id) end array_user_mail=[] User.each do |usr| array_user_mail << usr.user_email.where(usr.user_id = array_user_id) end mail(:to => "array_user_mail" :subject => student enrollment is completed ) end ``` is this correct? is that will send a mail?
2014/07/23
[ "https://Stackoverflow.com/questions/24903112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3733950/" ]
I hope this is what you expect: In enrolment controller, ``` def update unless params[:students] && params[:section_id] && !params[:is_academic].nil? send_back GlobalUtils.false_response_hash and return end Mailers.mark_entry_notification(params[:section_id]).deliver send_back( response_hash, :scope_3 ) end ``` in mailers.rb, ``` def mark_entry_notification(section_id) array_user_ids = array_user_emails = [] array_user_ids = Allotment.where(:section_id=>section_id).pluck(:user_id) array_user_emails = User.where(:id=>array_user_ids).pluck(:user_email) mail(:to => array_user_emails, :subject => "Student enrollment is completed" ) end ``` Hope this helps you. Thanks!!
mail(:to => **array\_user\_mail** :subject => student enrollment is completed) Note down the bolded text. Need not to use quotes for a ruby variable. You can send mails to multiple users in this way. I wonder why you have written this many lines of code just to fetch the email ids of User model. ``` array_user_mail = User.pluck(:user_email) ``` if you are using lower version of rails, try the following ``` array_user_mail = User.map(&:user_email) ``` Also, Are you sure the following code works in your application? ``` array_user_id << allot.user_id.where(allot.section_id = section_id) ``` You are trying to use where condition for table attribute. It is not possible right.? Okay, Anyhow answering your actual question "Use **array\_user\_mail** without quotes in :to" assuming **array\_user\_mail** is a proper array.. He he he... Kidding!!
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
This is a bit tricky, but for all the people interested in reversing an array without creating new predicate functions and/or modifying the array etc... ``` ng-repeat="feed in feeds | orderBy:'':true" ``` or ``` ng-repeat="feed in feeds | orderBy:'-'" ``` **EXPLANATION** if you leave the second parameter a blank string, then Angular will sort by the default order of the array (index), adding `true` at the end will enable the `reverse` parameter of Angular' `orderBy`
What is the structure of a single feed? It seems you can use the built-in filter from angular to order it the way you want. For example, if the field "id" is what provides "order" in the array, you would do this: ``` data-ng-repeat='feed in feeds | orderBy:id' ``` If you want that reversed, you just do: ``` data-ng-repeat='feed in feeds | orderBy:id:reverse' ``` Does that make sense? Not sure you need your own filter. If that is the case, perhaps try debugging (i.e. write to the console or otherwise) to see what you are actually being passed. If it is not an array, that's your problem, otherwise try this instead: ``` return Array.prototype.slice.call(items).reverse(); ``` Let me know if either of those work for you!
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
Please use directly Java-script slice function with reverse like this: ``` data-ng-repeat="item in items.slice().reverse()" ```
What is the structure of a single feed? It seems you can use the built-in filter from angular to order it the way you want. For example, if the field "id" is what provides "order" in the array, you would do this: ``` data-ng-repeat='feed in feeds | orderBy:id' ``` If you want that reversed, you just do: ``` data-ng-repeat='feed in feeds | orderBy:id:reverse' ``` Does that make sense? Not sure you need your own filter. If that is the case, perhaps try debugging (i.e. write to the console or otherwise) to see what you are actually being passed. If it is not an array, that's your problem, otherwise try this instead: ``` return Array.prototype.slice.call(items).reverse(); ``` Let me know if either of those work for you!
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
To make the array render in reverse and ordered by 'id', this should work: ``` data-ng-repeat="feed in feeds | orderBy:'id':true" ``` Let me know if that works for you. For your reference: <http://jsfiddle.net/byizzy/pgPVU/3/>
a solution which doesn't sort the array, but only copies and reverses it: `ng-repeat="item in items | orderBy : '[]': true"`
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
This is a bit tricky, but for all the people interested in reversing an array without creating new predicate functions and/or modifying the array etc... ``` ng-repeat="feed in feeds | orderBy:'':true" ``` or ``` ng-repeat="feed in feeds | orderBy:'-'" ``` **EXPLANATION** if you leave the second parameter a blank string, then Angular will sort by the default order of the array (index), adding `true` at the end will enable the `reverse` parameter of Angular' `orderBy`
Please use directly Java-script slice function with reverse like this: ``` data-ng-repeat="item in items.slice().reverse()" ```
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
Please use directly Java-script slice function with reverse like this: ``` data-ng-repeat="item in items.slice().reverse()" ```
Hope this will solve your problem ``` data-ng-repeat='feed in feeds.reverse()' ```
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
To make the array render in reverse and ordered by 'id', this should work: ``` data-ng-repeat="feed in feeds | orderBy:'id':true" ``` Let me know if that works for you. For your reference: <http://jsfiddle.net/byizzy/pgPVU/3/>
Hope this will solve your problem ``` data-ng-repeat='feed in feeds.reverse()' ```
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
This is a bit tricky, but for all the people interested in reversing an array without creating new predicate functions and/or modifying the array etc... ``` ng-repeat="feed in feeds | orderBy:'':true" ``` or ``` ng-repeat="feed in feeds | orderBy:'-'" ``` **EXPLANATION** if you leave the second parameter a blank string, then Angular will sort by the default order of the array (index), adding `true` at the end will enable the `reverse` parameter of Angular' `orderBy`
Another Alternative Way to Achieve the AngularJs Reverse is ``` <div ng-repeat="item in items | orderBy:'$index':true"> <code>{{item.id}} - {{item.name}}</code> </div> ```
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
This is a bit tricky, but for all the people interested in reversing an array without creating new predicate functions and/or modifying the array etc... ``` ng-repeat="feed in feeds | orderBy:'':true" ``` or ``` ng-repeat="feed in feeds | orderBy:'-'" ``` **EXPLANATION** if you leave the second parameter a blank string, then Angular will sort by the default order of the array (index), adding `true` at the end will enable the `reverse` parameter of Angular' `orderBy`
Hope this will solve your problem ``` data-ng-repeat='feed in feeds.reverse()' ```
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
Please use directly Java-script slice function with reverse like this: ``` data-ng-repeat="item in items.slice().reverse()" ```
a solution which doesn't sort the array, but only copies and reverses it: `ng-repeat="item in items | orderBy : '[]': true"`
21,286,822
When a user accesses **test.domain.co.uk**, I would like to show them the page at **channels/index.php?url=test** where **test** can be anything. I have this working with the following code: ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk$ RewriteCond %{HTTP_HOST} ^.+\.domain\.co\.uk$ RewriteRule ^(.*) %{HTTP_HOST}$1 [C] RewriteRule ^(.+)\.domain\.co\.uk/? channels/index.php?url=$1 [L] ``` However, I would also like it to work if you called **<http://test.domain.co.uk/login/>** And it would show you **channels/index.php?url=test&page=login** I have tried a few ways and it just shows it as if it is **?url=test**
2014/01/22
[ "https://Stackoverflow.com/questions/21286822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420051/" ]
What is the structure of a single feed? It seems you can use the built-in filter from angular to order it the way you want. For example, if the field "id" is what provides "order" in the array, you would do this: ``` data-ng-repeat='feed in feeds | orderBy:id' ``` If you want that reversed, you just do: ``` data-ng-repeat='feed in feeds | orderBy:id:reverse' ``` Does that make sense? Not sure you need your own filter. If that is the case, perhaps try debugging (i.e. write to the console or otherwise) to see what you are actually being passed. If it is not an array, that's your problem, otherwise try this instead: ``` return Array.prototype.slice.call(items).reverse(); ``` Let me know if either of those work for you!
Another Alternative Way to Achieve the AngularJs Reverse is ``` <div ng-repeat="item in items | orderBy:'$index':true"> <code>{{item.id}} - {{item.name}}</code> </div> ```
1,134,182
I'm unable to turn off backlight of my keyboard. I've tried every solutions available on the internet including **xset**, etc. But nothing seem to work on AsusFX503. I've Ubuntu 18.04 installed. Please help.
2019/04/15
[ "https://askubuntu.com/questions/1134182", "https://askubuntu.com", "https://askubuntu.com/users/800858/" ]
`cp -a ../somedir/.` is wrong. The general syntax is ``` cp source target ``` You only specified one argument. To copy something to current directory, you can run ``` cp ../somedir . ``` Note the space before the dot. `.` is shorthand for current directory. `..` is shorthand for parent directory.
You can say: `cp -a ../somedir .` if you want to copy the folder it self with its content Or you can say `cp -a ../somedir/* .` If you want to copy the content of the folder. the `-a` option will try to clone the same file structure with the same file tree to the new location
13,848,493
I basically have a table that holds counts for every date. I want to create a query that gives me the total # of counts over the entire table, as well as the total for yesterday. But when I try to join the table twice, the aggregates are off. Below is how you can replicate the results. ``` CREATE TABLE a (id int primary key); CREATE TABLE b (a_id int, b_id int, date date, count int, primary key (a_id,b_id,date)); INSERT INTO a VALUES (1); INSERT INTO b VALUES (1, 1, UTC_DATE(), 5); INSERT INTO b VALUES (1, 2, UTC_DATE(), 10); INSERT INTO b VALUES (1, 1, UTC_DATE()-1, 7); INSERT INTO b VALUES (1, 2, UTC_DATE()-1, 12); SELECT A.id,SUM(B.count) AS total_count,SUM(Y.count) AS y FROM a AS A LEFT JOIN b AS B ON (B.a_id=A.id) LEFT JOIN b AS Y ON (Y.a_id=A.id AND Y.date=UTC_DATE()-1) GROUP BY A.id; Results in: +----+-------------+------+ | id | total_count | y | +----+-------------+------+ | 1 | 68 | 76 | +----+-------------+------+ The correct result should be: +----+-------------+------+ | id | total_count | y | +----+-------------+------+ | 1 | 34 | 22 | +----+-------------+------+ ``` What's going on here? Is this a bug in mysql or am I not understanding how the joins are working.
2012/12/12
[ "https://Stackoverflow.com/questions/13848493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706441/" ]
No, it's not a bug in MySQL. Your JOIN conditions are generating "duplicate" rows. (Remove the aggregate functions and the GROUP BY, and you'll see what's happening. That row from table "a" is matching four rows from table "b". That's all fine and good. But when you add the join to the third table ("y"), each row returned from that third "y" table (two rows) is being "matched" to every row from the "b" table... so you wind up with a total of eight rows in your result set. (That's why the "total\_count" is getting doubled.) To get the result set you specify, you don't need to join that table "b" second time. Instead, just use a conditional test to determine whether that "count" should be included in the "y" total or not. e.g. ``` SELECT a.id , SUM(b.count) AS total_count , SUM(IF(b.date=UTC_DATE()-1 ,b.count,0)) AS y FROM a a LEFT JOIN b b ON (b.a_id=a.id) GROUP BY a.id; ``` --- Note that the MySQL `IF` expression can be replaced with an equivalent ANSI `CASE` expression for improved portability: ``` , SUM(CASE WHEN b.date=UTC_DATE()-1 THEN b.count ELSE 0 END) AS y ``` --- If you did want to do JOIN to that "b" table a second time, you would want the JOIN condition to be such that a row from "y" would match, at most, ONE row from "b", so as not to introduce any duplicates. So you'd basically need the join condition to include all of the columns in the primary key. (Note that the predicates in the join condition for table "y" guarantee that each from from "y" will match no more than ONE row from "b"): ``` SELECT a.id , SUM(b.count) AS total_count , SUM(y.count) AS y FROM a a LEFT JOIN b b ON b.a_id=a.id LEFT JOIN b y ON y.a_id = b.a_id AND y.b_id = b.b_id AND y.date = b.date AND y.date = UTC_DATE()-1 GROUP BY a.id; ``` (To get the first statement to return an identical resultset, with a potential NULL in place of a zero, you'd need to replace the '0' constant in the IF expression with 'NULL'. ``` , SUM(IF(b.date=UTC_DATE()-1 ,b.count,NULL)) AS y ```
``` SELECT A.id,b_count AS total_count,y_count as y FROM a AS A LEFT JOIN (select a_id,SUM(B.Count) b_count from b group by B.A_id) AS B1 ON (B1.a_id=A.id) LEFT JOIN (select a_id,SUM(Count) y_count from b where date=UTC_DATE()-1 group by B.A_id) AS Y ON (Y.a_id=A.id) ``` [SQLFiddle Demo](http://sqlfiddle.com/#!2/50b2e/8) ==================================================
64,886,259
this source code is use comprehension in python ``` hidden_layer = [{'weights':[random() for i in range (3)]} for i in range(1)] ``` so i transform to don't use comprehension expression and below is my source code to transform that ```py import random for i in range(3): for i in range (1): hidden_layer = {'weights':random()} ``` but it just have a only one value in dictionary what am i missing?
2020/11/18
[ "https://Stackoverflow.com/questions/64886259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13353248/" ]
```py pd.DataFrame({'col': ['AA_XX', 'AAA_BB_XX', 'AA_BB_XYX', 'AA_A_B_YXX']})['col'].apply(lambda r: '_'.join(r.split('_')[:-1])) ``` Explaination: ```py df = pd.DataFrame({'col': ['AA_XX', 'AAA_BB_XX', 'AA_BB_XYX', 'AA_A_B_YXX']}) ``` Creates ```py col 0 AA_XX 1 AAA_BB_XX 2 AA_BB_XYX 3 AA_A_B_YXX ``` Use apply in order to loop through the column you want to edit. I broke the string at `_` and then joined all parts leaving the last part at `_` ```py df['col'] = df['col'].apply(lambda r: '_'.join(r.split('_')[:-1])) print(df) ``` Results: ```py col 0 AA 1 AAA_BB 2 AA_BB 3 AA_A_B ``` If your dataset contains values like `AA` (values without underscore). Change the lambda like this ```py df = pd.DataFrame({'col': ['AA_XX', 'AAA_BB_XX', 'AA_BB_XYX', 'AA_A_B_YXX', 'AA']}) df['col'] = df['col'].apply(lambda r: '_'.join(r.split('_')[:-1]) if len(r.split('_')) > 1 else r) print(df) ```
Here is another way of going about it. ``` import pandas as pd data = {'s': ['AA_XX', 'AAA_BB_XX', 'AA_BB_XYX', 'AA_A_B_YXX']} df = pd.DataFrame(data) def cond1(s): temp_s = s.split('_') temp_len = len(temp_s) if len(temp_s) == 1: return temp_s else: return temp_s[:len(temp_s)-1] df['result'] = df['s'].apply(cond1) ```
64,886,259
this source code is use comprehension in python ``` hidden_layer = [{'weights':[random() for i in range (3)]} for i in range(1)] ``` so i transform to don't use comprehension expression and below is my source code to transform that ```py import random for i in range(3): for i in range (1): hidden_layer = {'weights':random()} ``` but it just have a only one value in dictionary what am i missing?
2020/11/18
[ "https://Stackoverflow.com/questions/64886259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13353248/" ]
You can do this simply using [`Series.str.split`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html) and [`Series.str.join`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html): ``` In [2381]: df Out[2381]: col1 0 AA_XX 1 AAA_BB_XX 2 AA_BB_XYX 3 AA_A_B_YXX In [2386]: df['col1'] = df['col1'].str.split('_').str[:-1].str.join('_') In [2387]: df Out[2387]: col1 0 AA 1 AAA_BB 2 AA_BB 3 AA_A_B ```
Here is another way of going about it. ``` import pandas as pd data = {'s': ['AA_XX', 'AAA_BB_XX', 'AA_BB_XYX', 'AA_A_B_YXX']} df = pd.DataFrame(data) def cond1(s): temp_s = s.split('_') temp_len = len(temp_s) if len(temp_s) == 1: return temp_s else: return temp_s[:len(temp_s)-1] df['result'] = df['s'].apply(cond1) ```
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
In fact this is an array, so you can simply loop it using a classic for loop, this is an exmaple snippet: ``` var data = [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; for (var i=0; i<data.length; i++) { console.log(data[i]); //You will get an object console.log(data[i].pk); } ``` In each iteration you will get an object and then you can access its properties. **EDIT:** It dependes on the type of `data` here, if it's a `string` like you mentioned in comments, you should parse it using `JSON.parse(data);` first then you can loop throught it. Otherwise if it is an `array` you will just need to directly loop throught its elements.
Here you go.. ``` <script> var object = [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; for(var i=0; i<object.length; i++){ console.log(object[i].pk); console.log(object[i].fields.email); console.log(object[i].fields.group_id); } </script> ``` Please let me know if it is not expected output.
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
Try using $.each instead of for loop : Try this : ``` var object = [{"pk": 1, "fields": {"email": "info@spott.com","locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; $.each(object, function(index, singleObject) { console.log("Single Object :%O",singleObject); }); ``` In console you will get object properly. For Fiddle Link Click Here : [Fiddle Link](https://jsfiddle.net/8ynch623/)
Here you go.. ``` <script> var object = [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; for(var i=0; i<object.length; i++){ console.log(object[i].pk); console.log(object[i].fields.email); console.log(object[i].fields.group_id); } </script> ``` Please let me know if it is not expected output.
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
In fact this is an array, so you can simply loop it using a classic for loop, this is an exmaple snippet: ``` var data = [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; for (var i=0; i<data.length; i++) { console.log(data[i]); //You will get an object console.log(data[i].pk); } ``` In each iteration you will get an object and then you can access its properties. **EDIT:** It dependes on the type of `data` here, if it's a `string` like you mentioned in comments, you should parse it using `JSON.parse(data);` first then you can loop throught it. Otherwise if it is an `array` you will just need to directly loop throught its elements.
response is in encoded manner,for access you want to decode response. ``` var x=[{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"},{"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; var object=JSON.parse(x);//you will get an object then you can find what you want. ```
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
In fact this is an array, so you can simply loop it using a classic for loop, this is an exmaple snippet: ``` var data = [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; for (var i=0; i<data.length; i++) { console.log(data[i]); //You will get an object console.log(data[i].pk); } ``` In each iteration you will get an object and then you can access its properties. **EDIT:** It dependes on the type of `data` here, if it's a `string` like you mentioned in comments, you should parse it using `JSON.parse(data);` first then you can loop throught it. Otherwise if it is an `array` you will just need to directly loop throught its elements.
you can try the bellow simple instruction : ``` var array=[{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; array.forEach(function(obj){ //to get the current object console.log(obj) // to access to the attribute of the current object // example console.log(obj.fields.email) }); ```
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
In fact this is an array, so you can simply loop it using a classic for loop, this is an exmaple snippet: ``` var data = [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; for (var i=0; i<data.length; i++) { console.log(data[i]); //You will get an object console.log(data[i].pk); } ``` In each iteration you will get an object and then you can access its properties. **EDIT:** It dependes on the type of `data` here, if it's a `string` like you mentioned in comments, you should parse it using `JSON.parse(data);` first then you can loop throught it. Otherwise if it is an `array` you will just need to directly loop throught its elements.
Try using $.each instead of for loop : Try this : ``` var object = [{"pk": 1, "fields": {"email": "info@spott.com","locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; $.each(object, function(index, singleObject) { console.log("Single Object :%O",singleObject); }); ``` In console you will get object properly. For Fiddle Link Click Here : [Fiddle Link](https://jsfiddle.net/8ynch623/)
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
Try using $.each instead of for loop : Try this : ``` var object = [{"pk": 1, "fields": {"email": "info@spott.com","locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; $.each(object, function(index, singleObject) { console.log("Single Object :%O",singleObject); }); ``` In console you will get object properly. For Fiddle Link Click Here : [Fiddle Link](https://jsfiddle.net/8ynch623/)
response is in encoded manner,for access you want to decode response. ``` var x=[{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"},{"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; var object=JSON.parse(x);//you will get an object then you can find what you want. ```
36,330,203
I have a JsonResponse which looks like this: ``` [{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}] ``` I have tried to access the data like this: ``` for (var key in data) { console.log(key) console.log(data[key]); } ``` The Response is every letter not every object. Which is a bit weird, after looking through the answers on stackoverflow, i tried the other ways as well but always get the same result. The Result should be the group\_name and the group\_id. Can anyone help me with that? Thank you in advance
2016/03/31
[ "https://Stackoverflow.com/questions/36330203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270231/" ]
Try using $.each instead of for loop : Try this : ``` var object = [{"pk": 1, "fields": {"email": "info@spott.com","locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; $.each(object, function(index, singleObject) { console.log("Single Object :%O",singleObject); }); ``` In console you will get object properly. For Fiddle Link Click Here : [Fiddle Link](https://jsfiddle.net/8ynch623/)
you can try the bellow simple instruction : ``` var array=[{"pk": 1, "fields": {"email": "info@spott.com", "locations": [1], "group_id": "spott", "group_name": "spott"}, "model": "grouping"}, {"pk": 2, "fields": {"email": "info@spott.com", "locations": [1, 2], "group_id": "spottalle", "group_name": "spott alle"}, "model": "grouping"}]; array.forEach(function(obj){ //to get the current object console.log(obj) // to access to the attribute of the current object // example console.log(obj.fields.email) }); ```
1,589,680
I have a Main window build with Qt Designer and I also have a widget built with Qt designer (both in a separate ui file). How can I instantiate my widget into my mainwindow at runtime?
2009/10/19
[ "https://Stackoverflow.com/questions/1589680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131981/" ]
The easiest way (using Designer) is to open your main window, drag a `QWidget` into it, and position/name the `QWidget` like you would your custom widget. Once that is done, right-click on the `QWidget`, and select **Promote to...**. A dialog will show up with the widgets it can be promoted to. At the bottom of that dialog, you can add a new widget for promotion. Type in the class name and include file information, and add that widget. Then select the entry in the list, and click the **Promote** button. At the end of this process, you should be able to recompile, and your custom widget will be where you placed it in the main window.
Can't you use [QMainWindow::setCentralWidget](http://qt.nokia.com/doc/4.5/qmainwindow.html#setCentralWidget) function?
74,137,405
I'm trying to reshape a data frame in a certain way. This is the data frame I have, | col\_1 | col\_2 | | --- | --- | | One | *Roxanne* | | Two | *Ghina* | | *Roxanne* | *Leila* | | *Ghina* | *George* | | Three | *Rock* | | Four | *Rock* | I'd like to reshape the dataframe such that it looks like this: | col\_3 | | --- | | *Roxanne* | | *Ghina* | | *Leila* | | *George* | | *Rock* | | *Rock* | | One | | Two | | Three | | Four | How would I go about doing this? *(without changing col\_2 values)*
2022/10/20
[ "https://Stackoverflow.com/questions/74137405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18641543/" ]
**Taking into account @OldBill 's comment & answer:** I corrected the code so that it gives an answer taking into account both of Op's problem. The counting of the trailing zero is @OldBill 's code and not mine. With ``` list = input("Enter the number: ") p = print("Trailing zeroes = ") print(p, list.count("0")) ``` What you do is `p = print("Trailing zeroes = ")` which is not a value. That explains the `None`when you print `p`. Plus your counting of trailing zero doesn't work, and count all zeroes. To have your code working, either you should have ``` num = input('Enter number: ') ntz = len(num)-len(num.rstrip('0')) print(f'Your input has {ntz} trailing zeroes') ``` or ``` num = input('Enter number: ') print('Your input has', len(num)-len(num.rstrip('0')),' trailing zeroes') ```
Here is a working example of the code: ``` i = input("Enter the number: ") p = "Trailing zeroes = " + str(i.count("0")) print(p) ``` Output: ``` Enter the number: 1000 Trailing zeroes = 3 ```
74,137,405
I'm trying to reshape a data frame in a certain way. This is the data frame I have, | col\_1 | col\_2 | | --- | --- | | One | *Roxanne* | | Two | *Ghina* | | *Roxanne* | *Leila* | | *Ghina* | *George* | | Three | *Rock* | | Four | *Rock* | I'd like to reshape the dataframe such that it looks like this: | col\_3 | | --- | | *Roxanne* | | *Ghina* | | *Leila* | | *George* | | *Rock* | | *Rock* | | One | | Two | | Three | | Four | How would I go about doing this? *(without changing col\_2 values)*
2022/10/20
[ "https://Stackoverflow.com/questions/74137405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18641543/" ]
To count **trailing** zeroes you could do this: ``` num = input('Enter number: ') ntz = len(s)-len(s.rstrip('0')) print(f'Your input has {ntz} trailing zeroes') ```
Here is a working example of the code: ``` i = input("Enter the number: ") p = "Trailing zeroes = " + str(i.count("0")) print(p) ``` Output: ``` Enter the number: 1000 Trailing zeroes = 3 ```
74,137,405
I'm trying to reshape a data frame in a certain way. This is the data frame I have, | col\_1 | col\_2 | | --- | --- | | One | *Roxanne* | | Two | *Ghina* | | *Roxanne* | *Leila* | | *Ghina* | *George* | | Three | *Rock* | | Four | *Rock* | I'd like to reshape the dataframe such that it looks like this: | col\_3 | | --- | | *Roxanne* | | *Ghina* | | *Leila* | | *George* | | *Rock* | | *Rock* | | One | | Two | | Three | | Four | How would I go about doing this? *(without changing col\_2 values)*
2022/10/20
[ "https://Stackoverflow.com/questions/74137405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18641543/" ]
**Taking into account @OldBill 's comment & answer:** I corrected the code so that it gives an answer taking into account both of Op's problem. The counting of the trailing zero is @OldBill 's code and not mine. With ``` list = input("Enter the number: ") p = print("Trailing zeroes = ") print(p, list.count("0")) ``` What you do is `p = print("Trailing zeroes = ")` which is not a value. That explains the `None`when you print `p`. Plus your counting of trailing zero doesn't work, and count all zeroes. To have your code working, either you should have ``` num = input('Enter number: ') ntz = len(num)-len(num.rstrip('0')) print(f'Your input has {ntz} trailing zeroes') ``` or ``` num = input('Enter number: ') print('Your input has', len(num)-len(num.rstrip('0')),' trailing zeroes') ```
Another way to do this: **NB1**: the *input* is a `string` not a `list`. **NB2**: This will count all zeroes - not just trailing – (*By @OldBill*) ``` text= input("Enter the number: ") print("Trailing zeroes = ", text.count("0")) ```
74,137,405
I'm trying to reshape a data frame in a certain way. This is the data frame I have, | col\_1 | col\_2 | | --- | --- | | One | *Roxanne* | | Two | *Ghina* | | *Roxanne* | *Leila* | | *Ghina* | *George* | | Three | *Rock* | | Four | *Rock* | I'd like to reshape the dataframe such that it looks like this: | col\_3 | | --- | | *Roxanne* | | *Ghina* | | *Leila* | | *George* | | *Rock* | | *Rock* | | One | | Two | | Three | | Four | How would I go about doing this? *(without changing col\_2 values)*
2022/10/20
[ "https://Stackoverflow.com/questions/74137405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18641543/" ]
To count **trailing** zeroes you could do this: ``` num = input('Enter number: ') ntz = len(s)-len(s.rstrip('0')) print(f'Your input has {ntz} trailing zeroes') ```
Another way to do this: **NB1**: the *input* is a `string` not a `list`. **NB2**: This will count all zeroes - not just trailing – (*By @OldBill*) ``` text= input("Enter the number: ") print("Trailing zeroes = ", text.count("0")) ```
443,390
Take the topology on $\Bbb R$, the real line, which is, $\tau=\{A\subseteq\Bbb R\mid\Bbb R\setminus A\text{ is countable}\}\cup \{\varnothing\}$. Can one find a convergence sequence in this topology? Because, Take a sequence $\{a\_n\}$, And suppose $a=\lim a\_n$. Take now the set $\Bbb R\setminus\{a\_n\}$. Then this is an open neighborhood of $a$ that doesn't contain any of $\{a\_n\}$ which is a contradiction... It feels like I am missing something basic in here but I can't put my finger on it. Thanks, Shir
2013/07/14
[ "https://math.stackexchange.com/questions/443390", "https://math.stackexchange.com", "https://math.stackexchange.com/users/60164/" ]
Be careful, if $a=a\_n$ for some $n\in\Bbb N$, then the set $\Bbb R-\{a\_n\mid n\in\Bbb N\}$ won't contain $a$ itself. But you can still take $(\Bbb R-\{a\_n\mid n\in\Bbb N\})\cup\{a\}$. This is always a neighborhood of $a$, and if the sequence isn't eventually constant, then it is not eventually in this neighborhood, so it does not converge to $a$. So the only convergent sequences are eventually constant. Also note that a convergent sequence has a unique limit, even though the space $(\Bbb R,\tau)$ is not Hausdorff. This means that we have an example of a space where the sequences do not completely determine the topology. For example, the set $A:=[0,\infty)$ is sequentially closed (every convergent sequence in $A$ has its limit within $A$) but not closed.
Stefan's answer is great. Here's an exercise relevant to your question which I think is worth thinking about: ***Exercise 1***: Let $\{a\_n\}\_{n\geq 1}$ be a sequence in the finite complement topology on $\mathbb{R}$. Under what conditions does $\{a\_n\}\_{n\geq 1}$ converge and how many limits does it have? The situation is, in some vague sense, "dual" to the case you're considering of the countable complement topology. I hope this exercise will be fun to think about for you!
19,129,456
Which way is more idiomatic to use Nullable<'a> or to use Option<'a> for representing a nullable int?
2013/10/02
[ "https://Stackoverflow.com/questions/19129456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139667/" ]
EMR does a lot of things for you that you won't find on standard Hadoop on EC2. Some particularly important ones include * Copying Hadoop logs from your machines to S3. This is very useful for debugging errors after the cluster has been shut down. * Running job flows of multiple MapReduce, Pig, or Hive jobs * Setting sensible configuration defaults based on hardware size you choose * Access to spot instances for cheaper compute * Ability to resize clusters dynamically You'll also find that the EMR S3 filesystem is faster and more reliable than the standard one packaged with Apache Hadoop. It supports Multipart upload, and streams writes directly to S3 rather than buffering to disk first. For a bit more on this, see [Tip #5](http://blog.mortardata.com/post/58920122308/s3-hadoop-performance.) Additionally, if you do decide to use EC2 directly, I'd recommend using instance-storage instead of EBS for your nodes. There's really no reason to pay the extra cost of EBS for Hadoop; you'll notice that EMR clusters all run on instance-storage nodes as well.
You are correct that EMR uses instance-store backed EC2 instances, rather than EBS. However, there's nothing stopping you from creating an instance-store based instance, packing an AMI and using it for your Hadoop cluster. Using EBS also might not represent a lot of additional costs, depending on your workload and frequency. Also, there's an added cost to the EC2 instance when using it through EMR. I've been using EMR for two years now and I would highly recommend the service as you don't need to invest time in managing and updating your distribution. If your workload is compatible with EMR (getting data from DynamoDB or S3), I would go for EMR as opposed to EC2/Hadoop.
43,771,830
We're using a `PUSH/PULL` Scalable Formal Communication Pattern in ZeroMQ. The sender application sends a total of 30,000 messages, 10kB each. There's a lot of data loss and hence we set the following on sender's side: ``` zmq_socket = context.socket(zmq.PUSH) zmq_socket.setsockopt(zmq.SNDBUF, 10240) zmq_socket.setsockopt(zmq.SNDHWM, 1) zmq_socket.bind("tcp://127.0.0.1:4999") ``` On receiver's side: ``` zmq_socket = context.socket(zmq.PULL) zmqSocket.setReceiveBufferSize(10240); zmqSocket.setRcvHWM(1); zmq_socket.connect("tcp://127.0.0.1:4999") ``` There's still data loss. Not sure how we can avoid packets being dropped silently. --- EDIT 1: **Sender** code in Python: ``` context = zmq.Context() zmq_socket = context.socket(zmq.PUSH) zmq_socket.setsockopt(zmq.SNDBUF, 10240) zmq_socket.setsockopt(zmq.SNDHWM, 1) zmq_socket.bind("tcp://127.0.0.1:4999") for file_name in list_of_files: # Reads data from a list of files: while True: # data from a file_name with open(os.path.join(self.local_base_dir,file_name), 'r') as sf: socket_data = sf.read(5120) if socket_data == '': sf.close() break # until EoF ret = zmq_socket.send(socket_data) if ret == 0: return True if ret == -1: print zmq_errno() ``` **Receiver** code in Java: ``` private ZMQ.Socket zmqSocket = zmqContext.socket(ZMQ.PULL); zmqSocket.setReceiveBufferSize(10240); zmqSocket.setRcvHWM(1); zmqSocket.connect(socketEndpoint); String message = new String(zmqSocket.recv()); messages.add(message); ```
2017/05/03
[ "https://Stackoverflow.com/questions/43771830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6656192/" ]
Remarks on ZeroMQ: *based just on what has been posted above so far in an MVCE* -------------------------------------------------------------------------------- **Never** pre-maturely optimise resources allocations: all quasi-optimisation decisions introduced in code before the code runtime operations meet all functional requirements are misleading. "Optimising" ill-functioning distributed system makes no sense at all. Only once the runtime was tested and is guaranteed to work as specified, some resources may get fine-tuned ex-post, given some positive output rationale of ( newly accrued cost of doing so + positive performance benefits + reduced resource use ) makes sense for doing so. Never vice versa. **Never.** **Never** design a ZeroMQ infrastructure as a consumable ( ref. as seen in the Java MCVE snippet above ). It takes a remarkable time to the O/S to setup and adjust the ZeroMQ world "under the hood", that the **`zmq.Context( n_IO_threads )`** instantiation and all the ad-hoc derived `.Socket()` instances have to create ( all inside the O/S scheduler dictated time-frames + under some realistic multi-agent system behaviour dynamics, given the distributed counterparties are introduced into underlying raw socket distributed handshaking & multi-lateral negotiations ), so even if SLOC one-liners or naive school-book examples may look that way, never jump into an ALAP setup of the ZeroMQ infrastructure "right" before reading just one message and dispose the whole cathedral of the ZeroMQ framework ( hidden under the hood ) - be that explicitly or ( the worse ) implicitly - right after `.recv()` just one message. **Never.** **Never** ignore documented ZeroMQ features. If it states: > > ØMQ does **not** guarantee that the socket will accept as many as **`ZMQ_SNDHWM`** messages, and the actual limit may be as much as 60-70% lower depending on the flow of messages on the socket. > > > one ought never ever attempt to declare `.setsockopt( ZMQ_SNDHWM, 1 )`. **Never.** **Never** leave the ZeroMQ infrastructure school-book "naked". There are many fair reasons to design principal **`try: except: finally;`** structures for the ZeroMQ infrastructure usage so as to release all the resources, down to the O/S maintained `port#`-s, in every case, incl. the unhandled exceptions. This practice is a serious resource-management must ( not only for re-entrant Factory patterns ) any professional design shall never skip. **Never.** ``` GLOBAL_context = zmq.Context( setMoreIOthreadsForPERFORMANCE ) // future PERF PUSH_socket = GLOBAL_context.socket( zmq.PUSH ) // -------------------------------------------------------------- // .SET PUSH_socket.setsockopt( zmq.SNDBUF, 123456 ) // ^ HI 1st PUSH_socket.setsockopt( zmq.SNDHWM, 123456 ) // ^ HI 1st // PULL_socket.setsockopt( zmq.MAXMSGSIZE, 12345 ) // ~ LOCK !DDoS PUSH_socket.setsockopt( zmq.AFFINITY, 0 ) // [0] 1st // -------------------------------------------------------------- // GRACEFUL TERMINATION: PUSH_socket.setsockopt( zmq.LINGER, 0 ) // ALWAYS // -------------------------------------------------------------- // PUSH_socket.bind( "tcp://127.0.0.1:4999" ) // IPC: w/o TCP overheads // -------------------------------------------------------------- // ... app logic ... // -------------------------------------------------------------- // ALWAYS PUSH_socket.close() // ALWAYS GLOBAL_context.term() // ALWAYS ``` --- Epilogue: --------- ZeroMQ clearly states, that one either gets the complete message or nothing. So the application design has to take all due care, if in a need to deliver each and every message, as the smart ZeroMQ tools handle many things, but leave this at the designer's responsibility. Given your comment has explained there is just one receiver for the proposed system, one may rather go into **`PAIR/PAIR`** Scalable Formal Communication Pattern + avoiding all the overheads associated with all the layers of the L3|L2|L1->-L1|L2|L3 multi-stack packet assembly / disassembly & O/S buffers management associated with the **`tcp://`** transport-class and go into **`ipc://`** ( if O/S permits ) or **`vmci://`** less complex & thus a lot faster transport-classes, having thus lower ( better ) latency & protocol overheads. Using `PAIR/PAIR` archetype also prevents nasty surprises once a DoS-attack **`.connect()`**-s onto a PUSH\_socket side, where ZeroMQ has no means to avoid such step and such game-changing step efficiently devastates your design efforts, as the default behaviour is to start round-robin serving all the "potentially" connected peers ( even after some attacker(s) 's('ve) been forced to disconnect ). Last but not least, one ought manage such distributed processes to rather always prefer **non-blocking** mode of **`.send() / .recv()`** calls in professional high-performance signalling / messaging & **`.poll()`** based control tools inside the most critical real-time sections of the data-pumping services used inside the respective application domain.
Use the `ZMQ_IMMEDIATE` flag to prevent any loss in messages that got queued to pipes which don't have a completed connection. From <http://api.zeromq.org/4-2:zmq-setsockopt#toc21> > > **`ZMQ_IMMEDIATE`: Queue messages only to completed connections** > > > By default queues will fill on outgoing connections even if the > connection has not completed. This can lead to "lost" messages on > sockets with round-robin routing (`REQ`, `PUSH`, `DEALER`). If this option > is set to 1, messages shall be queued only to completed connections. > This will cause the socket to block if there are no other connections, > but will prevent queues from filling on pipes awaiting connection. > Option value type int Option value unit boolean Default value `0` > (`false`) Applicable socket types all, only for connection-oriented > transports. > > > ``` zmq_socket.setsockopt(zmq.ZMQ_IMMEDIATE, 1) ```
55,004,829
``` clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) import pdb; pdb.set_trace() training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ``` i increments as normal and produces correct output however j remains at 0 for three loops and then jumps to 3. I don't understand this.
2019/03/05
[ "https://Stackoverflow.com/questions/55004829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8271065/" ]
There is a logical error on `clean.index(j)`. Array.index will return the first matched index in that array. So if there are some equal variables there will be some error You can inspect with below code. ``` malware = [1,2,3,4,5,6,7,8,8,8,8,8,2] clean = [1,2,3,4,4,4,4,4,4,2,4,4,4,4] clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ```
``` for a in something ``` a is what is contained in something, not the index for example: ``` for n in [1, 10, 9, 3]: print(n) ``` gives ``` 1 10 9 3 ```
55,004,829
``` clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) import pdb; pdb.set_trace() training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ``` i increments as normal and produces correct output however j remains at 0 for three loops and then jumps to 3. I don't understand this.
2019/03/05
[ "https://Stackoverflow.com/questions/55004829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8271065/" ]
``` for a in something ``` a is what is contained in something, not the index for example: ``` for n in [1, 10, 9, 3]: print(n) ``` gives ``` 1 10 9 3 ```
op has already figured the question, but in case anyone is wondering or needs a TL;DR of Barkin's comment, its just a small correction, replace ``` for i in malware ``` ``` for j in clean ``` with ``` for i in range(len(malware)) ``` ``` for j in range(len(clean)) ``` and at the end remove the .index() function, and place i and j.
55,004,829
``` clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) import pdb; pdb.set_trace() training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ``` i increments as normal and produces correct output however j remains at 0 for three loops and then jumps to 3. I don't understand this.
2019/03/05
[ "https://Stackoverflow.com/questions/55004829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8271065/" ]
There is a logical error on `clean.index(j)`. Array.index will return the first matched index in that array. So if there are some equal variables there will be some error You can inspect with below code. ``` malware = [1,2,3,4,5,6,7,8,8,8,8,8,2] clean = [1,2,3,4,4,4,4,4,4,2,4,4,4,4] clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ```
You either want ``` for i in range(len(malware)) ``` or ``` for i, element in enumerate(malware) ``` at which point the i is the count and the element in the malware.index(i) The last one is considered best practice when needing both the index and the element at that index in the loop.
55,004,829
``` clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) import pdb; pdb.set_trace() training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ``` i increments as normal and produces correct output however j remains at 0 for three loops and then jumps to 3. I don't understand this.
2019/03/05
[ "https://Stackoverflow.com/questions/55004829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8271065/" ]
You either want ``` for i in range(len(malware)) ``` or ``` for i, element in enumerate(malware) ``` at which point the i is the count and the element in the malware.index(i) The last one is considered best practice when needing both the index and the element at that index in the loop.
op has already figured the question, but in case anyone is wondering or needs a TL;DR of Barkin's comment, its just a small correction, replace ``` for i in malware ``` ``` for j in clean ``` with ``` for i in range(len(malware)) ``` ``` for j in range(len(clean)) ``` and at the end remove the .index() function, and place i and j.
55,004,829
``` clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) import pdb; pdb.set_trace() training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ``` i increments as normal and produces correct output however j remains at 0 for three loops and then jumps to 3. I don't understand this.
2019/03/05
[ "https://Stackoverflow.com/questions/55004829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8271065/" ]
There is a logical error on `clean.index(j)`. Array.index will return the first matched index in that array. So if there are some equal variables there will be some error You can inspect with below code. ``` malware = [1,2,3,4,5,6,7,8,8,8,8,8,2] clean = [1,2,3,4,4,4,4,4,4,2,4,4,4,4] clean_offset = len(malware) tuple_clean = [] tuple_malware = [] for i in malware: tuple_malware.append([malware.index(i), 0]) print(malware.index(i)) print(tuple_malware) for j in clean: tuple_clean.append([(clean_offset + clean.index(j)), 1]) print(clean.index(j)) print(tuple_clean) training_data_size_mal = 0.8 * len(malware) training_data_size_clean = 0.8 * len(clean) ```
op has already figured the question, but in case anyone is wondering or needs a TL;DR of Barkin's comment, its just a small correction, replace ``` for i in malware ``` ``` for j in clean ``` with ``` for i in range(len(malware)) ``` ``` for j in range(len(clean)) ``` and at the end remove the .index() function, and place i and j.
3,763
I have a gift for learning languages, but I haven't made much use of it. There's people younger than me that know more languages than I do. The only one I've ever learned was German, and that was because I was listening to NDH metal at the time, which I don't do anymore. I'm sick of my talent going to waste. I used to pride myself on how much more easily I could languages compared to everyone else around me. I don't get that joy anymore, because I have nothing to show for it other than my rusty German. I tried to find a reason to do so just to increase my linguistic knowledge, but from what I've been told, that would be completely unnecessary and a waste of time. I've heard it said a lot that learning languages helps with your brain health or something. Sadly, that's not enough motivation to try and get me to learn a language which I never use. I've never succeeded in learning any language that I had no use for. I have a pile of a dozen different language books in pristine condition that I bought over a decade ago, because I never used them much. The only one that actually shows any wear is my Spanish book. And no, I don't know Spanish. Can anyone list some reasons to learn another language? I've already exhausted the biggest reasons. To learn to understand some foreigners, to broaden my knowledge on languages, to improve my own health. My own pride is really the only reason I keep trying. Its the only thing I've ever been good at. And I'm completely wasting it.
2018/08/26
[ "https://languagelearning.stackexchange.com/questions/3763", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/-1/" ]
Start using the languages ========================= The internet is full of content in different languages. Take something that is interesting to you and start reading or listening. I enjoy roleplaying games, so I read some roleplaying blogs and material in the languages I am learning or know too poorly. I also set my computer, phone and browser to the language I want to learn the most. Alternatively, give up ====================== The sunk cost fallacy is when you do not give up on something because of former investments, even though giving up would be the best thing to do. If the investments (in books, in your identity as a good language learner) are a burden from past ages, leave them be. Make it a ritual that clears them; give the books away to more enthusiastic people or sell them, or give them to a charity or local library or school etc. Only learn languages in a way that is meaningful to you. If there is no such way, and the matter causes stress, then better drop it entirely.
Here's a reason: While learning another language, you also absorb some foreign culture and a different way of thinking and more importantly of perceiving the world around you. It opens doors to experiences, as if you were travelling far places, except these ones could be waiting only a block away from where you live. Being able to communicate with foreign people in their native language gives you a glimpse of what life could be other than what you are used to. It's very useful for a reflective lifestyle, and breaking out of the filter bubble prison that one tends lives in. That said, learning languages is one way to train your curiosity, a skill so natural as a child, and easy to loose when getting older. There are other ways too, do what works for you, but I am convinced, that training your curiosity is very healthy for your brain function and quality of life in old age.
3,763
I have a gift for learning languages, but I haven't made much use of it. There's people younger than me that know more languages than I do. The only one I've ever learned was German, and that was because I was listening to NDH metal at the time, which I don't do anymore. I'm sick of my talent going to waste. I used to pride myself on how much more easily I could languages compared to everyone else around me. I don't get that joy anymore, because I have nothing to show for it other than my rusty German. I tried to find a reason to do so just to increase my linguistic knowledge, but from what I've been told, that would be completely unnecessary and a waste of time. I've heard it said a lot that learning languages helps with your brain health or something. Sadly, that's not enough motivation to try and get me to learn a language which I never use. I've never succeeded in learning any language that I had no use for. I have a pile of a dozen different language books in pristine condition that I bought over a decade ago, because I never used them much. The only one that actually shows any wear is my Spanish book. And no, I don't know Spanish. Can anyone list some reasons to learn another language? I've already exhausted the biggest reasons. To learn to understand some foreigners, to broaden my knowledge on languages, to improve my own health. My own pride is really the only reason I keep trying. Its the only thing I've ever been good at. And I'm completely wasting it.
2018/08/26
[ "https://languagelearning.stackexchange.com/questions/3763", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/-1/" ]
Start using the languages ========================= The internet is full of content in different languages. Take something that is interesting to you and start reading or listening. I enjoy roleplaying games, so I read some roleplaying blogs and material in the languages I am learning or know too poorly. I also set my computer, phone and browser to the language I want to learn the most. Alternatively, give up ====================== The sunk cost fallacy is when you do not give up on something because of former investments, even though giving up would be the best thing to do. If the investments (in books, in your identity as a good language learner) are a burden from past ages, leave them be. Make it a ritual that clears them; give the books away to more enthusiastic people or sell them, or give them to a charity or local library or school etc. Only learn languages in a way that is meaningful to you. If there is no such way, and the matter causes stress, then better drop it entirely.
Well, then. You probably will use a language. ***Possibilities*** - An Indian using offensive language at you (I've had an experience of this on an Internet text chat, never knew or heard of "maderchod" before, it means motherfucker). - A tourist asking for directions. - A hacker has installed ransomware on to your computer (you just never know!). - You actually go to a country and try to read the street signs. and more to come...... <3 First of all, it depends what language is actually is. If it's Maori or something like a tribal language, then fair enough. Do you mean dead languages or popular ones you think you will never use (what's that Russian ransomware saying? It's alien, omg). If you want to understand English to the next level, ***Latin*** will be suggested. After all, even law students require some of it. Why Latin? It teaches you the concepts and origins of the English language, from many roots and stems. After all, knowing a word individually is like learning Chinese characters without bothering with their parts (radicals). For example, the word 'fero' means to carry, now it's used with "transfer". Why Ancient Egyptian ***hieroglyphics***? One day, you might find something really special. It's a possibility, don't think this sounds stupid! What about Ancient Greek? Its alphabet is definitely very useful to know at least (for example, maths and capabilities of reading Greek stuff). Personally, I think any language is useful. It's about dedicating to your time to it (which obviously requires motivation, none of "maybe I should learn something else perhaps").
3,763
I have a gift for learning languages, but I haven't made much use of it. There's people younger than me that know more languages than I do. The only one I've ever learned was German, and that was because I was listening to NDH metal at the time, which I don't do anymore. I'm sick of my talent going to waste. I used to pride myself on how much more easily I could languages compared to everyone else around me. I don't get that joy anymore, because I have nothing to show for it other than my rusty German. I tried to find a reason to do so just to increase my linguistic knowledge, but from what I've been told, that would be completely unnecessary and a waste of time. I've heard it said a lot that learning languages helps with your brain health or something. Sadly, that's not enough motivation to try and get me to learn a language which I never use. I've never succeeded in learning any language that I had no use for. I have a pile of a dozen different language books in pristine condition that I bought over a decade ago, because I never used them much. The only one that actually shows any wear is my Spanish book. And no, I don't know Spanish. Can anyone list some reasons to learn another language? I've already exhausted the biggest reasons. To learn to understand some foreigners, to broaden my knowledge on languages, to improve my own health. My own pride is really the only reason I keep trying. Its the only thing I've ever been good at. And I'm completely wasting it.
2018/08/26
[ "https://languagelearning.stackexchange.com/questions/3763", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/-1/" ]
If you don't plan to use a language actively (i.e. speaking and writing), you can still learn it out of sheer fascination with its (linguistic) features, or with the literature and culture associated with it. This fascination provides a source of motivation. For example, some people are interested in the diversity of grammatical features in languages that are not related to their own language. (This requires a strong interest in linguistics, otherwise you'll give up.) Others learn, for example, [Sanskrit](https://en.wikipedia.org/wiki/Sanskrit) in order to be able to read the [Vedas](https://en.wikipedia.org/wiki/Vedas) and classical works such as the [Mahabharata](https://en.wikipedia.org/wiki/Mahabharata) and the [Ramayana](https://en.wikipedia.org/wiki/Ramayana). (From *their* point of view, this isn't a waste of time.) **If you can't think of any motivation for *beginning* to learn a language, you won't have any motivation to *continue* learning it either**, unless you get hooked along the way. Being able to use a language contributes to your motivation to continue learning a language. But you'll need some kind of spark to get the language learning engine going. You mention that you have many language learning resources that you haven't used yet. These resources don't constitute a motivation. The argument, "I have invested so much time/money into this language, so I should continue or all is lost" would be an example of the "**sunk-cost fallacy**". The website Logically Fallacious defines this fallacy as follows: > > Reasoning that further investment is warranted on the fact that the resources already invested will be lost otherwise, not taking into consideration the overall losses involved in the further investment. > > > You also state, "There's people younger than me that know more languages than I do." So what? **Other people's success is not your failure!** (Quoted from a [video by Lindie Botes](https://www.youtube.com/watch?v=tJtOTDXBymM).) Also, if you think this is a form of envy (I don't want to jump to conclusion based on a few paragraphs), you should learn how to turn envy into motivation; see for example the article [4 Ways to Benefit from Envy](https://psychcentral.com/blog/4-ways-to-benefit-from-envy/). ([Leon Ho](https://www.lifehack.org/614250/how-envy-drains-your-motivation), founder of Lifehack, thinks that "envy costs your entire mind".)
Here's a reason: While learning another language, you also absorb some foreign culture and a different way of thinking and more importantly of perceiving the world around you. It opens doors to experiences, as if you were travelling far places, except these ones could be waiting only a block away from where you live. Being able to communicate with foreign people in their native language gives you a glimpse of what life could be other than what you are used to. It's very useful for a reflective lifestyle, and breaking out of the filter bubble prison that one tends lives in. That said, learning languages is one way to train your curiosity, a skill so natural as a child, and easy to loose when getting older. There are other ways too, do what works for you, but I am convinced, that training your curiosity is very healthy for your brain function and quality of life in old age.
3,763
I have a gift for learning languages, but I haven't made much use of it. There's people younger than me that know more languages than I do. The only one I've ever learned was German, and that was because I was listening to NDH metal at the time, which I don't do anymore. I'm sick of my talent going to waste. I used to pride myself on how much more easily I could languages compared to everyone else around me. I don't get that joy anymore, because I have nothing to show for it other than my rusty German. I tried to find a reason to do so just to increase my linguistic knowledge, but from what I've been told, that would be completely unnecessary and a waste of time. I've heard it said a lot that learning languages helps with your brain health or something. Sadly, that's not enough motivation to try and get me to learn a language which I never use. I've never succeeded in learning any language that I had no use for. I have a pile of a dozen different language books in pristine condition that I bought over a decade ago, because I never used them much. The only one that actually shows any wear is my Spanish book. And no, I don't know Spanish. Can anyone list some reasons to learn another language? I've already exhausted the biggest reasons. To learn to understand some foreigners, to broaden my knowledge on languages, to improve my own health. My own pride is really the only reason I keep trying. Its the only thing I've ever been good at. And I'm completely wasting it.
2018/08/26
[ "https://languagelearning.stackexchange.com/questions/3763", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/-1/" ]
If you don't plan to use a language actively (i.e. speaking and writing), you can still learn it out of sheer fascination with its (linguistic) features, or with the literature and culture associated with it. This fascination provides a source of motivation. For example, some people are interested in the diversity of grammatical features in languages that are not related to their own language. (This requires a strong interest in linguistics, otherwise you'll give up.) Others learn, for example, [Sanskrit](https://en.wikipedia.org/wiki/Sanskrit) in order to be able to read the [Vedas](https://en.wikipedia.org/wiki/Vedas) and classical works such as the [Mahabharata](https://en.wikipedia.org/wiki/Mahabharata) and the [Ramayana](https://en.wikipedia.org/wiki/Ramayana). (From *their* point of view, this isn't a waste of time.) **If you can't think of any motivation for *beginning* to learn a language, you won't have any motivation to *continue* learning it either**, unless you get hooked along the way. Being able to use a language contributes to your motivation to continue learning a language. But you'll need some kind of spark to get the language learning engine going. You mention that you have many language learning resources that you haven't used yet. These resources don't constitute a motivation. The argument, "I have invested so much time/money into this language, so I should continue or all is lost" would be an example of the "**sunk-cost fallacy**". The website Logically Fallacious defines this fallacy as follows: > > Reasoning that further investment is warranted on the fact that the resources already invested will be lost otherwise, not taking into consideration the overall losses involved in the further investment. > > > You also state, "There's people younger than me that know more languages than I do." So what? **Other people's success is not your failure!** (Quoted from a [video by Lindie Botes](https://www.youtube.com/watch?v=tJtOTDXBymM).) Also, if you think this is a form of envy (I don't want to jump to conclusion based on a few paragraphs), you should learn how to turn envy into motivation; see for example the article [4 Ways to Benefit from Envy](https://psychcentral.com/blog/4-ways-to-benefit-from-envy/). ([Leon Ho](https://www.lifehack.org/614250/how-envy-drains-your-motivation), founder of Lifehack, thinks that "envy costs your entire mind".)
Well, then. You probably will use a language. ***Possibilities*** - An Indian using offensive language at you (I've had an experience of this on an Internet text chat, never knew or heard of "maderchod" before, it means motherfucker). - A tourist asking for directions. - A hacker has installed ransomware on to your computer (you just never know!). - You actually go to a country and try to read the street signs. and more to come...... <3 First of all, it depends what language is actually is. If it's Maori or something like a tribal language, then fair enough. Do you mean dead languages or popular ones you think you will never use (what's that Russian ransomware saying? It's alien, omg). If you want to understand English to the next level, ***Latin*** will be suggested. After all, even law students require some of it. Why Latin? It teaches you the concepts and origins of the English language, from many roots and stems. After all, knowing a word individually is like learning Chinese characters without bothering with their parts (radicals). For example, the word 'fero' means to carry, now it's used with "transfer". Why Ancient Egyptian ***hieroglyphics***? One day, you might find something really special. It's a possibility, don't think this sounds stupid! What about Ancient Greek? Its alphabet is definitely very useful to know at least (for example, maths and capabilities of reading Greek stuff). Personally, I think any language is useful. It's about dedicating to your time to it (which obviously requires motivation, none of "maybe I should learn something else perhaps").
3,763
I have a gift for learning languages, but I haven't made much use of it. There's people younger than me that know more languages than I do. The only one I've ever learned was German, and that was because I was listening to NDH metal at the time, which I don't do anymore. I'm sick of my talent going to waste. I used to pride myself on how much more easily I could languages compared to everyone else around me. I don't get that joy anymore, because I have nothing to show for it other than my rusty German. I tried to find a reason to do so just to increase my linguistic knowledge, but from what I've been told, that would be completely unnecessary and a waste of time. I've heard it said a lot that learning languages helps with your brain health or something. Sadly, that's not enough motivation to try and get me to learn a language which I never use. I've never succeeded in learning any language that I had no use for. I have a pile of a dozen different language books in pristine condition that I bought over a decade ago, because I never used them much. The only one that actually shows any wear is my Spanish book. And no, I don't know Spanish. Can anyone list some reasons to learn another language? I've already exhausted the biggest reasons. To learn to understand some foreigners, to broaden my knowledge on languages, to improve my own health. My own pride is really the only reason I keep trying. Its the only thing I've ever been good at. And I'm completely wasting it.
2018/08/26
[ "https://languagelearning.stackexchange.com/questions/3763", "https://languagelearning.stackexchange.com", "https://languagelearning.stackexchange.com/users/-1/" ]
Here's a reason: While learning another language, you also absorb some foreign culture and a different way of thinking and more importantly of perceiving the world around you. It opens doors to experiences, as if you were travelling far places, except these ones could be waiting only a block away from where you live. Being able to communicate with foreign people in their native language gives you a glimpse of what life could be other than what you are used to. It's very useful for a reflective lifestyle, and breaking out of the filter bubble prison that one tends lives in. That said, learning languages is one way to train your curiosity, a skill so natural as a child, and easy to loose when getting older. There are other ways too, do what works for you, but I am convinced, that training your curiosity is very healthy for your brain function and quality of life in old age.
Well, then. You probably will use a language. ***Possibilities*** - An Indian using offensive language at you (I've had an experience of this on an Internet text chat, never knew or heard of "maderchod" before, it means motherfucker). - A tourist asking for directions. - A hacker has installed ransomware on to your computer (you just never know!). - You actually go to a country and try to read the street signs. and more to come...... <3 First of all, it depends what language is actually is. If it's Maori or something like a tribal language, then fair enough. Do you mean dead languages or popular ones you think you will never use (what's that Russian ransomware saying? It's alien, omg). If you want to understand English to the next level, ***Latin*** will be suggested. After all, even law students require some of it. Why Latin? It teaches you the concepts and origins of the English language, from many roots and stems. After all, knowing a word individually is like learning Chinese characters without bothering with their parts (radicals). For example, the word 'fero' means to carry, now it's used with "transfer". Why Ancient Egyptian ***hieroglyphics***? One day, you might find something really special. It's a possibility, don't think this sounds stupid! What about Ancient Greek? Its alphabet is definitely very useful to know at least (for example, maths and capabilities of reading Greek stuff). Personally, I think any language is useful. It's about dedicating to your time to it (which obviously requires motivation, none of "maybe I should learn something else perhaps").
5,421,018
I have a jQuery tooltip plugin that displays a tooltip when I hover over a anchor tag. I have modified my jCarousel so that my images are contained in anchor tags. When I hover over the first batch of images the tooltip hover function gets called. However, when the next batch of images come into view, the tooltip function does not get called again. I have created a basic example of my issue here: <http://jsfiddle.net/QAFZX/3/> I have tried using the itemVisibleInCallback callback but that doesn't allow my function to fire on all visible images.
2011/03/24
[ "https://Stackoverflow.com/questions/5421018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446677/" ]
You made a function that requires a parameter, and when you called the function, you didn't bring the parameter! ``` itemLastInCallback: { onAfterAnimation: afterAnimationLastInCallback($(this)) } ``` instead of: ``` itemLastInCallback: { onAfterAnimation: afterAnimationLastInCallback } ``` Fixed it for you, [click here](http://jsfiddle.net/QAFZX/6/)
I managed to fix this issue by using a different javascript tooltip. So that on mouseover and mouseout elements on my image would either show or hide the tooltip.
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
Some people don't realize that TeX can do math. I read years ago (maybe 2007?) on comp.text.tex that someone was using TeX for the business end of a billing system. I can't find that post though. Does anyone else remember it?
My most unusual use cases: * measuring all the ads for a national phonebook and forcing those which are w/in a reasonable tolerance to the exact size per their database entry, outputting a colour-coded PDF which lists those which are not and their size deviations * as the back-end for an ad re-sizing system which allows interactive, asymmetric, re-sizing of advertisements * back-end for an ad creation system allowing one to enter/format text, import a graphic, and shift the text and graphic around as desired interactively.
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
The `docstrip` program distributed with LaTeX does not typeset anything, it is used to extract source code (while evaluating boolean guards) from documented sources, and to optionally install them in specified locations. Another such program distributed with LaTeX is `latexbug`. `latex latexbug` interacts with the user to create a draft email of a bug report with several fields filled in accurately with information such as the latex version being used, it is of course written in LaTeX. [`makebst`](http://www.ctan.org/pkg/custom-bib) is an interactive program written in TeX that queries the user on the desired properties of the bibliography style and then produces a custom bibtex style file to meet the requested specification. [`basix`](http://www.ctan.org/pkg/basix) is an interpreter for the BASIC language written in TeX. TeX can also of course solve [sudoko](http://tug.org/pracjourn/2008-2/distract/). One other one I forgot to mention [xmltex](http://ctan.org/tex-archive/macros/xmltex/base) is a namespace aware XML parser written in TeX. It *can* be used for typesetting documents, but also other things. Its default behaviour is not to typeset anything and just to echo the parse tree to the log file.
Back in the day, it used to be the #1 means to provide math formulas for PowerPoint presentations. I don't know what the math capabilities of PowerPoint are nowadays.
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
The `sudokubundle` provides three packages related to Sudoku: 1. `printsudoko` which prints a given puzzle; 2. `solvesudoku` which attempts to solve a given puzzle; 3. `createsudoku` which (randomly) creates and prints a puzzle that `solvesudoku` can solve. There are other packages for playing other games, such as Bruno Le Floch's `reverxii` for Reversi, and for printing games like chess and bridge.
Some people don't realize that TeX can do math. I read years ago (maybe 2007?) on comp.text.tex that someone was using TeX for the business end of a billing system. I can't find that post though. Does anyone else remember it?
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
Let's not forget the amazing [`reverxii.tex`](http://ctan.org/tex-archive/macros/plain/contrib/reverxii) from our great friend [Bruno Le Floch](https://tex.stackexchange.com/users/2707). From the documentation: --- **reverxii - Playing Reversi, in the spirit of [xii.tex](http://www.ctan.org/pkg/xii)** The file `reverxii.tex` is a 938 character long TeX program which lets you play [Reversi](http://en.wikipedia.org/wiki/Reversi) against your favorite typesetting engine. Play by running ``` tex reverxii.tex ``` in the command line. This will also produce a record of your game as `reverxii.dvi.` Typeset the documentation by running ``` pdflatex reverxii.tex ``` This is work in progress, all suggestions/comments/bug reports are welcome! --- Hats off to Bruno! `:)`
Back in the day, it used to be the #1 means to provide math formulas for PowerPoint presentations. I don't know what the math capabilities of PowerPoint are nowadays.
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
The `sudokubundle` provides three packages related to Sudoku: 1. `printsudoko` which prints a given puzzle; 2. `solvesudoku` which attempts to solve a given puzzle; 3. `createsudoku` which (randomly) creates and prints a puzzle that `solvesudoku` can solve. There are other packages for playing other games, such as Bruno Le Floch's `reverxii` for Reversi, and for printing games like chess and bridge.
With the `beamer` and `impressive` packages, it's used for presentations, as I've [learned](https://tex.stackexchange.com/questions/41116/advantage-of-latex-presentations) :)
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
One, very incredible solution to an ICFP contest was created by Steve Hicks. He did an amazing job by coding a Mars rover guidance *bot*. See: <http://sdh33b.blogspot.com/2008/07/icfp-contest-2008.html> He has shared his code and written about it in the above link. This clearly shows that `TeX` is not just for typesetting (although it clearly is best at that!).
Some people don't realize that TeX can do math. I read years ago (maybe 2007?) on comp.text.tex that someone was using TeX for the business end of a billing system. I can't find that post though. Does anyone else remember it?
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
The `docstrip` program distributed with LaTeX does not typeset anything, it is used to extract source code (while evaluating boolean guards) from documented sources, and to optionally install them in specified locations. Another such program distributed with LaTeX is `latexbug`. `latex latexbug` interacts with the user to create a draft email of a bug report with several fields filled in accurately with information such as the latex version being used, it is of course written in LaTeX. [`makebst`](http://www.ctan.org/pkg/custom-bib) is an interactive program written in TeX that queries the user on the desired properties of the bibliography style and then produces a custom bibtex style file to meet the requested specification. [`basix`](http://www.ctan.org/pkg/basix) is an interpreter for the BASIC language written in TeX. TeX can also of course solve [sudoko](http://tug.org/pracjourn/2008-2/distract/). One other one I forgot to mention [xmltex](http://ctan.org/tex-archive/macros/xmltex/base) is a namespace aware XML parser written in TeX. It *can* be used for typesetting documents, but also other things. Its default behaviour is not to typeset anything and just to echo the parse tree to the log file.
Some people don't realize that TeX can do math. I read years ago (maybe 2007?) on comp.text.tex that someone was using TeX for the business end of a billing system. I can't find that post though. Does anyone else remember it?
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
One, very incredible solution to an ICFP contest was created by Steve Hicks. He did an amazing job by coding a Mars rover guidance *bot*. See: <http://sdh33b.blogspot.com/2008/07/icfp-contest-2008.html> He has shared his code and written about it in the above link. This clearly shows that `TeX` is not just for typesetting (although it clearly is best at that!).
Let's not forget the amazing [`reverxii.tex`](http://ctan.org/tex-archive/macros/plain/contrib/reverxii) from our great friend [Bruno Le Floch](https://tex.stackexchange.com/users/2707). From the documentation: --- **reverxii - Playing Reversi, in the spirit of [xii.tex](http://www.ctan.org/pkg/xii)** The file `reverxii.tex` is a 938 character long TeX program which lets you play [Reversi](http://en.wikipedia.org/wiki/Reversi) against your favorite typesetting engine. Play by running ``` tex reverxii.tex ``` in the command line. This will also produce a record of your game as `reverxii.dvi.` Typeset the documentation by running ``` pdflatex reverxii.tex ``` This is work in progress, all suggestions/comments/bug reports are welcome! --- Hats off to Bruno! `:)`
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
Some "crazy" people use TeX as a afm file parser and converter to "virtual fonts". Really impressive. It's called [fontinst](http://www.ctan.org/pkg/fontinst). > > The reason fontinst is so portable is simply that it is written in TEX, exploiting those features of the language which does other things than typesetting. > > >
With the `beamer` and `impressive` packages, it's used for presentations, as I've [learned](https://tex.stackexchange.com/questions/41116/advantage-of-latex-presentations) :)
53,082
Most people use TeX and its many varieties to create printed documents, such as reports, books, flyer's, etc. Occasionally, I have found software that uses TeX markup for other purposes, for e.g., the flashcard software, [Anki](http://ankisrs.net/) can use TeX to render on-screen flash cards. * Beyond producing typical printed documents, what other applications does TeX have? * Are there any other software programs which use TeX for other purposes?
2012/04/24
[ "https://tex.stackexchange.com/questions/53082", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/8918/" ]
The `docstrip` program distributed with LaTeX does not typeset anything, it is used to extract source code (while evaluating boolean guards) from documented sources, and to optionally install them in specified locations. Another such program distributed with LaTeX is `latexbug`. `latex latexbug` interacts with the user to create a draft email of a bug report with several fields filled in accurately with information such as the latex version being used, it is of course written in LaTeX. [`makebst`](http://www.ctan.org/pkg/custom-bib) is an interactive program written in TeX that queries the user on the desired properties of the bibliography style and then produces a custom bibtex style file to meet the requested specification. [`basix`](http://www.ctan.org/pkg/basix) is an interpreter for the BASIC language written in TeX. TeX can also of course solve [sudoko](http://tug.org/pracjourn/2008-2/distract/). One other one I forgot to mention [xmltex](http://ctan.org/tex-archive/macros/xmltex/base) is a namespace aware XML parser written in TeX. It *can* be used for typesetting documents, but also other things. Its default behaviour is not to typeset anything and just to echo the parse tree to the log file.
The `sudokubundle` provides three packages related to Sudoku: 1. `printsudoko` which prints a given puzzle; 2. `solvesudoku` which attempts to solve a given puzzle; 3. `createsudoku` which (randomly) creates and prints a puzzle that `solvesudoku` can solve. There are other packages for playing other games, such as Bruno Le Floch's `reverxii` for Reversi, and for printing games like chess and bridge.
11,688,689
I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game) How can I do this? EDIT: Here my code: ``` TextView test1; String punkte = "15"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences save = getSharedPreferences(punkte, 0); save.edit().putString("score", punkte); SharedPreferences load = getSharedPreferences(punkte, 0); String points = load.getString("score", "0"); test1 = (TextView) findViewById(R.id.test1); test1.setText(points); } ```
2012/07/27
[ "https://Stackoverflow.com/questions/11688689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557131/" ]
You should be using `SharedPrefences`. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there. Here is a code sample. To access variables: ``` SharedPreferences mPrefs = getSharedPreferences("label", 0); String mString = mPrefs.getString("tag", "default_value_if_variable_not_found"); ``` To edit the variables and commit (store) them: ``` SharedPreferences.Editor mEditor = mPrefs.edit(); mEditor.putString("tag", value_of_variable).commit(); ``` Make sure both "tag" fields match!
Use `SharedPreference`, this is a better option. To see [this](http://samir-mangroliya.blogspot.in/p/android-shared-preferences.html) tutorial.
11,688,689
I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game) How can I do this? EDIT: Here my code: ``` TextView test1; String punkte = "15"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences save = getSharedPreferences(punkte, 0); save.edit().putString("score", punkte); SharedPreferences load = getSharedPreferences(punkte, 0); String points = load.getString("score", "0"); test1 = (TextView) findViewById(R.id.test1); test1.setText(points); } ```
2012/07/27
[ "https://Stackoverflow.com/questions/11688689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557131/" ]
Use `SharedPreference`, this is a better option. To see [this](http://samir-mangroliya.blogspot.in/p/android-shared-preferences.html) tutorial.
sample code: save: ``` SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putString("statepara1", ts); editor.commit(); ``` get: ``` SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); String ret = settings.getString("statepara1", "0"); ```
11,688,689
I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game) How can I do this? EDIT: Here my code: ``` TextView test1; String punkte = "15"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences save = getSharedPreferences(punkte, 0); save.edit().putString("score", punkte); SharedPreferences load = getSharedPreferences(punkte, 0); String points = load.getString("score", "0"); test1 = (TextView) findViewById(R.id.test1); test1.setText(points); } ```
2012/07/27
[ "https://Stackoverflow.com/questions/11688689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557131/" ]
You should be using `SharedPrefences`. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there. Here is a code sample. To access variables: ``` SharedPreferences mPrefs = getSharedPreferences("label", 0); String mString = mPrefs.getString("tag", "default_value_if_variable_not_found"); ``` To edit the variables and commit (store) them: ``` SharedPreferences.Editor mEditor = mPrefs.edit(); mEditor.putString("tag", value_of_variable).commit(); ``` Make sure both "tag" fields match!
sample code: save: ``` SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putString("statepara1", ts); editor.commit(); ``` get: ``` SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); String ret = settings.getString("statepara1", "0"); ```
50,603,723
I'm trying to use dynamic pivot to have a column containing dates to be the column names. I want this table: ``` App Date Count Excel 2018-05-01 1 Excel 2018-05-02 1 Excel 2018-05-03 2 Word 2018-05-02 3 Word 2018-05-07 5 Word 2018-05-12 2 Paint 2018-05-07 6 ``` to look like this: ``` 2018-05-01 2018-05-02 2018-05-03 2018-05-07 2018-05-12 Excel 1 1 2 0 0 Word 0 3 0 5 2 Paint 0 0 0 6 0 ``` I can't use a normal pivot as I don't know how many or what the dates will actually be. Each app can have a different number of rows. This table isn't just a `SELECT * FROM TABLE` either, it's made up of subqueries and CTEs so is a little complicated to work with. Any help is appreciated. Let me know if you need more information.
2018/05/30
[ "https://Stackoverflow.com/questions/50603723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9771609/" ]
Ok. so your case is preflight request. when client tries to send a custom header, server needs to verify that it accepts that header. so in that case, a preflight options request is sent with header Access-Control-Request-Headers. if server responds that it will accept the custom header. then actual request will be sent. in your case server response header - access-control-allow-headers does not contains your custom header name. thats why it failed. [![enter image description here](https://i.stack.imgur.com/wdjkH.png)](https://i.stack.imgur.com/wdjkH.png) Note: the actual POST request does not include the Access-Control-Request-\* headers; they are needed only for the OPTIONS request.Read this article for more explanation - [cors - options call](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
Your axios request is correct. You need to allow your custom headers on server side. If you have your api in php then this code will work for you. ``` header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD"); header("Access-Control-Allow-Headers: Content-Type, Custom-Header"); ``` Once you will allow your custom headers on server side, your axios requests will start working fine.
5,478,733
I am just writing a class implementing the ServiceLocator pattern. ``` public class ServiceFactory : IServiceFactory { private IDictionary<Type, object> instantiatedServices; public ServiceFactory() { instantiatedServices = new Dictionary<Type, object>(); } public T GetService<T>() where T : class, new() { if (this.instantiatedServices.ContainsKey(typeof(T))) { return (T)this.instantiatedServices[typeof(T)]; } else { T service = new T(); instantiatedServices.Add(typeof(T), service); return service; } } } ``` Now I have several questions: 1.) Where should I call this class from? the app.xaml.cs doing wpf stuff? 2.) Should I register services , if yes where should I do that? 3.) When I do lazy Initialization of the service "ICustomerService" why then should I create a Register(T service)-method for it? thats double work. 4.) Should I go at all for a service locator? **UPDATE** At the moment I feel I have to rape a DI tool for my individual purposes which are => **App.xaml.cs** => Here I create the MainWindow and set its datacontext to the MainViewModel.cs ``` public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { var mainVM = new MainViewModel(); var mainWindow = new MainWindow(); mainWindow.DataContext = mainVM; mainWindow.ShowDialog(); } } ``` **MainViewModel.cs** => Here I preload/setup data which I need for certain Controller/ViewModel`s like the LessonPlannerDailyViewModel or LessonPlannerWeeklyViewModel etc... ``` public class MainViewModel : SuperViewModel { private LightCommand _newSchoolYearWizardCommand; private LightCommand _showSchoolclassAdministrationCommand; private LightCommand _showLessonPlannerDailyCommand; private LightCommand _showLessonPlannerWeeklyCommand; private LightCommand _openSchoolYearWizardCommand; private SuperViewModel _vm; private FadeTransition _fe = new FadeTransition(); private readonly IMainRepository _mainService; private readonly ILessonPlannerService _lessonPlannerService; private readonly IAdminService _adminService; private readonly IDocumentService _documentService; private readonly IMediator _mediator; private readonly IDailyPlanner _dailyVM; private readonly IWeeklyPlanner _weeklyVM; private SchoolclassAdministrationViewModel _saVM; public MainViewModel() { // These are a couple of services I create here because I need them in MainViewModel _mediator = new Mediator(); _mainService = new MainRepository(); _lessonPlannerService = new LessonPlannerService(); _adminService = new AdminService(); _documentService = new DocumentService(); this._mediator.Register(this); InitSchoolclassAdministration(); } //... Create other ViewModel/Controller via button commands and their execute method } ``` On of the other ViewModel is the **LessonPlannerDailyViewModel.cs** => Here I create a bindable collection of PeriodViewModel objects which take in their constructor some services. At next paragraph after the following code see the DocumentListViewModel.cs created by ONE PeriodViewModel which takes again services - the same that I created in the MainViewModel... - ``` public class LessonPlannerDailyViewModel : LessonPlannerBaseViewModel, IDailyPlanner { private ILessonPlannerService _lpRepo; private IMainRepository _mainRepo; private IMediator _mediator; private IDocumentService _docRepo; private ObservableCollection<PeriodViewModel> _periodListViewModel; private LightCommand _firstDateCommand; private LightCommand _lastDateCommand; private LightCommand _nextDateCommand; private LightCommand _previousDateCommand; public LessonPlannerDailyViewModel(IMediator mediator, ILessonPlannerService lpRepo, IMainRepository mainRepo, IDocumentService docRepo) { _mediator = mediator; _lpRepo = lpRepo; _mainRepo = mainRepo; _docRepo = docRepo; _mediator.Register(this); SchoolYear schoolyear = _mainRepo.GetSchoolYear(); MinDate = schoolyear.Start; MaxDate = schoolyear.End; SelectedDate = DateTime.Now; } private void LoadLessonPlannerByDay(DateTime data) { _periodListViewModel = new ObservableCollection<PeriodViewModel>(); _lpRepo.GetLessonPlannerByDay(data).ForEach(p => { _periodListViewModel.Add(new PeriodViewModel(p, _lpRepo, _docRepo)); }); PeriodListViewModel = _periodListViewModel; } private DateTime _selectedDate; public DateTime SelectedDate { get { return _selectedDate; } set { if (_selectedDate.Date == value.Date) return; _selectedDate = value; this.RaisePropertyChanged("SelectedDate"); LoadLessonPlannerByDay( value ); } } // ... } ``` **PeriodViewModel.cs** => Every DataRow in my DataGrid has a Period and a Period has a certain cell datatemplated to the DocumentListViewModel - Period 1 has N Documents is the relation FYI... so a PeriodViewModel creates a DocumentListViewModel. ``` public class PeriodViewModel : SuperViewModel { private Period _period; private ILessonPlannerService _lpRepo; public PeriodViewModel(Period period, ILessonPlannerService lpRepo, IDocumentService docRepo) { _period = period; _lpRepo = lpRepo; // Update properties to database this.PropertyChanged += (o, e) => { switch (e.PropertyName) { case "Homework": _lpRepo.UpdateHomeWork(PeriodNumber, LessonDayDate, Homework); break; case "Content": _lpRepo.UpdateContent(PeriodNumber, LessonDayDate, Content); break; } }; Documents = new DocumentListViewModel(_period.Id, period.Documents, docRepo); } //... } ``` **DocumentListViewModel.cs** => Here I setup the commands for add/delete/open a document and this can be done with the documentService/documentRepository ``` public class DocumentListViewModel : SuperViewModel { private LightCommand _deleteDocumentCommand; private LightCommand _addDocumentCommand; private LightCommand _openDocumentCommand; private int _parentId; private readonly IDocumentService _documentService; public DocumentListViewModel(int parentId,ObservableCollection<Document> documents, IDocumentService documentService) { _parentId = parentId; _documentService = documentService; DocumentList = documents; SelectedDocuments = new ObservableCollection<Document>(); } // ... } ``` To sum the problem up: Do you see the chain of objects cascading the services from top: MainViewodel -> LessonPlannerDailyViewModel -> PeriodViewModel -> DocumentListViewModel I need to cascade them because if I am not using a static service locator I can only make sure to have ONE instance of a service when I am cascading the services... How can a DI tool here help me **CONCRETELY** doing a wpf app following the MVVM pattern?
2011/03/29
[ "https://Stackoverflow.com/questions/5478733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/252289/" ]
The fourth question is the easiest to answer: **no,** you shouldn't go for Service Locator at all because [it's an anti-pattern](http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx). So what is the alternative? Use the [Register Resolve Release pattern](http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx). That should be a good starting point to answer your other questions.
1. You would call this whenever you need an instance of a service `T`. You would need more robust code to handle the cases where you don't have any logic to handle where `T` is unknown or unable to be handled by your service locator. 2. This varies from application to application, but most typically, registration of services happens at the application entry point, e.g. in Windows applications, before the form is loaded, in ASP.NET applications, in the`Application_Start` method, in services, when the service `Main` method is loaded. This is an application-specific call that you have to make depending on your needs. Note it is typically a *one-time* call. 3. If you want to expose lazy initialization, then you should have two registration methods, one which will take an instance of `T` (if you want to always use that one instance), or one that takes a `Func<T>`, which can be called when the instance is needed (and then cached, if desired). 4. If by this you mean write one yourself, then I would have to emphatically say no, it's [already been done for you](http://commonservicelocator.codeplex.com) and if you don't like that level of granularity, there is nothing stopping you from using tools like [Ninject](http://ninject.org/), [Unity](http://unity.codeplex.com/) or any of the other DI tools out there.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
You need to install [Microsoft SQL Server Compact 4.0](http://www.microsoft.com/download/en/details.aspx?id=17876).
I had a server. It ran windows updates. And a message waiting for restart was open. After restart it worked again.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
If you look at the config you'll see that installing SQL Server was a red herring; ``` <add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/> ``` SqlServerCE is not, I'm afraid, full blown SQL Server, it's [SQL Server Compact Edition](http://www.microsoft.com/sqlserver/en/us/editions/compact.aspx). I would have thought that would have been installed with VS Express, however you can download the specific installers from [here](http://www.microsoft.com/download/en/details.aspx?id=17876) I actually had both SQLServerCE and Express installed, but the tutorial used Compact Edition: [One step within part 4 of the tutorial](http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part4-cs) is to explicitly add the part you quoted to the Web.config. So this is a part of the web.config by intention. But deleting this part from the web.config makes it possible to add the Controller in the way the tutorial described it. While this means no longer *exactly* following the tutorial, it's fine for me. (This results in the creation of an MvcMovie.Models.MovieDBContext database in SQL Server Express.)
This worked for me, hope it helps ``` <add name="MovieDBContext" connectionString="Data Source=(local);Initial Catalog=Movies; Integrated Security=true;" providerName="System.Data.SqlClient" /> </connectionStrings> ```
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
I was having the same problem so I replaced ``` <add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/> ``` with the following ``` <add name="MovieDBContext" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;database=Movies;User ID=sa;password=" providerName="System.Data.SqlClient"/> ``` And it worked enough to let me continue working. I too would also eventually learn how to make these kinds of applications work with mysql at some point, but for now this should at least help you continue with the tutorial.
You need to install [Microsoft SQL Server Compact 4.0](http://www.microsoft.com/download/en/details.aspx?id=17876).
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
You need to install [Microsoft SQL Server Compact 4.0](http://www.microsoft.com/download/en/details.aspx?id=17876).
Rebuilding the project wont catch config errors in the DBContext section... the build process does not walk through connections, so you can build all day and still bomb out. As suggested above, fix the config so the connection string matches MachineName/SQLInstanceName/DBName with the correct SQL config. Worked just fine by just modifying my web.config in my solution.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
<http://forums.asp.net/t/1679349.aspx/1> CypressBender Re: Unable to retrieve metadata for \* Unable to find the requested .Net Framework Data Provider.... Aug 08, 2011 07:44 PM|LINK I installed Microsoft SQL Server Compact 4.0, and that fixed the problem for me. <http://www.microsoft.com/download/en/details.aspx?id=17876>
1. Make sure that you build prior to adding the controller. If that doesn't work... 2. Create a new project, create a new sql server database manually and see if you can connect to it. If not, then the problem is indeed in your sql server config on your machine. You can try going to postgres just be sure that the provider you choose has support for EF code first.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
If you look at the config you'll see that installing SQL Server was a red herring; ``` <add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/> ``` SqlServerCE is not, I'm afraid, full blown SQL Server, it's [SQL Server Compact Edition](http://www.microsoft.com/sqlserver/en/us/editions/compact.aspx). I would have thought that would have been installed with VS Express, however you can download the specific installers from [here](http://www.microsoft.com/download/en/details.aspx?id=17876) I actually had both SQLServerCE and Express installed, but the tutorial used Compact Edition: [One step within part 4 of the tutorial](http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part4-cs) is to explicitly add the part you quoted to the Web.config. So this is a part of the web.config by intention. But deleting this part from the web.config makes it possible to add the Controller in the way the tutorial described it. While this means no longer *exactly* following the tutorial, it's fine for me. (This results in the creation of an MvcMovie.Models.MovieDBContext database in SQL Server Express.)
1. Make sure that you build prior to adding the controller. If that doesn't work... 2. Create a new project, create a new sql server database manually and see if you can connect to it. If not, then the problem is indeed in your sql server config on your machine. You can try going to postgres just be sure that the provider you choose has support for EF code first.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
If you look at the config you'll see that installing SQL Server was a red herring; ``` <add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/> ``` SqlServerCE is not, I'm afraid, full blown SQL Server, it's [SQL Server Compact Edition](http://www.microsoft.com/sqlserver/en/us/editions/compact.aspx). I would have thought that would have been installed with VS Express, however you can download the specific installers from [here](http://www.microsoft.com/download/en/details.aspx?id=17876) I actually had both SQLServerCE and Express installed, but the tutorial used Compact Edition: [One step within part 4 of the tutorial](http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part4-cs) is to explicitly add the part you quoted to the Web.config. So this is a part of the web.config by intention. But deleting this part from the web.config makes it possible to add the Controller in the way the tutorial described it. While this means no longer *exactly* following the tutorial, it's fine for me. (This results in the creation of an MvcMovie.Models.MovieDBContext database in SQL Server Express.)
I changed my SQL providerName="System.Data.SqlClient" in web.config , since I have SQL client as well as SQL compact installed on my system.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
<http://forums.asp.net/t/1679349.aspx/1> CypressBender Re: Unable to retrieve metadata for \* Unable to find the requested .Net Framework Data Provider.... Aug 08, 2011 07:44 PM|LINK I installed Microsoft SQL Server Compact 4.0, and that fixed the problem for me. <http://www.microsoft.com/download/en/details.aspx?id=17876>
What I did was in order to overcome the first problem I put in Web.config the code: ``` <add name="MovieDBContext" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Movies.sdf;Integrated Security=True" providerName="System.Data.SqlClient"/> ``` Notice I am creating SQL CE 4 database, therefore the .sdf and not .mdf Next, you should receive another connection errors on the page /Movies, so replace the above code with : ``` <add name="MovieDBContext" connectionString="Data Source=|DataDirectory|\Movies.sdf;" providerName="System.Data.SqlServerCe.4.0" /> ``` And you should be fine.
6,508,519
I want a user to be able to access objects (could be JSON or XML) using a restful syntax rather than having to use query strings. So instead of `http://mywebsite.com/objects/get=obj1&get=obj2&get=someotherobject/` they could do something like `http://mywebsite.com/objects/obj1/obj2/` and the xml/JSON would be returned. They could list the objects in any order just like you can with query strings. In asp.net mvc you map a route like so: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{param}", new { controller = "MyController", action = "MyAction", param = "" } ); ``` I would want to do something like: ``` routes.MapRoute( "MyRoute", "MyController/MyAction/{params}", new { controller = "MyController", action = "MyAction", params = [] } ); ``` where the `params` array would contain each get.
2011/06/28
[ "https://Stackoverflow.com/questions/6508519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277140/" ]
I was having the same problem so I replaced ``` <add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/> ``` with the following ``` <add name="MovieDBContext" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;database=Movies;User ID=sa;password=" providerName="System.Data.SqlClient"/> ``` And it worked enough to let me continue working. I too would also eventually learn how to make these kinds of applications work with mysql at some point, but for now this should at least help you continue with the tutorial.
<http://forums.asp.net/t/1679349.aspx/1> CypressBender Re: Unable to retrieve metadata for \* Unable to find the requested .Net Framework Data Provider.... Aug 08, 2011 07:44 PM|LINK I installed Microsoft SQL Server Compact 4.0, and that fixed the problem for me. <http://www.microsoft.com/download/en/details.aspx?id=17876>