qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
12,552,843
I have a `Localizable.strings` file for my project's i18n, and a lib uses `KYLocalizable.strings`. I have considered to make `Localizable.strings` "subclass" from `KYLocalizable.strings`, but it cannot as far as I know. So instead, I want to define a function macro like what SDK does: ``` #define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] #define NSLocalizedStringFromTable(key, tbl, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)] ``` Pseudo code: ``` #define CustomLocalizedString(key, comment) \ // if key exists in Localizable.strings // use it [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] // else // search it in KYLocalizable.strings [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] ``` so I can just use `CustomLocalizedString(<key>, <comment>)` in my project. But how to check whether the key exists in `Localizable.strings` or not? Thanks in advance!!
2012/09/23
[ "https://Stackoverflow.com/questions/12552843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904365/" ]
If the key doesn't exist, the string you will receive will be the key itself. So as long as you suppose you will never use the key as a localized string, you can test if NSLocalizableString returned you the key or not.
Thanks @Xval, I've just figured it myself and here's a simple function (please offer some suggestions if you have a better idea): ``` #define KYLocalizedString(key, comment) \ [[[NSBundle mainBundle] localizedStringForKey:(key) value:nil table:nil] isEqualToString:(key)] ? \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] : \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] ``` `localizedStringForKey:` will return a NSString that as @Xval said. :)
12,552,843
I have a `Localizable.strings` file for my project's i18n, and a lib uses `KYLocalizable.strings`. I have considered to make `Localizable.strings` "subclass" from `KYLocalizable.strings`, but it cannot as far as I know. So instead, I want to define a function macro like what SDK does: ``` #define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] #define NSLocalizedStringFromTable(key, tbl, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)] ``` Pseudo code: ``` #define CustomLocalizedString(key, comment) \ // if key exists in Localizable.strings // use it [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] // else // search it in KYLocalizable.strings [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] ``` so I can just use `CustomLocalizedString(<key>, <comment>)` in my project. But how to check whether the key exists in `Localizable.strings` or not? Thanks in advance!!
2012/09/23
[ "https://Stackoverflow.com/questions/12552843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904365/" ]
If the key doesn't exist, the string you will receive will be the key itself. So as long as you suppose you will never use the key as a localized string, you can test if NSLocalizableString returned you the key or not.
For Swift: ``` var key = "your_key" NSBundle.mainBundle().localizedStringForKey(key, value: NSBundle.mainBundle().localizedStringForKey(key, value:"", table: nil), table: "Your_Custom_Localizable_File") ``` Just to clarify things, according to Apple's documentation: ``` If key is not found and value is nil or an empty string, returns key. ``` So using this technique you can nest calls to as many localization files as you want.
12,552,843
I have a `Localizable.strings` file for my project's i18n, and a lib uses `KYLocalizable.strings`. I have considered to make `Localizable.strings` "subclass" from `KYLocalizable.strings`, but it cannot as far as I know. So instead, I want to define a function macro like what SDK does: ``` #define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] #define NSLocalizedStringFromTable(key, tbl, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)] ``` Pseudo code: ``` #define CustomLocalizedString(key, comment) \ // if key exists in Localizable.strings // use it [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] // else // search it in KYLocalizable.strings [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] ``` so I can just use `CustomLocalizedString(<key>, <comment>)` in my project. But how to check whether the key exists in `Localizable.strings` or not? Thanks in advance!!
2012/09/23
[ "https://Stackoverflow.com/questions/12552843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904365/" ]
If the key doesn't exist, the string you will receive will be the key itself. So as long as you suppose you will never use the key as a localized string, you can test if NSLocalizableString returned you the key or not.
I wrote this handy extension for localized strings, so you can just use the `localized()` function to get the localized string(you can also pass arguments) and the `isLocalized` computed property to check whether the string is localized or not: ``` extension String { var isLocalized: Bool { return localized() != self } func localized(parameter: CVarArg? = nil) -> String { if let parameter = parameter { return String(format: NSLocalizedString(self, comment: ""), parameter) } else { return NSLocalizedString(self, comment: "") } } func localized(parameter0: CVarArg, parameter1: CVarArg) -> String { return String(format: NSLocalizedString(self, comment: ""), parameter0, parameter1) } } ```
12,552,843
I have a `Localizable.strings` file for my project's i18n, and a lib uses `KYLocalizable.strings`. I have considered to make `Localizable.strings` "subclass" from `KYLocalizable.strings`, but it cannot as far as I know. So instead, I want to define a function macro like what SDK does: ``` #define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] #define NSLocalizedStringFromTable(key, tbl, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)] ``` Pseudo code: ``` #define CustomLocalizedString(key, comment) \ // if key exists in Localizable.strings // use it [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] // else // search it in KYLocalizable.strings [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] ``` so I can just use `CustomLocalizedString(<key>, <comment>)` in my project. But how to check whether the key exists in `Localizable.strings` or not? Thanks in advance!!
2012/09/23
[ "https://Stackoverflow.com/questions/12552843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904365/" ]
In this call: ``` [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] ``` The **value** parameter (currently an empty string) will be used if a string can't be located in your strings file using the specified key. So... all you should need to do is place your second lookup to *KYLocalizable.strings* as the value to that parameter. The code would look similar to this (I didn't actually run this, but it should be close): ``` [[NSBundle mainBundle] localizedStringForKey:(key) value:[[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] table:nil] ``` At that point, the string in *Localizable.strings* will be used if found. Otherwise, the value in KYLocalizable.strings will be used. If it isn't found either, then a blank string will be returned (since that is what is specified in the nested **value** parameter). However, one inefficiency of this approach is that your application will actually attempt the lookup in KYLocalizable.strings first on every attempt (so that this result can subsequently be passed in as the **value** parameter when doing the outer lookup to *Localizable.strings*). If you actually want to check *Localized.strings* first, and then *only* do a second lookup if the string isn't found, I think you'd need to create a method with that logic in it (for example, add a method in a category on NSBundle).
Thanks @Xval, I've just figured it myself and here's a simple function (please offer some suggestions if you have a better idea): ``` #define KYLocalizedString(key, comment) \ [[[NSBundle mainBundle] localizedStringForKey:(key) value:nil table:nil] isEqualToString:(key)] ? \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] : \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] ``` `localizedStringForKey:` will return a NSString that as @Xval said. :)
12,552,843
I have a `Localizable.strings` file for my project's i18n, and a lib uses `KYLocalizable.strings`. I have considered to make `Localizable.strings` "subclass" from `KYLocalizable.strings`, but it cannot as far as I know. So instead, I want to define a function macro like what SDK does: ``` #define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] #define NSLocalizedStringFromTable(key, tbl, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)] ``` Pseudo code: ``` #define CustomLocalizedString(key, comment) \ // if key exists in Localizable.strings // use it [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] // else // search it in KYLocalizable.strings [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] ``` so I can just use `CustomLocalizedString(<key>, <comment>)` in my project. But how to check whether the key exists in `Localizable.strings` or not? Thanks in advance!!
2012/09/23
[ "https://Stackoverflow.com/questions/12552843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904365/" ]
In this call: ``` [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] ``` The **value** parameter (currently an empty string) will be used if a string can't be located in your strings file using the specified key. So... all you should need to do is place your second lookup to *KYLocalizable.strings* as the value to that parameter. The code would look similar to this (I didn't actually run this, but it should be close): ``` [[NSBundle mainBundle] localizedStringForKey:(key) value:[[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] table:nil] ``` At that point, the string in *Localizable.strings* will be used if found. Otherwise, the value in KYLocalizable.strings will be used. If it isn't found either, then a blank string will be returned (since that is what is specified in the nested **value** parameter). However, one inefficiency of this approach is that your application will actually attempt the lookup in KYLocalizable.strings first on every attempt (so that this result can subsequently be passed in as the **value** parameter when doing the outer lookup to *Localizable.strings*). If you actually want to check *Localized.strings* first, and then *only* do a second lookup if the string isn't found, I think you'd need to create a method with that logic in it (for example, add a method in a category on NSBundle).
For Swift: ``` var key = "your_key" NSBundle.mainBundle().localizedStringForKey(key, value: NSBundle.mainBundle().localizedStringForKey(key, value:"", table: nil), table: "Your_Custom_Localizable_File") ``` Just to clarify things, according to Apple's documentation: ``` If key is not found and value is nil or an empty string, returns key. ``` So using this technique you can nest calls to as many localization files as you want.
12,552,843
I have a `Localizable.strings` file for my project's i18n, and a lib uses `KYLocalizable.strings`. I have considered to make `Localizable.strings` "subclass" from `KYLocalizable.strings`, but it cannot as far as I know. So instead, I want to define a function macro like what SDK does: ``` #define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] #define NSLocalizedStringFromTable(key, tbl, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)] ``` Pseudo code: ``` #define CustomLocalizedString(key, comment) \ // if key exists in Localizable.strings // use it [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] // else // search it in KYLocalizable.strings [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] ``` so I can just use `CustomLocalizedString(<key>, <comment>)` in my project. But how to check whether the key exists in `Localizable.strings` or not? Thanks in advance!!
2012/09/23
[ "https://Stackoverflow.com/questions/12552843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904365/" ]
In this call: ``` [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] ``` The **value** parameter (currently an empty string) will be used if a string can't be located in your strings file using the specified key. So... all you should need to do is place your second lookup to *KYLocalizable.strings* as the value to that parameter. The code would look similar to this (I didn't actually run this, but it should be close): ``` [[NSBundle mainBundle] localizedStringForKey:(key) value:[[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:@"KYLocalizable"] table:nil] ``` At that point, the string in *Localizable.strings* will be used if found. Otherwise, the value in KYLocalizable.strings will be used. If it isn't found either, then a blank string will be returned (since that is what is specified in the nested **value** parameter). However, one inefficiency of this approach is that your application will actually attempt the lookup in KYLocalizable.strings first on every attempt (so that this result can subsequently be passed in as the **value** parameter when doing the outer lookup to *Localizable.strings*). If you actually want to check *Localized.strings* first, and then *only* do a second lookup if the string isn't found, I think you'd need to create a method with that logic in it (for example, add a method in a category on NSBundle).
I wrote this handy extension for localized strings, so you can just use the `localized()` function to get the localized string(you can also pass arguments) and the `isLocalized` computed property to check whether the string is localized or not: ``` extension String { var isLocalized: Bool { return localized() != self } func localized(parameter: CVarArg? = nil) -> String { if let parameter = parameter { return String(format: NSLocalizedString(self, comment: ""), parameter) } else { return NSLocalizedString(self, comment: "") } } func localized(parameter0: CVarArg, parameter1: CVarArg) -> String { return String(format: NSLocalizedString(self, comment: ""), parameter0, parameter1) } } ```
59,763
I'm struggling with figuring out a way to describe subtle movements in a scene that wouldn't normally be picked up on if not shown. For example: > > A character is being put in a prison cell and another > character slips them a key or a small pin behind their back. > > > Or: > > Like in the movie Gladiator, when Maximus kneels before Commodus in > the Colosseum, he picks up a broken arrowhead and conceals it behind his hand and forearm. > > > How does one describe a simple, subtle action/movement that would be unknown had it not been focused on or shown at all? Or would I just not describe that and then jump straight into what happens next? Would I just jump right into the character "fumbling to get the pin in the key hole while the guards are distracted"?
2021/12/12
[ "https://writers.stackexchange.com/questions/59763", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/49129/" ]
I think you just reveal it to the audience (reader or viewer). I think you have to, or you will create a deus ex machina; the audience will say "WTF? How did he get an arrowhead?!?" In a movie script, this would be Action description; no dialogue is spoken. (In fact in movies visually passed information without any dialogue is often preferred.) In a novel, it is a narrator's job, and the time restrictions of a movie do not apply: > > The second cop cuffed Darius, his hands behind his back, and leaned in > to speak in his ear. > > > "I don't why we even bother with your kind. Fucking traitors." > > > Simultaneously, Darius felt the cop press something cold into his palm. > Metal. A key. He closed his fist over it. > > > Darius turned his head toward the cop. "Fuck you!" > > > The cop slapped him in the back of the head. "Load 'im up!" > > >
Go Bold or Go Home or Be Chill Little Fonzies --------------------------------------------- The examples you cite from movies take great pains to ensure the audience knows what action the character. It's only implied to be subtle from the in-world characters sharing the stage with Maximus. From the storytelling viewpoint, do the same thing in your writing that the filmmakers did and show the moment clearly. How much you weight it depends on the consequences of that action. For instance, if it is a thing of no great matter. Then describe it an action beat. "John's fingers brushed his wallet." This might suggest a character is wary of pick pockets or is speculating about making a purchase. A few sentences later, resolve whatever it is that caused the action. This is the kind of thing to do when you've decided in this scenario, it's not truly important, and that a skimming reader might miss the action beat, and it still works. On the other end of the scale, you decided it is really important. It might start as an action beat or it might get is own first sentence of a paragraph, or it might get setup and described in narrative action. "Max saw Empii walking towards him. Kneeling to the sands, making his obeisance, his fingers dug for a broken eclair. Its creamy goodness, filled him with joy, knowing Empii's allergies were about to be his death." But it gets the action, then the character reacts emotionally to that action, Bells and whistles telling the reader this is important, because you don't want a skimming reader to miss it.
59,763
I'm struggling with figuring out a way to describe subtle movements in a scene that wouldn't normally be picked up on if not shown. For example: > > A character is being put in a prison cell and another > character slips them a key or a small pin behind their back. > > > Or: > > Like in the movie Gladiator, when Maximus kneels before Commodus in > the Colosseum, he picks up a broken arrowhead and conceals it behind his hand and forearm. > > > How does one describe a simple, subtle action/movement that would be unknown had it not been focused on or shown at all? Or would I just not describe that and then jump straight into what happens next? Would I just jump right into the character "fumbling to get the pin in the key hole while the guards are distracted"?
2021/12/12
[ "https://writers.stackexchange.com/questions/59763", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/49129/" ]
I think you just reveal it to the audience (reader or viewer). I think you have to, or you will create a deus ex machina; the audience will say "WTF? How did he get an arrowhead?!?" In a movie script, this would be Action description; no dialogue is spoken. (In fact in movies visually passed information without any dialogue is often preferred.) In a novel, it is a narrator's job, and the time restrictions of a movie do not apply: > > The second cop cuffed Darius, his hands behind his back, and leaned in > to speak in his ear. > > > "I don't why we even bother with your kind. Fucking traitors." > > > Simultaneously, Darius felt the cop press something cold into his palm. > Metal. A key. He closed his fist over it. > > > Darius turned his head toward the cop. "Fuck you!" > > > The cop slapped him in the back of the head. "Load 'im up!" > > >
**Don't go for the obvious.** You want to describe a subtle, but highly significant action, don't describe the action. Describe the effects. Your about-to-be-imprisoned character might feel cold metal against their palm which quickly closes around the object, releasing a surge of hope. They look down, wary of revealing anything that might result in the guards finding out. In the Gladiator scene, rather than focusing on the positive action, you could focus on nobody noticing it, and spend more time describing what other people's attention was focused on, building tension that way.
122,754
I understand that for low cross-section events a very high luminosity is necessary in order to obtain enough data to produce meaningful statistics. That is why the [LHC](http://en.wikipedia.org/wiki/Large_Hadron_Collider) was built. But which are these event which we are interested in? What are the events which would hint at new physics or would confirm theoretical models?
2014/07/02
[ "https://physics.stackexchange.com/questions/122754", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/52636/" ]
The history of high energy physics is in the words "high energy" . There are two ways to get it, building higher and higher energy accelerators or studying cosmic rays, [which last has answers in another question.](https://physics.stackexchange.com/questions/33565/why-not-using-cosmic-rays-to-study-hep-since-they-are-way-more-energetic-than-l/33574#33574) Accelerators are of two types, those creating beams of particles that fall on fixed targets, and colliders, having two beams collide. All studies have yielded the enormous amount of data that one can find in the [particle data book](http://www.google.gr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB8QFjAA&url=http%3A%2F%2Fpdg.lbl.gov%2F&ei=Ghq0U5TqBYHt0gWyw4GwCg&usg=AFQjCNEQ1HoQeOSIK265C4A0V0gwlcYhIg&sig2=cHjXvAQlN0zv7NF4V0U_ng&bvm=bv.70138588,d.d2k), a plethora of resonances and particles that are encapsulated the [Standard Model](http://en.wikipedia.org/wiki/Standard_Model) of particle physics. Colliders provide higher center of mass energies and have been for some time the center of studies for the behavior of higher and higher energies at scattering. The reason is that the standard model fits well low energy data but also predicts data for higher energies, as for example the existence of the Higgs. Also the SM is a gauge that will show if something unusual is happening at higher energies like manifestation of supersymmetric particles etc. by checking crossections and branching ratios against SM calculations . Colliders come into two physics types and two geometry types: hadronic, i.e. proton antiproton colliders or proton proton colliders, which is scattering a bag of quarks and gluons (proton) against another bag of antiquarks and gluons (antiproton) or also quarks and gluons (proton), and leptonic, scattering electrons on positrons and watching the fall out. They can be linear one off beam collisions, or circular colliders the beam increasing in energy by a lot of rotations around the ring. Leptonic collisions are much more accurate experimentally and theoretically, as the vertices in the Feynman diagrams are simple and computable with fewer assumptions than for hadronic ones. I have heard that Feynman defended leptonic experiments by saying" if you want to study the interior of a watch you do not throw one watch against another and study the wheels coming out. You take a screw driver ( in this case it was neutrino scattering on a target, I think but it holds for all leptonic collisions). The one of the drawbacks of leptonic circular colliders is also their advantage: the known fixed energy at center of mass can explore systematically a phase space with great accuracy and less modeling but the spread of energies is limited. It is also hard to accelerate electrons and positrons in circular colliders to high enough energies due to synchrotron radiation that degrades the energies of the beams. The drawback of the hadron colliders is that a lot of modelling has to enter since it is a scatter of many on many elementary particles but because of the high luminosity achievable they are great for new discoveries. The Z and W were found at a [proton antiproton collider at CERN](http://en.wikipedia.org/wiki/Super_Proton_Synchrotron) and then were explored in great detail in the leptonic collider [LEP,](http://en.wikipedia.org/wiki/LEP) the results of which nailed the parameters of the SM. Already there are proposals for a higher energy [leptonic collider](http://en.wikipedia.org/wiki/LEP) to sit on the Higgs and study with accuracy its branching ratios etc. As well there are plans for an [international linear collider](https://www.linearcollider.org/) at high energies after the LHC gives all the hints it can for where to look for new physics. Hadronic colliders are discovery machines. Leptonic are for nailing down accurately the parameters of the theoretical models.
As pfnuessel said in his comment: The first thing to look at was the Higgs - there were hints from LEP and Tevatron, but no evidence, so the LHC was designed that the (SM-)Higgs has to be seen, if it exists. And for everything beyond the Higgs - we don't know! There are various theories, e.g. the different flavors of super-symmetry and others, but they all have different predictions. If any of these theories is right there must be something - havier SUSY-partners of the standard model particles for example. But as there are many different theories it's not a very targeted search, its more a scan over a broad energy range not reachable in pre-LHC-times - we'll see what the experiemnt-collaborations will stumble upon, and which theory will be best to describe the results...
58,054,080
I have two different custom TableView Cells. That said, when the first cell type is returned, I want the other returned immediately after. Technically, the below code is what I want to occur: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath]; UniversalAlertTableViewCell *cellUni = (UniversalAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifierUni forIndexPath:indexPath]; return cell; return cellUni; } ``` However, as we know, code stops executing after the first return cell. How can I accomplish this?
2019/09/22
[ "https://Stackoverflow.com/questions/58054080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3030060/" ]
You can only return one specific type at a time. Use the `indexPath` parameter to decide which one to return. The following code is a rough idea of what you need. It's up to you to adapt the `if` statement based on your actual needs. ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0) { ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath]; // configure cell based on data from your data model for this indexPath return cell; } else { UniversalAlertTableViewCell *cell = (UniversalAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifierUni forIndexPath:indexPath]; // configure cell based on data from your data model for this indexPath return cell; } } ```
Your question is very interesting. First clarify your needs. I guess your demand is probably like this, and once the layout is displayed, switch to another layout. Let me talk about my habit of using tables. I am used to using data to control display and animation behavior. For your needs, I can use two data sources, corresponding to two kinds of cells. After one data source is displayed, immediately switch to another data source, and finally refresh the table. The code is probably like this, you need a data source array `models`, and then each `cell` corresponds to a data source. ``` @property (strong, nonatomic) NSArray *models; ``` ``` - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. ChatModel *model = ChatModel.new; self.models = @[model]; [self.tableView reloadData]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ UniversalAlertModel *universalModel = UniversalAlertModel.new; self.models = @[universalModel]; [self.tableView reloadData]; }); } ``` ``` - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.models.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ id model = self.models[indexPath.row]; if ([model isMemberOfClass:ChatModel.class]) { ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath]; // Set UI display according to model return cell; }else if ([model isMemberOfClass:UniversalAlertModel.class]){ UniversalAlertTableViewCell *cellUni = (UniversalAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifierUni forIndexPath:indexPath]; // Set UI display according to model return cellUni; } } ```
58,054,080
I have two different custom TableView Cells. That said, when the first cell type is returned, I want the other returned immediately after. Technically, the below code is what I want to occur: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath]; UniversalAlertTableViewCell *cellUni = (UniversalAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifierUni forIndexPath:indexPath]; return cell; return cellUni; } ``` However, as we know, code stops executing after the first return cell. How can I accomplish this?
2019/09/22
[ "https://Stackoverflow.com/questions/58054080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3030060/" ]
You can only return one specific type at a time. Use the `indexPath` parameter to decide which one to return. The following code is a rough idea of what you need. It's up to you to adapt the `if` statement based on your actual needs. ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0) { ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath]; // configure cell based on data from your data model for this indexPath return cell; } else { UniversalAlertTableViewCell *cell = (UniversalAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifierUni forIndexPath:indexPath]; // configure cell based on data from your data model for this indexPath return cell; } } ```
You cannot return two custom cells at the same time. It is not possible, because the delegate only runs one time per row. You can return a different cell on a different row or section.
21,590,875
We have 2 queries on an SSRS report . One query returns a single number that is a total record count. The other query returns a single column that we'd like to divide by the total returned in the first query. So Query 1 DATASET (this will always return a single value) ``` TOTAL 100 ``` Query 2 DATASET (this will return a list of values we'd like to divide by q1 answer) ``` COL A 1 20 3 49 ``` What we want to show on the report ``` RATIO (A/Total) 1/100 20/100 3/100 49/100 ``` Not show how to marry these two datasets in a single ssrs tablix. The 100 is not an aggregate of any value in the table from set 2, its a totally different number so I don't know of a way to write a query to bring out these values ins a single dataset. Ideas? thanks,. MC
2014/02/05
[ "https://Stackoverflow.com/questions/21590875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2714083/" ]
If you don't want to combine your datasets, you can do the following to achieve your end result. For the dataset that returns a single value, you could create a report parameter (@MyParam) that is hidden and is populated by your dataset Query1. Your dataset for Query2 can remain as it was. Then you can use the following expression to populate a textbox in your report ``` =CString(Fields!ColA.value) &"/"& CString(Parameters!MyParam.value) ``` If that is put in a list or table, it will go through each value in ColA and produce your desired result.
Why not do one data set? Err...I assume you want to see 49/100 and not .49 with this answer ``` select q2.A + '/' + q1.value as 'output' from query2 q2, query1 q1 ``` It's a cross join and applies q1 values to all q2 (since q1 is just one value, this'll work)...query1 and query 2 can be replaced with whatever queries you want to have there...you'll need to provide the SQL for q1 and q2 if you want a more full answer
9,975,649
In windows phone I have installed adobe reader its very nice but I am not able to jump to particular page I need to start from the starting . Its very difficult if we are reading book please any one have any solution for that.
2012/04/02
[ "https://Stackoverflow.com/questions/9975649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1292348/" ]
(reposting my comment as an answer for your approval so this question can get marked as answered): There is not a good way to do this out of the box. Are you willing to look at using a third party app to accomplish this? Unfortunately I see it as your only option right now. Downside is that you cannot install an app to be used as the "default" PDF reader other than the one adobe provides. I would encourage you to reach out to the Adobe folks and ask for the feature you want to be included in the next release of the app.
Maybe you could try and ebook reader for windows phone 7: <http://www.mobiletechworld.com/2011/03/20/samsung-ebook-reader-for-windows-phone-7-hands-on-video-review/> If it isnt what youre looking for just google for ebook reader, cheers :)
9,975,649
In windows phone I have installed adobe reader its very nice but I am not able to jump to particular page I need to start from the starting . Its very difficult if we are reading book please any one have any solution for that.
2012/04/02
[ "https://Stackoverflow.com/questions/9975649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1292348/" ]
The latest adobe reader version released for the windows phone is working fine. We can go to particular pages also many advancement. SO the problem no more exist.
Maybe you could try and ebook reader for windows phone 7: <http://www.mobiletechworld.com/2011/03/20/samsung-ebook-reader-for-windows-phone-7-hands-on-video-review/> If it isnt what youre looking for just google for ebook reader, cheers :)
9,975,649
In windows phone I have installed adobe reader its very nice but I am not able to jump to particular page I need to start from the starting . Its very difficult if we are reading book please any one have any solution for that.
2012/04/02
[ "https://Stackoverflow.com/questions/9975649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1292348/" ]
(reposting my comment as an answer for your approval so this question can get marked as answered): There is not a good way to do this out of the box. Are you willing to look at using a third party app to accomplish this? Unfortunately I see it as your only option right now. Downside is that you cannot install an app to be used as the "default" PDF reader other than the one adobe provides. I would encourage you to reach out to the Adobe folks and ask for the feature you want to be included in the next release of the app.
The latest adobe reader version released for the windows phone is working fine. We can go to particular pages also many advancement. SO the problem no more exist.
2,356,965
My application includes a client, web tier (load balanced), application tier (load balanced), and database tier. The web tier exposes services to clients, and forwards calls onto the application tier. The application tier then executes queries against the database (using NHibernate) and returns the results. Data is mostly read, but writes occur fairly frequently, particularly as new data enters the system. Much more often than not, data is aggregated and those aggregations are returned to the client - not the original data. Typically, users will be interested in the aggregation of recent data - say, from the past week. Thus, to me it makes sense to introduce a cache that includes *all data* from the past 7 days. I cannot just cache entities as and when they are loaded because I need to aggregate over a *range* of entities, and that range is dictated by the client, along with other complications, such as filters. I need to know whether - for a given range of time - all data within that range is in the cache or not. In my ideal fantasy world, my services would not have to change at all: ``` public AggregationResults DoIt(DateTime starting, DateTime ending, Filter filter) { // execute HQL/criteria call and have it automatically use the cache where possible } ``` There would be a separate filtering layer that would hook into NHibernate and intelligently and transparently determine whether the HQL/criteria query could be executed against the cache or not, and would only go to the database if necessary. If all the data was in the cache, it would query the cached data itself, kind of like an in-memory database. However, on first inspection, NHibernate's second level cache mechanism does not seem appropriate for my needs. What I'd like to be able to do is: 1. Configure it to always have the last 7 days worth of data in the cache. eg. "For this table, cache all records where this field is between 7 days ago and now." 2. Have the ability to manually maintain the cache. As new data enters the system, it would be nice if I could just throw it straight into the cache rather than waiting until the cache is invalidated. Similarly, as data falls out of the time period, I'd like to be able to pull it from the cache. 3. Have NHibernate intelligently understand when it can serve a query directly from the cache rather than hitting the database at all. eg. If the user asks for an aggregate of data over the past 3 days, that aggregation should be calculated directly from the cache rather than touching the DB. Now, I'm pretty sure #3 is asking too much. Even if I *can* get the cache populated with all the data required, NHibernate has no idea how to efficiently query that data. It would literally have to loop over all entities in order to discriminate which are relevant to the query (which might be fine, to be honest). Also, it would require an implementation of NHibernate's query engine that executed against objects rather than a database. But I can dream, right? Assuming #3 is asking too much, I would require some logic in my services like this: ``` public AggregationResults DoIt(DateTime starting, DateTime ending, Filter filter) { if (CanBeServicedFromCache(starting, ending, filter)) { // execute some LINQ to object code or whatever to determine the aggregation results } else { // execute HQL/criteria call to determine the aggregation results } } ``` This isn't ideal because each service must be cache-aware, and must duplicate the aggregation logic: once for querying the database via NHibernate, and once for querying the cache. That said, it would be nice if I could *at least* store the relevant data in NHibernate's second level cache. Doing so would allow other services (that don't do aggregation) to transparently benefit from the cache. It would also ensure that I'm not doubling up on cached entities (once in the second level cache, and once in my own separate cache) if I ever decide the second level cache is required elsewhere in the system. I suspect if I can get a hold of the implementation of `ICache` at runtime, all I would need to do is call the `Put()` method to stick my data into the cache. But this might be treading on dangerous ground... Can anyone provide any insight as to whether any of my requirements can be met by NHibernate's second level cache mechanism? Or should I just roll my own solution and forgo NHibernate's second level cache altogether? Thanks PS. I've already considered a cube to do the aggregation calculations much more quickly, but that still leaves me with the database as the bottleneck. I may well use a cube in addition to the cache, but the lack of a cache is my primary concern right now.
2010/03/01
[ "https://Stackoverflow.com/questions/2356965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380/" ]
Define 2 cache regions "aggregation" and "aggregation.today" with a large expiry time. Use these for your aggregation queries for previous days and today respectively. In `DoIt()`, make 1 NH query per day in the requested range using cacheable queries. Combine the query results in C#. Prime the cache with a background process which calls `DoIt()` periodically with the date range that you need to be cached. The frequency of this process must be lower than the expiry time of the aggregation cache regions. When today's data changes, clear cache region "aggregation.today". If you want to reload this cache region quickly, either do so immediately or have another more frequent background process which calls `DoIt()` for today. When you have query caching enabled, NHibernate will pull the results from cache if possible. This is based on the query and parameters values.
When analyzing the NHibernate cache details i remember reading something that you should not relay on the cache being there, witch seems a good suggestion. Instead of trying to make your O/R Mapper cover your applications needs i think rolling your own data/cache management strategy might be more reasonable. Also the 7 days caching rule you talk about sounds like something business related, witch is something the O/R mapper should not know about. In conclusion make your app work without any caching at all, than use a profiler (or more - .net,sql,nhibernate profiler ) to see where the bottlenecks are and start improving the "red" parts by eventually adding caching or any other optimizations. PS: about caching in general - in my experience one caching point is fine, two caches is in the gray zone and you should have a strong reason for the separation and more than two is asking for trouble. hope it helps
2,356,965
My application includes a client, web tier (load balanced), application tier (load balanced), and database tier. The web tier exposes services to clients, and forwards calls onto the application tier. The application tier then executes queries against the database (using NHibernate) and returns the results. Data is mostly read, but writes occur fairly frequently, particularly as new data enters the system. Much more often than not, data is aggregated and those aggregations are returned to the client - not the original data. Typically, users will be interested in the aggregation of recent data - say, from the past week. Thus, to me it makes sense to introduce a cache that includes *all data* from the past 7 days. I cannot just cache entities as and when they are loaded because I need to aggregate over a *range* of entities, and that range is dictated by the client, along with other complications, such as filters. I need to know whether - for a given range of time - all data within that range is in the cache or not. In my ideal fantasy world, my services would not have to change at all: ``` public AggregationResults DoIt(DateTime starting, DateTime ending, Filter filter) { // execute HQL/criteria call and have it automatically use the cache where possible } ``` There would be a separate filtering layer that would hook into NHibernate and intelligently and transparently determine whether the HQL/criteria query could be executed against the cache or not, and would only go to the database if necessary. If all the data was in the cache, it would query the cached data itself, kind of like an in-memory database. However, on first inspection, NHibernate's second level cache mechanism does not seem appropriate for my needs. What I'd like to be able to do is: 1. Configure it to always have the last 7 days worth of data in the cache. eg. "For this table, cache all records where this field is between 7 days ago and now." 2. Have the ability to manually maintain the cache. As new data enters the system, it would be nice if I could just throw it straight into the cache rather than waiting until the cache is invalidated. Similarly, as data falls out of the time period, I'd like to be able to pull it from the cache. 3. Have NHibernate intelligently understand when it can serve a query directly from the cache rather than hitting the database at all. eg. If the user asks for an aggregate of data over the past 3 days, that aggregation should be calculated directly from the cache rather than touching the DB. Now, I'm pretty sure #3 is asking too much. Even if I *can* get the cache populated with all the data required, NHibernate has no idea how to efficiently query that data. It would literally have to loop over all entities in order to discriminate which are relevant to the query (which might be fine, to be honest). Also, it would require an implementation of NHibernate's query engine that executed against objects rather than a database. But I can dream, right? Assuming #3 is asking too much, I would require some logic in my services like this: ``` public AggregationResults DoIt(DateTime starting, DateTime ending, Filter filter) { if (CanBeServicedFromCache(starting, ending, filter)) { // execute some LINQ to object code or whatever to determine the aggregation results } else { // execute HQL/criteria call to determine the aggregation results } } ``` This isn't ideal because each service must be cache-aware, and must duplicate the aggregation logic: once for querying the database via NHibernate, and once for querying the cache. That said, it would be nice if I could *at least* store the relevant data in NHibernate's second level cache. Doing so would allow other services (that don't do aggregation) to transparently benefit from the cache. It would also ensure that I'm not doubling up on cached entities (once in the second level cache, and once in my own separate cache) if I ever decide the second level cache is required elsewhere in the system. I suspect if I can get a hold of the implementation of `ICache` at runtime, all I would need to do is call the `Put()` method to stick my data into the cache. But this might be treading on dangerous ground... Can anyone provide any insight as to whether any of my requirements can be met by NHibernate's second level cache mechanism? Or should I just roll my own solution and forgo NHibernate's second level cache altogether? Thanks PS. I've already considered a cube to do the aggregation calculations much more quickly, but that still leaves me with the database as the bottleneck. I may well use a cube in addition to the cache, but the lack of a cache is my primary concern right now.
2010/03/01
[ "https://Stackoverflow.com/questions/2356965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380/" ]
Stop using your transactional ( OLTP ) datasource for analytical ( OLAP ) queries and the problem goes away. When a domain significant event occurs (eg a new entity enters the system or is updated), fire an event ( a la domain events ). Wire up a handler for the event that takes the details of the created or updated entity and stores the data in a denormalised reporting store specifically designed to allow reporting of the aggregates you desire ( most likely push the data into a star schema ). Now your reporting is simply the querying of aggregates ( which may even be precalculated ) along predefined axes requiring nothing more than a simple select and a few joins. Querying can be carried out using something like L2SQL or even simple parameterised queries and datareaders. Performance gains should be significant as you can optimise the read side for fast lookups across many criteria while optimising the write side for fast lookups by id and reduced index load on write. Additional performance and scalability is also gained as once you have migrated to this approach, you can then physically separate your read and write stores such that you can run n read stores for every write store thereby allowing your solution to scale out to meet increased read demands while write demands increase at a lower rate.
Define 2 cache regions "aggregation" and "aggregation.today" with a large expiry time. Use these for your aggregation queries for previous days and today respectively. In `DoIt()`, make 1 NH query per day in the requested range using cacheable queries. Combine the query results in C#. Prime the cache with a background process which calls `DoIt()` periodically with the date range that you need to be cached. The frequency of this process must be lower than the expiry time of the aggregation cache regions. When today's data changes, clear cache region "aggregation.today". If you want to reload this cache region quickly, either do so immediately or have another more frequent background process which calls `DoIt()` for today. When you have query caching enabled, NHibernate will pull the results from cache if possible. This is based on the query and parameters values.
2,356,965
My application includes a client, web tier (load balanced), application tier (load balanced), and database tier. The web tier exposes services to clients, and forwards calls onto the application tier. The application tier then executes queries against the database (using NHibernate) and returns the results. Data is mostly read, but writes occur fairly frequently, particularly as new data enters the system. Much more often than not, data is aggregated and those aggregations are returned to the client - not the original data. Typically, users will be interested in the aggregation of recent data - say, from the past week. Thus, to me it makes sense to introduce a cache that includes *all data* from the past 7 days. I cannot just cache entities as and when they are loaded because I need to aggregate over a *range* of entities, and that range is dictated by the client, along with other complications, such as filters. I need to know whether - for a given range of time - all data within that range is in the cache or not. In my ideal fantasy world, my services would not have to change at all: ``` public AggregationResults DoIt(DateTime starting, DateTime ending, Filter filter) { // execute HQL/criteria call and have it automatically use the cache where possible } ``` There would be a separate filtering layer that would hook into NHibernate and intelligently and transparently determine whether the HQL/criteria query could be executed against the cache or not, and would only go to the database if necessary. If all the data was in the cache, it would query the cached data itself, kind of like an in-memory database. However, on first inspection, NHibernate's second level cache mechanism does not seem appropriate for my needs. What I'd like to be able to do is: 1. Configure it to always have the last 7 days worth of data in the cache. eg. "For this table, cache all records where this field is between 7 days ago and now." 2. Have the ability to manually maintain the cache. As new data enters the system, it would be nice if I could just throw it straight into the cache rather than waiting until the cache is invalidated. Similarly, as data falls out of the time period, I'd like to be able to pull it from the cache. 3. Have NHibernate intelligently understand when it can serve a query directly from the cache rather than hitting the database at all. eg. If the user asks for an aggregate of data over the past 3 days, that aggregation should be calculated directly from the cache rather than touching the DB. Now, I'm pretty sure #3 is asking too much. Even if I *can* get the cache populated with all the data required, NHibernate has no idea how to efficiently query that data. It would literally have to loop over all entities in order to discriminate which are relevant to the query (which might be fine, to be honest). Also, it would require an implementation of NHibernate's query engine that executed against objects rather than a database. But I can dream, right? Assuming #3 is asking too much, I would require some logic in my services like this: ``` public AggregationResults DoIt(DateTime starting, DateTime ending, Filter filter) { if (CanBeServicedFromCache(starting, ending, filter)) { // execute some LINQ to object code or whatever to determine the aggregation results } else { // execute HQL/criteria call to determine the aggregation results } } ``` This isn't ideal because each service must be cache-aware, and must duplicate the aggregation logic: once for querying the database via NHibernate, and once for querying the cache. That said, it would be nice if I could *at least* store the relevant data in NHibernate's second level cache. Doing so would allow other services (that don't do aggregation) to transparently benefit from the cache. It would also ensure that I'm not doubling up on cached entities (once in the second level cache, and once in my own separate cache) if I ever decide the second level cache is required elsewhere in the system. I suspect if I can get a hold of the implementation of `ICache` at runtime, all I would need to do is call the `Put()` method to stick my data into the cache. But this might be treading on dangerous ground... Can anyone provide any insight as to whether any of my requirements can be met by NHibernate's second level cache mechanism? Or should I just roll my own solution and forgo NHibernate's second level cache altogether? Thanks PS. I've already considered a cube to do the aggregation calculations much more quickly, but that still leaves me with the database as the bottleneck. I may well use a cube in addition to the cache, but the lack of a cache is my primary concern right now.
2010/03/01
[ "https://Stackoverflow.com/questions/2356965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380/" ]
Stop using your transactional ( OLTP ) datasource for analytical ( OLAP ) queries and the problem goes away. When a domain significant event occurs (eg a new entity enters the system or is updated), fire an event ( a la domain events ). Wire up a handler for the event that takes the details of the created or updated entity and stores the data in a denormalised reporting store specifically designed to allow reporting of the aggregates you desire ( most likely push the data into a star schema ). Now your reporting is simply the querying of aggregates ( which may even be precalculated ) along predefined axes requiring nothing more than a simple select and a few joins. Querying can be carried out using something like L2SQL or even simple parameterised queries and datareaders. Performance gains should be significant as you can optimise the read side for fast lookups across many criteria while optimising the write side for fast lookups by id and reduced index load on write. Additional performance and scalability is also gained as once you have migrated to this approach, you can then physically separate your read and write stores such that you can run n read stores for every write store thereby allowing your solution to scale out to meet increased read demands while write demands increase at a lower rate.
When analyzing the NHibernate cache details i remember reading something that you should not relay on the cache being there, witch seems a good suggestion. Instead of trying to make your O/R Mapper cover your applications needs i think rolling your own data/cache management strategy might be more reasonable. Also the 7 days caching rule you talk about sounds like something business related, witch is something the O/R mapper should not know about. In conclusion make your app work without any caching at all, than use a profiler (or more - .net,sql,nhibernate profiler ) to see where the bottlenecks are and start improving the "red" parts by eventually adding caching or any other optimizations. PS: about caching in general - in my experience one caching point is fine, two caches is in the gray zone and you should have a strong reason for the separation and more than two is asking for trouble. hope it helps
65,796,518
First post here, so apologies if I break any etiquette. If something is missing please let me know so I can edit my post if needed. I'm currently working on an Excel macro, which enables me to import an interactive pdf form into excel and read data that was written in the form. Most of the script I have down by finding bits and pieces all over the internet, just one specific problem I wasn't able to solve so far. I have one text field in my pdf that I need to split in two and save the new values in two separate cells. Not a big problem so far, but the formatting may differ, depending on the entered data, so just cutting it of after e.g. a certain amount of characters won't work. Also the quality of the user input data may not be always the same (e.g. sometimes using a hyphen between both parts of the string, using an underscore or no seperator at all). Unfortunately I can't give that text field in the pdf form a strict formatting rule, as the formatting may differ. I also cannot just make to separate form fields in the pdf file for each part of the string. The ease of use is supposed to be on the pdf user's side, not on mine... Now, what does the data look like: ABC-1234 ABCD-0123 A1B-12A As you can see there is not a clear pattern. Please note that as said before the hyphen may not be there or be replaced by an underscore. I added it here to show you the separation of the two sub datasets (lets call them "Data A" for everything on the left side and "Data B" for everything on the right side of the hyphen). The good thing! I know all the potential values Data A may have. Data B is then just supposed to be stored separately in another cell. My first train of thought was to use InStr, but that may not be the most elegant solution. Data A may be one of around 130 different values, which is also frequently growing. My excel file also has a "helper sheet", in which I store some information for e.g. dropdown menus or deadlines etc. I could store a list of potential Data A candidates here as well. So what exactly do I need? A method to look at the string, compare it to a list of substrings (Data A, e.g. using a column in my excel sheet as data source) and store that match in Cell A1. Then take that value away from the original string so only Data B remains (I can strip away any hyphens or underscores at this point) and store this value in Cell A2. **Examples:** My import data may look like this: BER1234 Compare this to my list of match candidates, which includes "BER". Cell A1 = "BER" Cell A2 = (string minus the match) 1234 Import data: BERA59 Match in my candidate list: BERA A1 = "BERA" A2 = "59" Import data: P9CD-1009A Match: P9CD A1 = "P9CD" A2 = "1009A" etc. I may be able to do this with a giant block of if/else and many many InStr comparisons. Problem is, whenever I need to add a new match candidate I will have to go back to coding. It would make my life way easier if I could just e.g. add the value at the bottom of my candidate list and let the macro do it's magic. I would love to post a piece of code here of what I did so far, unfortunately I really have no idea where to start. I do not expect a ready-to-use piece of code that I can just slab in my macro with copy and paste. If I can't understand the code, I usually go for another solution. Otherwise I can't fix it myself if anything breaks and I don't really like that approach. Giving me pointers on which functions and variable types to look at would be greatly appreciated, though. Maybe I can then piece together what I think it should look like and ask for more help after that step. My experience level: Kind of beginner, but not total beginner. I have a basic understanding of how things work, but I'm not "fluent" in any programming languages. I know what I want to do and then usually try to get it to work by piecing together different solutions I find on the internet. So far so good, this one's a bit illusive for me, though. Any help is greatly appreciated. As mentioned before, if anything is missing or unclear, I'll gladly try to update this post. With the suggestions I somewhat got it to work with this: ``` Dim wb As Workbook: Set wb = ThisWorkbook Dim LastRow As Long Dim x As Integer Dim Remover As String Dim CatNo As String Dim Matches As Integer With Sheets("MenuData") LastRow = .Range("o" & .Rows.Count).End(xlUp).Row End With LastRow = LastRow - 4 Matches = 0 For x = 1 To LastRow If InStr(AlbumCode1, wb.Sheets("MenuData").Range("O" & x + 4).Value) <> 0 Then Matches = Matches + 1 Range(ColCatalog & (ImportCell.Row)).Value = wb.Sheets("MenuData").Range("O" & x + 4).Value Remover = wb.Sheets("MenuData").Range("O" & x + 4).Value CatNo = Replace(AlbumCode1, Remover, "") Range(ColCatNo & (ImportCell.Row)).Value = CatNo End If Next MsgBox Matches & (" Matches") ``` What I do is count the rows and substract 4, because my candidate list starts on row 4. Then do the loop for each x. I have declared all the Colxxx variables as Const at the very beginning of the macro. ImportCell is also declared somewhere else and working as intended for the rest of the data I import. My "Remover" is just set to the value of the match and then gets used to strip it away from the original string that is stored in AlbumCode1 (declared also at the beginning of the macro). Probably not strictly neccessary to do it this way. So far it works. My candidates may look like this, though: BER BERA If I import data like "BERA12342" I will get two matches (the MsgBox here is for checking what my code does and will be deleted later). As the candidate BERA comes after the candidate BER in my source list it's working fine, because the 2nd "match" just overwrites the first. If they were to be in a different order I would get a false match. Is there a way to only always get one match? Or will I have to make sure the source list is ordered in a certain way?
2021/01/19
[ "https://Stackoverflow.com/questions/65796518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15038077/" ]
In your view you can use `self.request` (because you are using class-based-views) instead of just `request`. ```py class BlogView(LoginRequiredMixin, DetailView): def get_context_data(self, **kwargs): ... user = self.request.user blog_post = get_object_or_404(BlogPost, slug=self.kwargs['slug']) ... ``` Surprisingly, this is only documented in one place (that I could find), <https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/#dynamic-filtering>: > > [...] when class-based views are called, various useful things are stored on `self`; as well as the request (`self.request`) this includes the positional (`self.args`) and name-based (`self.kwargs`) arguments captured according to the URLconf. > > >
you can do it in the html like ``` {{q_search_customers.count}} ```
3,606,538
We're thinking about switching technology for our future projects going from C++ to Java or C#. So naturally there's a big discussion going on right now what to choose. The problem is that none of us has industry experience with EMF or RCP, which would be quite nice to have if it fits our needs. so i wanted to ask you what you would prefer. our program is: * gui heavy (lots of dialogs, properties) * quite big models (serialized xml takes up about 15mb right now) * application should be integrated into our framework-application-center * data format (xml and binary) has to be the same as our current format * graphical editing is needed (creating, moving, connecting shapes + editing their properties) * lots of similar but tiny different objects in data model and the actual questions are: * is there an equivalent to EMF in C#? * is there an equivalent to RCP in C#? (e.g. commands to edit data model, gui frontend, ...) * is the gui editing in RCP as good and flexible as with windows forms or WPF? * how rigid/flexible is EMF? * we've got lot's of interdependencies between data models (some control others or allow different options on them) - how would you model these? * what of the options would you choose? thanks very much for any advice or opinions manni
2010/08/31
[ "https://Stackoverflow.com/questions/3606538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435608/" ]
As Java developer I can't say much about C#, but I can give you an overview about the Java side: There are sevaral good choices for RCP (the most prominent is of course Eclipse, but there are others as NetBeans). The learning curve is quite steep, but once you have the "hello world" running, it gets much easier. GUI-programming is no problem (you have several choices, and there exist a lot of free and commercial widgets), and you have several ways for dealing with XML. Generally for almost everything there is a (often free) lib. So if you like to have choices, Java is for you. On the other hand the C# language is technically ahead. Java7 could decrease the gap, but won't close it, that's sure. If you want to have both the advantages of the JVM (open, widespread, platform independent, plethora of libs...) and the advantages of a modern language, then you should have a look at Scala (you can mix Scala and Java code without problems). Scala is very innovative, mixing OO and functional features, but is still very "accessible" for programmers that are used to a C++/Java style syntax.
I'm not familiar at all with EMF and RCP, but from what I gathered in a quick glance, there are cetainly 'equivalents' in .Net. However I'm heavily biased so don't take my word for it. There are tools from generating data classes from xml/xsd and vice-versa (xsd.exe), graphical integrated modeling tools inside Visual Studio etc. And there is WPF, which I highly recommend for any project (not just graphical-heavy ones); the object model is easy to work with, it has declarative GUI design (XAML), and it makes diagramming-like tools (like what you described) a lot easier to make compared to older .Net technologies like WinForms. Especially look into MVVM (Model-View-ViewModel) for the most wide-spread pattern when working with WPF/Silverlight.
3,606,538
We're thinking about switching technology for our future projects going from C++ to Java or C#. So naturally there's a big discussion going on right now what to choose. The problem is that none of us has industry experience with EMF or RCP, which would be quite nice to have if it fits our needs. so i wanted to ask you what you would prefer. our program is: * gui heavy (lots of dialogs, properties) * quite big models (serialized xml takes up about 15mb right now) * application should be integrated into our framework-application-center * data format (xml and binary) has to be the same as our current format * graphical editing is needed (creating, moving, connecting shapes + editing their properties) * lots of similar but tiny different objects in data model and the actual questions are: * is there an equivalent to EMF in C#? * is there an equivalent to RCP in C#? (e.g. commands to edit data model, gui frontend, ...) * is the gui editing in RCP as good and flexible as with windows forms or WPF? * how rigid/flexible is EMF? * we've got lot's of interdependencies between data models (some control others or allow different options on them) - how would you model these? * what of the options would you choose? thanks very much for any advice or opinions manni
2010/08/31
[ "https://Stackoverflow.com/questions/3606538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435608/" ]
As Java developer I can't say much about C#, but I can give you an overview about the Java side: There are sevaral good choices for RCP (the most prominent is of course Eclipse, but there are others as NetBeans). The learning curve is quite steep, but once you have the "hello world" running, it gets much easier. GUI-programming is no problem (you have several choices, and there exist a lot of free and commercial widgets), and you have several ways for dealing with XML. Generally for almost everything there is a (often free) lib. So if you like to have choices, Java is for you. On the other hand the C# language is technically ahead. Java7 could decrease the gap, but won't close it, that's sure. If you want to have both the advantages of the JVM (open, widespread, platform independent, plethora of libs...) and the advantages of a modern language, then you should have a look at Scala (you can mix Scala and Java code without problems). Scala is very innovative, mixing OO and functional features, but is still very "accessible" for programmers that are used to a C++/Java style syntax.
For the bulk of the application I highly recommend Eclipse RCP + EMF (Eclipse RAP is also a plus as you can single source the application and get a web-based rich Ajax application "for free"). If you need to access native features you can always write it in another language or use JNI, or implement a form of IPC or using web services (SOAP) or REST-JSON or DBus or whatever favorite communication mechanism you like. I sometimes call Linux tools from my Java app to do the job (e.g. "ssh someserver" or "rsync") and feel comfortable doing it. I don't find it a pressing reason to get a "pure SSH library for Java" or "pure Rsync library for Java" when other tools do the job perfectly and I can get on with the next interesting task. BTW although I am biased towards Eclipse and JVM (Note: Java language isn't my favorite, I prefer Scala and Groovy, but with EMF it's easier to work in Java language), I have some experience with .NET. While there are some good things about .NET (one is that C#'s superior over Java language, but that's just about it, the second is Microsoft packs more functionality built-in than Sun/Oracle gives to Java[SE] API), there are some things you need to consider. First is cross-platformness. While there is Mono, overall .NET is hard to port. While you may not have a need for this, it may come in handy. Besides, Eclipse RCP not only it is "more cross-platform" but it is superior to the out of the box functionality provided by .NET Framework. (I know it isn't a fair comparison, it's fairer to compare it with Visual Studio Shell) Second is license, then tooling, and cost (makes three items). The whole Eclipse tooling is freely available. They are open source (you can fix any bug, contribute a patch). The license is open and you can rightly create commercial products on top of it. Third is functionality. There are so much functionality inside RCP itself, when combined with EMF, other Eclipse projects and the rest of Java ecosystem (not to mention the JVM languages) you've a lot of options for basic functionality. See also: <http://eclipsedriven.blogspot.com>
46,841,723
So this is a doubly linked list that is supposed to hold names, address, and phone numbe and print them out. It works for the first 3 nodes then suddenly crashes after the the phone number entry on the third node. something is wrong with the pointers I believe but I have tried everything I can think of. ``` #include <iostream> using namespace std; class node { private: string elem; node* next; node* prev; string firstName; string lastName; string address; string phoneNumber; friend class linkedList; }; //Linked list class linkedList { public: linkedList(); void addFrontNode(const string& e); void addNode(const string& e); void addNode2(node* nextloc, const string& e); void addNode3(node* nextloc, const string& e); void addNode4(node* nextloc, const string& e); void print(); void search(); node* nextloc; private: node* head; node* tail; }; void linkedList::addFrontNode(const string &e) { node* v = new node; string firstNameEntry; string lastNameEntry; string addressEntry; string phoneNumberEntry; cout << "Enter first name: "; cin >> firstNameEntry; cout << "Enter last name: "; cin >> lastNameEntry; cout << "Enter the address "; cin.ignore(); getline(cin, addressEntry); cout << "Enter a phone number "; cin >> phoneNumberEntry; v->elem = firstNameEntry; v->lastName = lastNameEntry; v->address = addressEntry; v->phoneNumber = phoneNumberEntry; v->next = head; head = v; } void linkedList::addNode(const string &e) { node* v = new node; string firstNameEntry; string lastNameEntry; string addressEntry; string phoneNumberEntry; cout << "Enter first name: "; cin >> firstNameEntry; cout << "Enter last name: "; cin >> lastNameEntry; cout << "Enter the address "; cin.ignore(); getline(cin, addressEntry); cout << "Enter a phone number "; cin >> phoneNumberEntry; v->elem = firstNameEntry; v->lastName = lastNameEntry; v->address = addressEntry; v->phoneNumber = phoneNumberEntry; v->next = tail; tail = v; tail->next = NULL; } void linkedList::addNode2(node* nextloc, const string &e) { node* v = new node; string firstNameEntry; string lastNameEntry; string addressEntry; string phoneNumberEntry; cout << "Enter first name: "; cin >> firstNameEntry; cout << "Enter last name: "; cin >> lastNameEntry; cout << "Enter the address "; cin.ignore(); getline(cin, addressEntry); cout << "Enter a phone number "; cin >> phoneNumberEntry; v->elem = firstNameEntry; v->lastName = lastNameEntry; v->address = addressEntry; v->phoneNumber = phoneNumberEntry; nextloc = head -> next; v->next = nextloc; v->next = nextloc; v->prev = nextloc->prev; nextloc->prev = v; } void linkedList::addNode3(node* nextloc, const string &e) { node* v = new node; string firstNameEntry; string lastNameEntry; string addressEntry; string phoneNumberEntry; cout << "Enter first name: "; cin >> firstNameEntry; cout << " Enter last name: "; cin >> lastNameEntry; cout << " Enter the address "; cin.ignore(); getline(cin, addressEntry); cout << " Enter a phone number "; cin >> phoneNumberEntry; v->elem = firstNameEntry; v->lastName = lastNameEntry; v->address = addressEntry; v->phoneNumber = phoneNumberEntry; v->next = nextloc; v->prev = nextloc->prev; nextloc->prev = v; } void linkedList::addNode4(node* nextloc, const string &e) { node* v = new node; string firstNameEntry; string lastNameEntry; string addressEntry; string phoneNumberEntry; cout << "Enter first name: "; cin >> firstNameEntry; cout << " Enter last name: "; cin >> lastNameEntry; cout << " Enter the address "; cin.ignore(); getline(cin, addressEntry); cout << " Enter a phone number "; cin >> phoneNumberEntry; v->elem = firstNameEntry; v->lastName = lastNameEntry; v->address = addressEntry; v->phoneNumber = phoneNumberEntry; v->next = nextloc; v->prev = nextloc->prev; nextloc->prev->next = v; nextloc->prev = v; } linkedList::linkedList() :head(NULL) {} void linkedList::print() { node* v = new node; v = head; while (v != NULL) { cout << v->elem << " "; cout << v->lastName << " "; cout << v->address << " "; cout << v->phoneNumber; v = v->next; } } void linkedList::search() { node* v = new node; v = tail; string lastNameSearch; cout << "Enter a last name to search "; cin >> lastNameSearch; while (v != NULL) { if (v->lastName == lastNameSearch) { cout << v->elem; cout << v->address; cout << v->phoneNumber; } v = v->prev; } } int main() { string node1; string node2; string node3; string node31; string node4; string node5; linkedList list; list.addFrontNode(node1); list.addNode(node2); list.addNode2(list.nextloc, node3); list.addNode3(list.nextloc, node4); list.addNode4(list.nextloc, node5); list.print(); return 0; } ```
2017/10/20
[ "https://Stackoverflow.com/questions/46841723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8692871/" ]
There are several issues. 1. If you use `addFrontNode()` to add first node, you must set your `tail`. Change this: ``` v->next = head; head = v; ``` To this: ``` v->next = NULL; head = v; tail = v; ``` 2. Your function `addNode()` doesn't add to list correctly, try calling `print` and you will see, no node is added by this function. Change this: ``` v->next = tail; tail = v; tail->next = NULL; ``` To this: ``` tail->next = v; v->next = NULL; tail = v; ``` 3. In `main()` just use `addFrontNode()` to add first and then use `addNode()` to add all others. After this your code worked as expected. 4. Didn't understand meaning of variable `nextloc`, might be the source of problems. Overall recommendation: create one function to add node
The code is indeed in need of re-write, but I don't want to repeat recommendations from the first answer. I however, believe that the question was about the reasons of the crash. It's because while copy-pasting the code, you added 2 extra lines to your addNode2: ``` void linkedList::addNode2(node* nextloc, const string &e) { ... nextloc = head -> next; v->next = nextloc; ... } ``` [Comment out at least first of them](https://repl.it/Mw5p/0) and it won't crash any more (but this wouldn't make it better, really).
273,816
This is an example in the textbook. > > To prove: for any real number\*\* $a\_1, a\_2, \cdots, a\_n, b\_1, b\_2, \cdots b\_n$, linear dependence of the two vectors $\left(a\_1, a\_2, \cdots, a\_n\right)$ and $\left(b\_1, b\_2, \cdots, b\_n\right)$ is a necessary and sufficient condition for the equality: > > > $\left(a\_1^2+a\_2^2+\cdots+a\_n^2\right)\left(b\_1^2+b\_2^2+\cdots+b\_n^2\right)=\left(a\_1 b\_1+a\_2 b\_2+\cdots+a\_n b\_n\right)^2$ > > > I take a three-dimensional vector as an example to prove its necessity: ``` Clear["Global`*"]; listA = Table[a[i], {i, 1, 3}]; listB = m*listA; Refine[Reduce[ Sum[a[i]^2, {i, 1, 3}]*Sum[(m*a[j])^2, {j, 1, 3}] == Sum[a[k]*m*a[k], {k, 1, 3}]^2], m ∈ Reals && a[1] ∈ Reals && a[2] ∈ Reals && a[3] ∈ Reals] ``` > > True > > > But I cannot prove its sufficiency: ``` Clear["Global`*"]; listA = Table[a[i], {i, 1, 3}]; listB = Table[b[i], {i, 1, 3}]; sol = Solve[ Sum[a[i]^2, {i, 1, 3}]*Sum[b[j]^2, {j, 1, 3}] == Sum[a[k]*b[k], {k, 1, 3}]^2, listA, Reals][[1]] ResourceFunction["LinearlyIndependent"][{listA, listB}] /. sol ``` > > $\left\{\mathrm{a}[2] \rightarrow \frac{\mathrm{a}[1] \times \mathrm{b}[2]}{\mathrm{b}[1]}, \mathrm{a}[3] \rightarrow \frac{\mathrm{a}[1] \times \mathrm{b}[1] \times \mathrm{b}[3]+\frac{a[1] b[2]^2 \mathrm{~b}[3]}{\mathrm{b}[1]}}{\mathrm{b}[1]^2+\mathrm{b}[2]^2}\right\}$ > > > True if condition... > > > `ResourceFunction["LinearlyIndependent"][{listA, listB}] /. sol` should give `False` to prove that `listA` and `listB` are linearly dependent. How can I modify this code?
2022/09/22
[ "https://mathematica.stackexchange.com/questions/273816", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/69835/" ]
I use `l`, `m`, `r` for the left, middle, right robots respectively. Each can take the values $-1,0,1$ with the following interpretation: ``` truthteller[x_]:=(x==1); joker[x_]:=(x==0); liar[x_]:=(x==-1); ``` Using ``` claim[who_,what_]:=And[Implies[truthteller[who],what], Implies[liar[who],Not[what]]]; ``` the answers of the three robots are: ``` claims=And[ claim[l,truthteller[m]], claim[m,joker[m]], claim[r,liar[m]] ]; ``` Our general assumptions are ``` assumptions=And[l!=m!=r, (* no two robots are of same kind *) l*(l^2-1)==0,m*(m^2-1)==0,r*(r^2-1)==0 (* only -1,0,1 *) ]; ``` We solve using: ``` Reduce[And[claims,assumptions],{l,m,r}] (* l==0&&m==-1&&r==1 *) ``` From left to right: joker, liar, truthteller.
Thanks for the solution from user293787. It is very helpful to me. After a lot of effort, I also worked out a way myself to solve this. I define l, m, r as Roberts at left, middle, and right. t as truth-teller, i as liar, and h as hesitater. So, for example, "lt" means the proposition that "left Robert is a truth-teller", "mi" means the proposition that "middle Robert is a liar" (1) l, m, r each take one role: ``` a = (lt \[And] mh \[And] ri) \[Or] (lt \[And] mi \[And] rh) \[Or] (lh \[And] mt \[And] ri) \[Or] (li \[And] mt \[And] rh) \[Or] ( li \[And] mh \[And] rt) \[Or] (lh \[And] mi \[And] rt); ``` (2) the answers from three roberts: ``` b = lt \[Implies] mt; c = mt \[Implies] mh; d = rt \[Implies] mi; ``` (3) l, m, r each can be only one of the role (no dual roles): ``` e = (lt \[And] \[Not] li \[And] \[Not] lh) \[Or] (\[Not] lt \[And] li \[And] \[Not] lh) \[Or] (\[Not] lt \[And] \[Not] li \[And] lh); f = (mt \[And] \[Not] mi \[And] \[Not] mh) \[Or] (\[Not] mt \[And] mi \[And] \[Not] mh) \[Or] (\[Not] mt \[And] \[Not] mi \[And] mh); g = (rt \[And] \[Not] ri \[And] \[Not] rh) \[Or] (\[Not] rt \[And] ri \[And] \[Not] rh) \[Or] (\[Not] rt \[And] \[Not] ri \[And] rh); ``` (4) Use **BooleanConvert** ``` a && b && c && d && e && f && g // BooleanConvert ``` or **SatisfiabilityInstances** ``` SatisfiabilityInstances[ a && b && c && d && e && f && g, {lt, li, lh, mt, mi, mh, rt, ri, rh}] ``` [![enter image description here](https://i.stack.imgur.com/Eu7y3.png)](https://i.stack.imgur.com/Eu7y3.png) To sum up, with **BooleanConvert** or **SatisifiabilityInstances** or **BooleanTable**, it seems every logic problem like this can be solved.
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
[C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 99 bytes ========================================================= * Saved a byte thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184). * Saved a byte. ```c s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));} ``` [Try it online!](https://tio.run/##FctLCgIxDADQuwwIyaTFxA@MZMa7lILahR@auBr06tVuH7wcrzm3ZsE1QQkV18uzgi9fViKfq77ebjAMiN1tYbW5dMy3VOEwETiBnYWj4wjCo9EpgtE/RxHc7hA3woj6afdUHoBrAjkG2Xf5AQ "C (gcc) – Try It Online")
[Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 17 bytes ===================================================================== ``` Eη⭆θ﹪⌊⟦ι÷⁺⁻ιλχ²⟧χ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUAjQ0chuATISwdxCnUUfPNTSnPyNXwz8zJzS3M1ojN1FDzzSlwyyzJTUjUCckqLQVJAEiieo6mjYGgAJIw0YyFMELD@/z/a0BTINY79r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` η Height E Map over implicit range θ Width ⭆ Map over implicit range and join ⁻ιλ Subtract column from row ⁺ χ Add 10 ÷ ² Integer divide by 2 ι Current row ⌊⟦ ⟧ Take the minimum ﹪ χ Modulo by 10 Implicitly print each row on its own line ``` Edit: Saved 3 bytes by switching to @dzaima's algorithm.
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
[C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 99 bytes ========================================================= * Saved a byte thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184). * Saved a byte. ```c s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));} ``` [Try it online!](https://tio.run/##FctLCgIxDADQuwwIyaTFxA@MZMa7lILahR@auBr06tVuH7wcrzm3ZsE1QQkV18uzgi9fViKfq77ebjAMiN1tYbW5dMy3VOEwETiBnYWj4wjCo9EpgtE/RxHc7hA3woj6afdUHoBrAjkG2Xf5AQ "C (gcc) – Try It Online")
[Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ========================================================== Uses a very similar approach to [pizzapants'](https://codegolf.stackexchange.com/a/168544/59487) and [Neil's](https://codegolf.stackexchange.com/a/168548/59487). Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). ``` p’Ḣ_/HḞ+ʋS<9Ɗ?€5s%⁵ ``` [Try it online!](https://tio.run/##y0rNyan8/7/gUcPMhzsWxet7PNwxT/tUd7CN5bEu@0dNa0yLVR81bv1/eLk@kOMOxFmPGuYc2gaCjxrm/v8fHW2oo6CgYBirw6UQbQRiGoOZIFEjAwjTQEfBEKLA0BjINI2NBSoDAA "Jelly – Try It Online") --- **The helper link** ``` _/HḞ+5 ``` This is a monadic link (the Jelly equivalent of a single argument function), that can be invoked from the next link using the quick `Ç`. It takes a list of two integers and does the following on it: ``` _/ ``` Reduce by subtraction. ``` HḞ+5%⁵ ``` Floor its halve to an integer and add 5, then take it modulo 10. **The main link** ``` p’ḢÇS<9Ɗ?€s ``` This is a dyadic link (the Jelly equivalent of a two-argument function), that can be invoked from the next link using the `ç` quick. It takes two integers \$x\$ and \$y\$ and performs the following: ``` p’ ``` Cartesian product of their ranges, and then subtract \$1\$ from each integer in that list. It is equivalent to \$([0, x)\cap \mathbb{Z}) \times ([0, y)\cap \mathbb{Z})\$. ``` S<9Ɗ?€ ``` And for each of the pair in the Cartesian product, if their sum is less than 9, then: ``` Ḣ ``` Retrieve the head of the pair (first element). Otherwise, ``` Ç ``` Call the helper link (explained above) on the pair. ``` s%⁵ ``` Finally, split the resulting list into chunks of length \$y\$ and take each mod 10.
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
[C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 99 bytes ========================================================= * Saved a byte thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184). * Saved a byte. ```c s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));} ``` [Try it online!](https://tio.run/##FctLCgIxDADQuwwIyaTFxA@MZMa7lILahR@auBr06tVuH7wcrzm3ZsE1QQkV18uzgi9fViKfq77ebjAMiN1tYbW5dMy3VOEwETiBnYWj4wjCo9EpgtE/RxHc7hA3woj6afdUHoBrAjkG2Xf5AQ "C (gcc) – Try It Online")
Canvas, 14 bytes ================ ``` [⁷{¹∔⁶+»¹m◂@]] ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXUyMDc3JXVGRjVCJUI5JXUyMjE0JXUyMDc2JXVGRjBCJUJCJUI5JXVGRjREJXUyNUMyJXVGRjIwJXVGRjNEJXVGRjNE,i=MTMlMEExNQ__,v=4) While making this I noticed in several places I had negative modulos in Canvas (here, it meant that `»` - floor div 2 - rounded towards 0). The previous 18 byte answer that worked without fixes doesn't work anymore (because I only save `main.js` between versions) but [TIO still has the old version](https://tio.run/##AUIAvf9jYW52YXP//@@8u@KBt@@9m8K54oiU4oG277yL77ya77yQ77yc77yNwrvCue@9jeKXgu@8oO@8ve@8vf//MTMKMTU) Explanation: ``` [ ] for 1..input ⁷{ ] for 1..2nd input ¹∔ subtract from this loop counter the outer loops one ⁶+ add 12 » divide by 2, rounded to -∞ ¹m minimum of that & the outer loops counter ◂@ in the string "0123456789", get the xth char, 1-indexed ```
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
[C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 99 bytes ========================================================= * Saved a byte thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184). * Saved a byte. ```c s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));} ``` [Try it online!](https://tio.run/##FctLCgIxDADQuwwIyaTFxA@MZMa7lILahR@auBr06tVuH7wcrzm3ZsE1QQkV18uzgi9fViKfq77ebjAMiN1tYbW5dMy3VOEwETiBnYWj4wjCo9EpgtE/RxHc7hA3woj6afdUHoBrAjkG2Xf5AQ "C (gcc) – Try It Online")
[Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ==================================================================================================================== ``` _@þ:2+6«"J$’%⁵ ``` A dyadic link taking \$w\$ on the left and \$h\$ on the right which yields a list of lists of digits. **[Try it online!](https://tio.run/##y0rNyan8/z/e4fA@KyNts0OrlbxUHjXMVH3UuPX///@Gpv8NjQE "Jelly – Try It Online")** Or see a (post-formatted) [test-suite](https://tio.run/##y0rNyan8/z/e4fA@KyNts0OrlbxUHjXMVH3UuPX/4eX6kSqPmtZkPWrcd2jboW3//0dHG@oYxupEG@sYAUkjAzDHEChmAKJNdQyNY2MB "Jelly – Try It Online"). ### How? ``` _@þ:2+6«"J$’%⁵ - Link: integer w, integer h þ - outer product using (i.e. [[f(i,j) for i in 1..w] for j in 1..h]): _@ - subtraction with swapped arguments (i.e. f(i,j): j-i) - e.g. the 4th row is [3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,...] :2 - integer divide by two (vectorises) - [1, 1, 0, 0,-1,-1,-2,-2,-3,-3,-4,-4,-5,-5,-6,...] +6 - add six (vectorises) - [7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0,...] $ - last two links as a monad: J - range of length -> [1,2,3,...,h] " - zip with: « - minimum (vectorises) - [4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 2, 1, 1, 0,...] ’ - decrement (vectorises) - [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0,-1,...] ⁵ - literal ten % - modulo (vectorises) - [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0, 9,...] ```
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
[C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 99 bytes ========================================================= * Saved a byte thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184). * Saved a byte. ```c s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));} ``` [Try it online!](https://tio.run/##FctLCgIxDADQuwwIyaTFxA@MZMa7lILahR@auBr06tVuH7wcrzm3ZsE1QQkV18uzgi9fViKfq77ebjAMiN1tYbW5dMy3VOEwETiBnYWj4wjCo9EpgtE/RxHc7hA3woj6afdUHoBrAjkG2Xf5AQ "C (gcc) – Try It Online")
[Kotlin](https://kotlinlang.org), 78 bytes ========================================== ``` {w:Int,h:Int->List(h){r->List(w){c->if(c<11-r)r%10 else(r+9*((c-9+r)/2))%10}}} ``` [Try it online!](https://tio.run/##3Vbbbtw2EH3nVzBGC0iJsruym8Q2kgDpBW2AACmSAEWR@oErUSsiEqmSVDZbw9/RD@qHpWeG2rWcC@C3AiV8EYdznzNDvnOxM/bj8q78wWsVdS0b52VsTZCVq7XcuK6RVau6TtuNPhdtjEM4Xy7pkM4WIarqnf4AFpwvKtcv/xx1iMbZsCwfnj74rhSvmaWWtdmYKCFgfKWCDkL8bN5rKwcXTMSXNDbqjfZBboWytWylG@MwRrmFL93Y2yCZLIR32yBdI6P@EKUKstah8mYNG2vdue1CiDetlo3xIUrwgroxkN6a2MqylKtQIEQtg64cFBJHOlrJko@MrxPFGqvlcbIbnHRW1m5rWZh/tQXTQT5unTwLC/nSSq2qlj1sddh7Am7ihYXGdXDT2A1rMRbhq0760ZIIfIJjI2eEUzZ5aylYiCG7UyrVMGiFdJHdaHodECjKp@fB3UKqmLynog8qRu3hpwZTJA9J4XvtF/J5I9XexxXSX1Wjn1xLbkrVQFaSCfiguq3aBcqHEK@oXlyaT9Km9s6qXlMh6Zvopu91bYDHbifV2hE2olwDCqE1DaE0usRrNi0OdqiMXsg3nKXtFGds1XWwJnxmZ0Bcxo1BdrqJvTvkxzRkbAsu62LKH6wpbFqKzgLAttKUBcSs0QLyJZ1sTWAvJ0ss18K968Rn1a7qOKXe9fJMrtEWpHqV3wBsWf7zd7kSQne6R6JCymaYQBPOhVhdL1Ee1koc71dZipNpYSO@S4s24gEv3oiHtNJGPMKaNuL09HS/EWdnh40Qv2i4YqgdUCG10Qk4aE5gpE7diHh69S5VdQ@mnjBZdSgEAm3Mh4lXCEBq50bkKlV08K4ekdpGb5HpqeeX3OxQZ5k3tG7s0IymH4CNyruBTSWQkNbFV9UmN25qVZZxX0j9wQTG@/V82ttaa5wCs7WuuQs@16PqOjDyZsJf6eSpVa5VMygqiqV1AUEyONJYSNOQcD0GnsvG0jjMygdFeZILQVzTiDzou4EOKt4cIUSYo4QIc6QQYY4WIswRQ4Q5ahhpM@Qw2mboYcTNEMSoW90kiNVNgihvEr6AOp6r1GcEuGsIojP2dUr4ejV2dMtIrJcpTRV0IOcbvncwNpTdUZWwM2g12evYunrBEj8Z7nclm7HrCEMbr3rpEsVWdMOlzqwqPUS17vQ0IvenBYOQLHodR59ujalcXrFyxt/gUWlCnonJ8u83xZTsAE0KGsMDwDIJ3RhfDcbylyWOf4RvXu1IakIcPL/WE2KYHX1BI@5sWytcg51zQ@uQRzAHRRMIXSDE69b5SKONXwm4yjDm3/A@3ezPGalUIwwDS@Mr2xYtMJueF9Sqe2ZoK4tSYOKdFMdimmlCHK@IeBPLjAmwg3/1301Bbr//XZvdXQqxXMoXql/XCgMPaAiBQE4VO7wAF@K98nKQT4j30Sl6CIX8eLk9f25j0dLf@09fAF5Zm1/66XObX1b3n5omqx6X5X2f@28Rnu6Czvy9s7tZVt0/u@fz5XGe4@Dq6uojVDOWao8@9Z86gP7CFWNspvwmnMtnhPPHryO6aPM0l5fU71DwSquan23QYJodY25raswKfkNqfjjElh8hNongFYtOppDxo713ePT86l2FPKTHw6Ar0xhdJ/ZaRcXK0BhDp5IJJG3suI@j38EZ6qX3eNsx3J/gWNUv0MVZfufOAlImZkfyKF/0apiYaWEQRIdUZvkV09CfGSlYBPOXlneeyON84k0BPEdqNqp75jcjvRh@2seRHTRKefSbd5gxduzXSCl6X03c4c5RfnAzuQ9HBzb4dnVRsOtvy4vExMOqs9nRH/aby4nlqpDTd3lxNSmjmmX8krNyJUcMuO6g6BApM6WL9DO@1UV@8J6NZsm3t1B68TYJHVj2XqX9FVUHuick0Gt8n5EC8woPB6CHKzfMqlvrRkF/kplPJ1JYqYj3fMagOMd9DCdo4u9DOWTle4COL@lCjoFm@qQ1LGZJJuUBOaYx/LLJpn9lIcu82BNPChS5OGRgomImzplKklnN9g@wP8lnFeA4ECybvE78rUp9@2Lfsty3L/gtSv5p0Wdl/2TDn@hGwR80OT7@Cw "Kotlin – Try It Online")
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
Python 3, ~~94~~ ~~93~~ ~~78~~ ~~77~~ 74 bytes ============================================== ``` lambda x,y:[[[(j-i+10)//2%10,j][j+i<9]for i in range(x)]for j in range(y)] ``` -1 byte from [dylnan](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407367_168544) -15 bytes by returning a list of lists instead of printing from [xnor](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544?noredirect=1#comment407382_168544) -1 byte by switching the order of the `(j-i+10)//2%10` and `j` parts of the `if`-`else` -3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407390_168544) by changing the `if`-`else` to a list. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqOjpaI0s3U9vQQFNf30jV0EAnKzY6SzvTxjI2Lb9IIVMhM0@hKDEvPVWjQhMskoUQqdSM/V9QlJlXoqGVpmFoqAM0Q6c4tcBWPSZPXZMLIgOjQSpMdQyNkVT8BwA "Python 3 – Try It Online")
[Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 17 bytes ===================================================================== ``` Eη⭆θ﹪⌊⟦ι÷⁺⁻ιλχ²⟧χ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUAjQ0chuATISwdxCnUUfPNTSnPyNXwz8zJzS3M1ojN1FDzzSlwyyzJTUjUCckqLQVJAEiieo6mjYGgAJIw0YyFMELD@/z/a0BTINY79r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` η Height E Map over implicit range θ Width ⭆ Map over implicit range and join ⁻ιλ Subtract column from row ⁺ χ Add 10 ÷ ² Integer divide by 2 ι Current row ⌊⟦ ⟧ Take the minimum ﹪ χ Modulo by 10 Implicitly print each row on its own line ``` Edit: Saved 3 bytes by switching to @dzaima's algorithm.
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
Python 3, ~~94~~ ~~93~~ ~~78~~ ~~77~~ 74 bytes ============================================== ``` lambda x,y:[[[(j-i+10)//2%10,j][j+i<9]for i in range(x)]for j in range(y)] ``` -1 byte from [dylnan](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407367_168544) -15 bytes by returning a list of lists instead of printing from [xnor](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544?noredirect=1#comment407382_168544) -1 byte by switching the order of the `(j-i+10)//2%10` and `j` parts of the `if`-`else` -3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407390_168544) by changing the `if`-`else` to a list. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqOjpaI0s3U9vQQFNf30jV0EAnKzY6SzvTxjI2Lb9IIVMhM0@hKDEvPVWjQhMskoUQqdSM/V9QlJlXoqGVpmFoqAM0Q6c4tcBWPSZPXZMLIgOjQSpMdQyNkVT8BwA "Python 3 – Try It Online")
[Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ========================================================== Uses a very similar approach to [pizzapants'](https://codegolf.stackexchange.com/a/168544/59487) and [Neil's](https://codegolf.stackexchange.com/a/168548/59487). Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). ``` p’Ḣ_/HḞ+ʋS<9Ɗ?€5s%⁵ ``` [Try it online!](https://tio.run/##y0rNyan8/7/gUcPMhzsWxet7PNwxT/tUd7CN5bEu@0dNa0yLVR81bv1/eLk@kOMOxFmPGuYc2gaCjxrm/v8fHW2oo6CgYBirw6UQbQRiGoOZIFEjAwjTQEfBEKLA0BjINI2NBSoDAA "Jelly – Try It Online") --- **The helper link** ``` _/HḞ+5 ``` This is a monadic link (the Jelly equivalent of a single argument function), that can be invoked from the next link using the quick `Ç`. It takes a list of two integers and does the following on it: ``` _/ ``` Reduce by subtraction. ``` HḞ+5%⁵ ``` Floor its halve to an integer and add 5, then take it modulo 10. **The main link** ``` p’ḢÇS<9Ɗ?€s ``` This is a dyadic link (the Jelly equivalent of a two-argument function), that can be invoked from the next link using the `ç` quick. It takes two integers \$x\$ and \$y\$ and performs the following: ``` p’ ``` Cartesian product of their ranges, and then subtract \$1\$ from each integer in that list. It is equivalent to \$([0, x)\cap \mathbb{Z}) \times ([0, y)\cap \mathbb{Z})\$. ``` S<9Ɗ?€ ``` And for each of the pair in the Cartesian product, if their sum is less than 9, then: ``` Ḣ ``` Retrieve the head of the pair (first element). Otherwise, ``` Ç ``` Call the helper link (explained above) on the pair. ``` s%⁵ ``` Finally, split the resulting list into chunks of length \$y\$ and take each mod 10.
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
Python 3, ~~94~~ ~~93~~ ~~78~~ ~~77~~ 74 bytes ============================================== ``` lambda x,y:[[[(j-i+10)//2%10,j][j+i<9]for i in range(x)]for j in range(y)] ``` -1 byte from [dylnan](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407367_168544) -15 bytes by returning a list of lists instead of printing from [xnor](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544?noredirect=1#comment407382_168544) -1 byte by switching the order of the `(j-i+10)//2%10` and `j` parts of the `if`-`else` -3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407390_168544) by changing the `if`-`else` to a list. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqOjpaI0s3U9vQQFNf30jV0EAnKzY6SzvTxjI2Lb9IIVMhM0@hKDEvPVWjQhMskoUQqdSM/V9QlJlXoqGVpmFoqAM0Q6c4tcBWPSZPXZMLIgOjQSpMdQyNkVT8BwA "Python 3 – Try It Online")
Canvas, 14 bytes ================ ``` [⁷{¹∔⁶+»¹m◂@]] ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXUyMDc3JXVGRjVCJUI5JXUyMjE0JXUyMDc2JXVGRjBCJUJCJUI5JXVGRjREJXUyNUMyJXVGRjIwJXVGRjNEJXVGRjNE,i=MTMlMEExNQ__,v=4) While making this I noticed in several places I had negative modulos in Canvas (here, it meant that `»` - floor div 2 - rounded towards 0). The previous 18 byte answer that worked without fixes doesn't work anymore (because I only save `main.js` between versions) but [TIO still has the old version](https://tio.run/##AUIAvf9jYW52YXP//@@8u@KBt@@9m8K54oiU4oG277yL77ya77yQ77yc77yNwrvCue@9jeKXgu@8oO@8ve@8vf//MTMKMTU) Explanation: ``` [ ] for 1..input ⁷{ ] for 1..2nd input ¹∔ subtract from this loop counter the outer loops one ⁶+ add 12 » divide by 2, rounded to -∞ ¹m minimum of that & the outer loops counter ◂@ in the string "0123456789", get the xth char, 1-indexed ```
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
Python 3, ~~94~~ ~~93~~ ~~78~~ ~~77~~ 74 bytes ============================================== ``` lambda x,y:[[[(j-i+10)//2%10,j][j+i<9]for i in range(x)]for j in range(y)] ``` -1 byte from [dylnan](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407367_168544) -15 bytes by returning a list of lists instead of printing from [xnor](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544?noredirect=1#comment407382_168544) -1 byte by switching the order of the `(j-i+10)//2%10` and `j` parts of the `if`-`else` -3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407390_168544) by changing the `if`-`else` to a list. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqOjpaI0s3U9vQQFNf30jV0EAnKzY6SzvTxjI2Lb9IIVMhM0@hKDEvPVWjQhMskoUQqdSM/V9QlJlXoqGVpmFoqAM0Q6c4tcBWPSZPXZMLIgOjQSpMdQyNkVT8BwA "Python 3 – Try It Online")
[Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ==================================================================================================================== ``` _@þ:2+6«"J$’%⁵ ``` A dyadic link taking \$w\$ on the left and \$h\$ on the right which yields a list of lists of digits. **[Try it online!](https://tio.run/##y0rNyan8/z/e4fA@KyNts0OrlbxUHjXMVH3UuPX///@Gpv8NjQE "Jelly – Try It Online")** Or see a (post-formatted) [test-suite](https://tio.run/##y0rNyan8/z/e4fA@KyNts0OrlbxUHjXMVH3UuPX/4eX6kSqPmtZkPWrcd2jboW3//0dHG@oYxupEG@sYAUkjAzDHEChmAKJNdQyNY2MB "Jelly – Try It Online"). ### How? ``` _@þ:2+6«"J$’%⁵ - Link: integer w, integer h þ - outer product using (i.e. [[f(i,j) for i in 1..w] for j in 1..h]): _@ - subtraction with swapped arguments (i.e. f(i,j): j-i) - e.g. the 4th row is [3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,...] :2 - integer divide by two (vectorises) - [1, 1, 0, 0,-1,-1,-2,-2,-3,-3,-4,-4,-5,-5,-6,...] +6 - add six (vectorises) - [7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0,...] $ - last two links as a monad: J - range of length -> [1,2,3,...,h] " - zip with: « - minimum (vectorises) - [4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 2, 1, 1, 0,...] ’ - decrement (vectorises) - [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0,-1,...] ⁵ - literal ten % - modulo (vectorises) - [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0, 9,...] ```
168,541
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below. The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s. Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0). The first \$11\times10\$ elements are as follows: ``` 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 ``` Here is an image with colored text to make the pattern more clear. [![fixed text](https://i.stack.imgur.com/sYcT1m.png)](https://i.stack.imgur.com/sYcT1m.png) If you need to produce fewer columns/rows then you should simply crop the above text. If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be ``` 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544 ``` Here is an image of this text with color: [![extended text](https://i.stack.imgur.com/BqDCUm.png)](https://i.stack.imgur.com/BqDCUm.png) ### Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * You can return a list of lines if you prefer. * You can return a 2D array of digits or list of lists of digits if you prefer. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed. Shortest code wins. ### Test cases Input is taken as \$(w,h)\$ for the test cases. ``` 1,1 0 ``` 3,2 000 111 20,1 00000000000998877665 11,10 00000000000 11111111110 22222222211 33333333221 44444443322 55555544332 66666554433 77776655443 88877665544 99887766554 15,13 000000000009988 111111111100998 222222222110099 333333332211009 444444433221100 555555443322110 666665544332211 777766554433221 888776655443322 998877665544332 099887766554433 009988776655443 100998877665544
2018/07/13
[ "https://codegolf.stackexchange.com/questions/168541", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/75553/" ]
Python 3, ~~94~~ ~~93~~ ~~78~~ ~~77~~ 74 bytes ============================================== ``` lambda x,y:[[[(j-i+10)//2%10,j][j+i<9]for i in range(x)]for j in range(y)] ``` -1 byte from [dylnan](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407367_168544) -15 bytes by returning a list of lists instead of printing from [xnor](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544?noredirect=1#comment407382_168544) -1 byte by switching the order of the `(j-i+10)//2%10` and `j` parts of the `if`-`else` -3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407390_168544) by changing the `if`-`else` to a list. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqOjpaI0s3U9vQQFNf30jV0EAnKzY6SzvTxjI2Lb9IIVMhM0@hKDEvPVWjQhMskoUQqdSM/V9QlJlXoqGVpmFoqAM0Q6c4tcBWPSZPXZMLIgOjQSpMdQyNkVT8BwA "Python 3 – Try It Online")
[Kotlin](https://kotlinlang.org), 78 bytes ========================================== ``` {w:Int,h:Int->List(h){r->List(w){c->if(c<11-r)r%10 else(r+9*((c-9+r)/2))%10}}} ``` [Try it online!](https://tio.run/##3Vbbbtw2EH3nVzBGC0iJsruym8Q2kgDpBW2AACmSAEWR@oErUSsiEqmSVDZbw9/RD@qHpWeG2rWcC@C3AiV8EYdznzNDvnOxM/bj8q78wWsVdS0b52VsTZCVq7XcuK6RVau6TtuNPhdtjEM4Xy7pkM4WIarqnf4AFpwvKtcv/xx1iMbZsCwfnj74rhSvmaWWtdmYKCFgfKWCDkL8bN5rKwcXTMSXNDbqjfZBboWytWylG@MwRrmFL93Y2yCZLIR32yBdI6P@EKUKstah8mYNG2vdue1CiDetlo3xIUrwgroxkN6a2MqylKtQIEQtg64cFBJHOlrJko@MrxPFGqvlcbIbnHRW1m5rWZh/tQXTQT5unTwLC/nSSq2qlj1sddh7Am7ihYXGdXDT2A1rMRbhq0760ZIIfIJjI2eEUzZ5aylYiCG7UyrVMGiFdJHdaHodECjKp@fB3UKqmLynog8qRu3hpwZTJA9J4XvtF/J5I9XexxXSX1Wjn1xLbkrVQFaSCfiguq3aBcqHEK@oXlyaT9Km9s6qXlMh6Zvopu91bYDHbifV2hE2olwDCqE1DaE0usRrNi0OdqiMXsg3nKXtFGds1XWwJnxmZ0Bcxo1BdrqJvTvkxzRkbAsu62LKH6wpbFqKzgLAttKUBcSs0QLyJZ1sTWAvJ0ss18K968Rn1a7qOKXe9fJMrtEWpHqV3wBsWf7zd7kSQne6R6JCymaYQBPOhVhdL1Ee1koc71dZipNpYSO@S4s24gEv3oiHtNJGPMKaNuL09HS/EWdnh40Qv2i4YqgdUCG10Qk4aE5gpE7diHh69S5VdQ@mnjBZdSgEAm3Mh4lXCEBq50bkKlV08K4ekdpGb5HpqeeX3OxQZ5k3tG7s0IymH4CNyruBTSWQkNbFV9UmN25qVZZxX0j9wQTG@/V82ttaa5wCs7WuuQs@16PqOjDyZsJf6eSpVa5VMygqiqV1AUEyONJYSNOQcD0GnsvG0jjMygdFeZILQVzTiDzou4EOKt4cIUSYo4QIc6QQYY4WIswRQ4Q5ahhpM@Qw2mboYcTNEMSoW90kiNVNgihvEr6AOp6r1GcEuGsIojP2dUr4ejV2dMtIrJcpTRV0IOcbvncwNpTdUZWwM2g12evYunrBEj8Z7nclm7HrCEMbr3rpEsVWdMOlzqwqPUS17vQ0IvenBYOQLHodR59ujalcXrFyxt/gUWlCnonJ8u83xZTsAE0KGsMDwDIJ3RhfDcbylyWOf4RvXu1IakIcPL/WE2KYHX1BI@5sWytcg51zQ@uQRzAHRRMIXSDE69b5SKONXwm4yjDm3/A@3ezPGalUIwwDS@Mr2xYtMJueF9Sqe2ZoK4tSYOKdFMdimmlCHK@IeBPLjAmwg3/1301Bbr//XZvdXQqxXMoXql/XCgMPaAiBQE4VO7wAF@K98nKQT4j30Sl6CIX8eLk9f25j0dLf@09fAF5Zm1/66XObX1b3n5omqx6X5X2f@28Rnu6Czvy9s7tZVt0/u@fz5XGe4@Dq6uojVDOWao8@9Z86gP7CFWNspvwmnMtnhPPHryO6aPM0l5fU71DwSquan23QYJodY25raswKfkNqfjjElh8hNongFYtOppDxo713ePT86l2FPKTHw6Ar0xhdJ/ZaRcXK0BhDp5IJJG3suI@j38EZ6qX3eNsx3J/gWNUv0MVZfufOAlImZkfyKF/0apiYaWEQRIdUZvkV09CfGSlYBPOXlneeyON84k0BPEdqNqp75jcjvRh@2seRHTRKefSbd5gxduzXSCl6X03c4c5RfnAzuQ9HBzb4dnVRsOtvy4vExMOqs9nRH/aby4nlqpDTd3lxNSmjmmX8krNyJUcMuO6g6BApM6WL9DO@1UV@8J6NZsm3t1B68TYJHVj2XqX9FVUHuick0Gt8n5EC8woPB6CHKzfMqlvrRkF/kplPJ1JYqYj3fMagOMd9DCdo4u9DOWTle4COL@lCjoFm@qQ1LGZJJuUBOaYx/LLJpn9lIcu82BNPChS5OGRgomImzplKklnN9g@wP8lnFeA4ECybvE78rUp9@2Lfsty3L/gtSv5p0Wdl/2TDn@hGwR80OT7@Cw "Kotlin – Try It Online")
31,955
To the best of my knowledge, energy equals work, $\mathrm{E = W}$; work equals force multiplied by distance, $\mathrm{W = Fm}$ ; force equals mass multiplied by acceleration, $\mathrm{F = MA}$; and acceleration equals distance per second squared, $\mathrm{A = m \setminus s^2}$. However, when I substitute those values in for the dimensions of $ \mathrm{W}$, I can't transform the result of those substitutions into $ \mathrm{W= \frac{1}{2}Mv^2}$. Perhaps I've done the algebra incorrectly. Does the result of those substitutions transform into $ \mathrm{W= \frac{1}{2}Mv^2}$? If it doesn't transform into that equation, why doesn't it do so, and why do we use an equation that isn't compatible with our other equations?
2015/05/24
[ "https://chemistry.stackexchange.com/questions/31955", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/15929/" ]
The kinetic energy $E\_\text{k}$ equals the work $W$ done on an object: $$E\_\text{k}=W$$ The work $W$ is the result of a force $F$ on a distance $s$. If $F$ is constant, the work $W$ is equal to the force $F$ multiplied by the distance $s$: $$W=Fs$$ The force $F$ on an object is equal to the mass $m$ of that object multiplied by the acceleration $a$: $$F=ma$$ For uniform acceleration $a$, the final velocity $v$ is $$v=at$$ and the distance $s$ is $$s=\frac{1}{2}vt=\frac{1}{2}at^2$$ Therefore, $$\begin{align} E\_\text{k}&=W\\ &=Fs\\ &=mas\\ &=ma\cdot\frac{1}{2}vt=ma\cdot\frac{1}{2}at^2=\frac{1}{2}m(at)^2\\ &=\frac{1}{2}mv^2 \end{align}$$
@Loong's answer is perfect but I just want to show another method which can be used even if the acceleration is **not** uniform. $$a=\frac{dv}{dt} = \frac{dv}{dx} \times \frac{dx}{dt}$$ Hence $$a=v\frac{dv}{dx}$$ Force is mass times acceleration. Hence $$F=ma=mv \frac{dv}{dx}$$ For a small distance $dx$ moved, the work done by the force is $F \times dx$. By the Work-Energy Theorem, this is also the gain in kinetic energy. Hence $$\Delta KE = \int\_{x\_1}^{x\_2} Fdx = \int\_{x\_1}^{x\_2} (mv \frac{dv}{dx}) dx = \int\_{v\_1}^{v\_2}mvdv$$ Hence $$\Delta KE = \frac{1}{2}m{v\_2}^2 - \frac{1}{2}m{v\_1}^2$$ If the body starts at rest $v\_1=0$ and we get the kinetic energy as $\frac{1}{2}mv^2$
5,838,764
I'm working on a function that takes filepaths and dices them up into smaller sections. For example, if the input parameter was "cd mypath/mystuff/stack/overflow/string", I want to be able to return "cd" "mypath", "mystuff", "stack", "overflow", and "string" in succession. While I could simply continually use "getchar", appending the results to an ever-increasing string, stopping when getchar returns a '/', I feel like there *must* be a more elegant way to achieve the same functionality. Any ideas?
2011/04/30
[ "https://Stackoverflow.com/questions/5838764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355682/" ]
You can use the `char * strtok ( char * str, const char * delimiters );` using `/` as separator. An example here: <http://www.cplusplus.com/reference/clibrary/cstring/strtok/> ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s path\n", argv[0]); exit(EXIT_FAILURE); } char* saveptr = NULL; for (char* str = argv[1]; ; str = NULL) { char *token = strtok_r(str, "/", &saveptr); if (token == NULL) break; printf("%s\n", token); } return 0; } ``` ### Example ``` clang -Wall *.c && ./a.out mypath/mystuff/stack/overflow/string mypath mystuff stack overflow string ```
Here's an example of how `sscanf()` can stop after a certain character. ``` sscanf("abcd/efgh", "%[^/]", &buf); printf("%s\n", buf); ``` Should produce ``` abcd ``` EDIT: You could try something like this to advance sscanf() input. I have not tested this for various edge cases, but it should get the idea across. ``` char *str = "abcd/efgh/ijk/xyz"; while (sscanf(str, "%[^/]%n", &buf, &n)) { printf("%s\n", buf); str += n; if (*str == '\0') break; ++str; } ``` should produce ``` abcd efgh ijk xyz ```
5,838,764
I'm working on a function that takes filepaths and dices them up into smaller sections. For example, if the input parameter was "cd mypath/mystuff/stack/overflow/string", I want to be able to return "cd" "mypath", "mystuff", "stack", "overflow", and "string" in succession. While I could simply continually use "getchar", appending the results to an ever-increasing string, stopping when getchar returns a '/', I feel like there *must* be a more elegant way to achieve the same functionality. Any ideas?
2011/04/30
[ "https://Stackoverflow.com/questions/5838764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355682/" ]
You can use the `char * strtok ( char * str, const char * delimiters );` using `/` as separator. An example here: <http://www.cplusplus.com/reference/clibrary/cstring/strtok/> ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s path\n", argv[0]); exit(EXIT_FAILURE); } char* saveptr = NULL; for (char* str = argv[1]; ; str = NULL) { char *token = strtok_r(str, "/", &saveptr); if (token == NULL) break; printf("%s\n", token); } return 0; } ``` ### Example ``` clang -Wall *.c && ./a.out mypath/mystuff/stack/overflow/string mypath mystuff stack overflow string ```
Here is an example using regcomp, regexec. Compile and run it with the first arg being the character you are searching on, while the second arg is the string to search. For example, a.out X abcXdefXghiXjkl will print abc def ghi jkl on separate lines. ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <regex.h> int main(int argc, char *argv[]) { int len; char *cp; char *token; regex_t preg; regmatch_t match; if (regcomp(&preg, argv[1], REG_EXTENDED) != 0) { return 0; } for (cp = argv[2]; *cp != '\0'; cp += len) { len = (regexec(&preg, cp, 1, &match, 0) == 0) ? match.rm_eo : strlen(cp); token = malloc(len); strncpy(token, cp, len); printf("%s\n", token); } return 0; } ```
5,838,764
I'm working on a function that takes filepaths and dices them up into smaller sections. For example, if the input parameter was "cd mypath/mystuff/stack/overflow/string", I want to be able to return "cd" "mypath", "mystuff", "stack", "overflow", and "string" in succession. While I could simply continually use "getchar", appending the results to an ever-increasing string, stopping when getchar returns a '/', I feel like there *must* be a more elegant way to achieve the same functionality. Any ideas?
2011/04/30
[ "https://Stackoverflow.com/questions/5838764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355682/" ]
Here's an example of how `sscanf()` can stop after a certain character. ``` sscanf("abcd/efgh", "%[^/]", &buf); printf("%s\n", buf); ``` Should produce ``` abcd ``` EDIT: You could try something like this to advance sscanf() input. I have not tested this for various edge cases, but it should get the idea across. ``` char *str = "abcd/efgh/ijk/xyz"; while (sscanf(str, "%[^/]%n", &buf, &n)) { printf("%s\n", buf); str += n; if (*str == '\0') break; ++str; } ``` should produce ``` abcd efgh ijk xyz ```
Here is an example using regcomp, regexec. Compile and run it with the first arg being the character you are searching on, while the second arg is the string to search. For example, a.out X abcXdefXghiXjkl will print abc def ghi jkl on separate lines. ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <regex.h> int main(int argc, char *argv[]) { int len; char *cp; char *token; regex_t preg; regmatch_t match; if (regcomp(&preg, argv[1], REG_EXTENDED) != 0) { return 0; } for (cp = argv[2]; *cp != '\0'; cp += len) { len = (regexec(&preg, cp, 1, &match, 0) == 0) ? match.rm_eo : strlen(cp); token = malloc(len); strncpy(token, cp, len); printf("%s\n", token); } return 0; } ```
338,195
I have a big .gz file. I would like to split it into 100 smaller gzip files, that can each be decompressed by itself. In other words: I am not looking for a way of chopping up the .gz file into chunks that would have to be put back together to be able to decompress it. I want to be able to decompress each of the smaller files independently. Can it be done without recompressing the whole file? Can it be done if the original file is compressed with `--rsyncable`? ("Cater better to the rsync program by periodically resetting the internal structure of the compressed data stream." sounds like these reset points might be good places to split at and probably prepend a header.) Can it be done for any of the other compressed formats? I would imagine `bzip2` would be doable - as it is compressed in blocks.
2017/01/17
[ "https://unix.stackexchange.com/questions/338195", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/2972/" ]
Split and join of the big file works, but it is impossible to decompress pieces of the compressed file, because essential informations are distributed through the whole dataset. Another way; split the uncompressed file and compress the single parts. Now you can decompress each pieces. But why? You have to merge all decompressed parts before further processing.
Except my error, i think this is not possible, without alterate your file in losing the ability to rebuild and decompress the big file because you will lose the metadata (header and tail) from the first big file compress and those metadata don't exist for each of your small file. But you could create a wrapper that could do... 1. (optional) compress the big file 2. split your big file into 100 small chunk 3. compress each of your small chunck in gzip 4. decompress each chunck in gzip. 5. concat chunck into the big file. 6. (optional) decompress the big file Notice : I am not sure in terme of your purpose... save storage ? save time network transmission ? limite space system ? what is your root need ? Best Regards
47,606,668
I have two main html elements. First one is a group of options, the second is a `ul` where I display the content, like this: ``` <optgroup style="display:none;" class="groupOfOptions"> <option value="15" data-upsell="presentation1"> Item 1 </option> <option value="3" data-upsell="presentation2"> Item 2 </option> <option value="5" data-upsell="presentation3"> Item 3 </option> </optgroup> <ul class="displayedList"> <li> <label> <input value="15" type="radio"> Item 1 </label> </li> <li> <label> <input value="3" type="radio"> Item 2 </label> </li> <li> <label> <input value="5" type="radio"> Item 3 </label> </li> </ul> ``` What I'm trying to do is to assign the `data-upsell-type` from the `optgroup` into the `ul` list. If a `li` item has the same text (Item 1, Item 2, Item 3) or `value` of input as some `option` element from the `optgroup`, then take the `data-upsell` from that `option` item and assign it to the specific `li` element. This is what I tried: ``` var objWithData = document.querySelector('.groupOfOptions'); var listToModify = document.querySelector('.displayedList'); var currentText; var getDataAttr; for (var i = 0; i < objWithData.length; i++) { currentText = objWithData[i].text; getDataAttr = this.getAttribute('data-upsell'); for (var x = 0; x < listToModify.length; i++) { if (listToModify[i].text == currentText) { listToModify[i].dataset.upsell = getDataAttr; } } } ``` However, nothing happens and no errors are thrown for me to analyse. Could someone offer a look at this?
2017/12/02
[ "https://Stackoverflow.com/questions/47606668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are too many questions and they are too generic. But in most cases: 1. No way 2. it's up to you, your app's logic and particular case. Say if there is water leak somewhere in the city is it expected to stop water supply system completely? Typically there is concrete module/part that does not make sense to process further once DB query fails. And only that module/part should exit/stop. 3. it's better not doing your own wrapping around PDO. in most cases you will just make code harder to maintain without any real benefit. 4. typically the best solution is to return some HTTP error(404 Not Found or 500 Internal Server Error) letting client code to know "sorry, you cannot get this information yet"; how client code will handle such an error - it depends on your client code's logic/flow
1. Only if you have a certain scenario to handle a particular error. For example, a duplicated unique key, for which you have a fall-back scenario. (note that you should always check for this particular error, and re-throw the exception otherwise). But for a regular query, only to handle an arbitrary error - just like @skyboyer said - no way. The exception should bubble up to a site-wide handler. 2. Again, it depends. If is a special handling scenario, do whatever you have in mind for the scenario. But for the arbitrary error, it is agreed upon to halt the code execution, as your code could yield unpredictable results. 3. That's two questions in one. * it's perfectly OK to have a *global* try catch which will act as a site-wide exception handler, wrapping the whole code. * as of the function to run all your queries - it's a brilliant idea by itself, but it has nothing to do with error handling. Simply because database errors are no different from any other error on your site and thus should be treated exactly the same way. Therefore it makes no sense to write a dedicated try-catch for the query function. Just let it throw an Exception and then handle that exception as any other error on your site. 4. Pretty much the same way as non-AJAX errors. Again - just like @skyboyer said - make your handler to return 500 HTTP status and then your AJAX calling code will know there was an error. That's enough I wrote an article where tried to explain all there matters, [PHP Error reporting](https://phpdelusions.net/articles/error_reporting) which you may find interesting.
717,136
I have the following cron job running a Python script which seems to install okay with no issues after creating it in Crontab and saving (this is on a server running Centos7). I'm not seeing either a log file nor any output sent in to the email address included. I've tried this: ``` */2 * * * * /home/local/DEV/mdub/FTWFB/FTWFBUploader.py > /home/local/DEV/mdub/FTWFB/logs`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log 2>&1 | mailx -s “Facebook Uploads - Cronlog" mdubs@gmail.com ``` and this: ``` */2 * * * * /home/local/DEV/mdub/FTWFB/FTWFBUploader.py | tee /home/local/DEV/mdub/FTWFB/logs`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log | mailx -s “Facebook Uploads - Cronlog" mdubs@gmail.com ``` What am I doing wrong? On both files I ran `chmod +x (filename)` and when I manually run the scripts they run and output as expected.
2015/08/27
[ "https://serverfault.com/questions/717136", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
Firstly, when configuring a crontab use the full path for any commands and scripts you are calling. For example: * `tee` should be `/usr/bin/tee` * `mailx` should be `/bin/mailx` * `date` should be `/bin/date` Note: If the paths are different on your system change as appropriate Also, chaining commands in a crontab (i.e. piping, `|`) can get messy very quickly. It might be better to put those commands in a script and call that from cron instead. If that doesn't help follow these general troubleshooting steps for cron: Verify that `crond` is enabled and running, for example: ``` $ systemctl status crond | grep enabled Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled) $ ps -ef | grep ^root.*crond root 1251 1 0 May15 ? 00:00:55 /usr/sbin/crond -n ``` Check the cron logs to see if any errors show up in there (replace `UserName` with the name of the user): ``` grep UserName /var/log/cron ``` Check that user's mail file to see if any cron output is showing up there: ``` more /var/mail/UserName ``` If all else fails, append a redirect at the end of the crontab entry to help catch any spurious errors that might arise. For example instead of this: ``` * * * * * /bin/date | /usr/bin/mailx -s cron.test UserName@domain.tld ``` Do this: ``` * * * * * /bin/date | /usr/bin/mailx -s cron.test UserName@domain.tld > /tmp/crontab.test.UserName.log 2>&1 ```
Cron doesn't allow % characters.
717,136
I have the following cron job running a Python script which seems to install okay with no issues after creating it in Crontab and saving (this is on a server running Centos7). I'm not seeing either a log file nor any output sent in to the email address included. I've tried this: ``` */2 * * * * /home/local/DEV/mdub/FTWFB/FTWFBUploader.py > /home/local/DEV/mdub/FTWFB/logs`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log 2>&1 | mailx -s “Facebook Uploads - Cronlog" mdubs@gmail.com ``` and this: ``` */2 * * * * /home/local/DEV/mdub/FTWFB/FTWFBUploader.py | tee /home/local/DEV/mdub/FTWFB/logs`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log | mailx -s “Facebook Uploads - Cronlog" mdubs@gmail.com ``` What am I doing wrong? On both files I ran `chmod +x (filename)` and when I manually run the scripts they run and output as expected.
2015/08/27
[ "https://serverfault.com/questions/717136", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
The best practice here is to write a script and call that script by full path within cron. This really is just reinforcing what Gene stated, but writing a script that will run those commands allows you the ability to test the script before placing it in a cron. Additionally, this makes cron easier to read over the long run.
Cron doesn't allow % characters.
259,392
We are seeing restore taking more than 25 minutes for a simple 4 mb file .Restore progresses to 100%,but it wont update any status from there When checked in error log ,we could see below error... > > Process 0:0:0 (0x12c8) Worker 0x000000CB5481A160 appears to be non-yielding on Scheduler 0. Thread creation time: 13223894899341. Approx Thread CPU Used: kernel 0 ms, user 0 ms. Process Utilization 2%. System Idle 92%. Interval: 70083 ms. > > > We are able to match the worker address with session id of restore as shown in below screenshot [![enter image description here](https://i.stack.imgur.com/hjTPg.jpg)](https://i.stack.imgur.com/hjTPg.jpg) further we could see wait type of the spid for restore is 'PREEMPTIVE\_OS\_CREATEFILE' Below are some more details Version: > > Microsoft SQL Server 2014 (SP3-CU4) (KB4500181) - 12.0.6329.1 (X64) > Jul 20 2019 21:42:29 > Copyright (c) Microsoft Corporation > Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 (Build 9600: ) > > > windows details : > > windows serrver 2012 R2 standard > > > actual file sizes of this mdf,ndf ,ldf are 0.5,0.4 and 1 GB respectively.backup file is 4 MB File speeds during restore are below 50 MS. Any ideas on what may cause this behaviour ..?
2020/02/11
[ "https://dba.stackexchange.com/questions/259392", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/31995/" ]
The size of the backup file is only partly relevant. The restore process first have to create the database files (the "containers" as I like to think of them) and they need to have the same size as when the backup was produced. So you have have a database with only small amount of information, but sitting in large database files. Instant File Initialization can help to some extent, but only for database files. I.e., not for transaction log files. See for instant [this](https://www.brentozar.com/blitz/instant-file-initialization/) for more info. If you want to know the size of the file to be created, you can use RESTORE FILELISTONLY: ``` RESTORE FILELISTONLY FROM DISK = 'R:\mybackup.bak' ``` You might need a FILE option if you have more than one backup in the file (just like in the RESTORE command you are running).
I had the same problem it was due to the size of the DB. Although the backup shows 9 MB, when I right click the DB in SQL server management and select properties, the size shown was 25 GB! What I did is that I changed the DB to "Simple Recovery", shrinked the log file,backup again, and I could restore now.
1,372,048
I am in really big trouble right now, so a VERY quick solution would be much appreciated. I was in an SSH session on my laptop that has LUKS encryption, and I thought I was restoring its header. But I realized later that I had actually SSH'd to my desktop and accidentally used the LUKS header backup file to restore on my desktop, which did not have any LUKS encryption. Now, I cannot boot into my filesystem at all. Is there any way I can retrieve my operating system, or at the very least my files? I also deleted tried to erase the header as soon as I realized, but it did not help, the header still remains, just all of they keys are disabled. 64-bit Kali Linux ext4 filesystem, dual-booted with Windows 10 partition The Kali Linux partition is the one that had the header accidentally overwritten. The command I used that accidentally restored the header was: `cryptsetup luksHeaderRestore /dev/sda5 --header-backup-file header.bak`
2018/11/02
[ "https://superuser.com/questions/1372048", "https://superuser.com", "https://superuser.com/users/959792/" ]
This is a VERY early release version of the tabbed interface Microsoft is developing for future versions of Windows. I've had it in my Fast Ring Insiders builds of Windows 10 for 6 months or more at this point. The basic premise of the UI is that any window can be grouped with any other application window, and that is what you see in this screenshot: Windows Subsystem for Linux running embedded Ubuntu, then the CMD prompt, and then Powershell. Microsoft original hoped to include "Sets" in 1803, last spring, but pulled it. I believe the feature was also pulled from 1809 for being still not polished enough.
Are you referring to the feature of having multiple tabs? I remember seeing it from the windows insider program. It is called "Sets" where you can have tabs for every window and application but if this is not what you are talking about could you give some more information.
672,721
I am trying to solve the problem: A, B are given point. **a** is the position vector of A, and **b** is the position vector of B. I want to find the equation of perpendicular bisector of AB in a vector form. I solved this problem in a regular form, which I first set A $(x\_1,y\_1)$ B $(x\_2,y\_2)$, then the equation of this line is $$ (x\_2-x\_1)x+(y\_2-y\_1)y-\dfrac{x\_2^2-x\_1^2}{2}-\dfrac{y\_2^2-y\_1^2}{2}=0$$ But I don't know how to convert it in to something in the form of $$\vec{r}=\vec{r}\_0+t\vec{v}=\langle x\_0,y\_0,z\_0\rangle+t\langle a,b,c\rangle $$ Would someone give me a hint? Thanks in advance.
2014/02/11
[ "https://math.stackexchange.com/questions/672721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/95064/" ]
It *is* likely more helpful to set out the problem using vector forms for the relevant lines. The vector $ \ \vec{c} \ = \ \vec{AB} \ $ is $ \ \vec{c} \ = \ \vec{b} \ - \ \vec{a} \ $ (since $ \ \vec{a} \ + \ \vec{c} \ = \ \vec{b} \ $ ) . It appears that you are working in $ \ \mathbb{R}^2 \ $ , so we have $$ \vec{a} \ = \ \langle x\_1 \ , \ y\_1 \rangle \ \ , \ \ \vec{b} \ = \ \langle x\_2 \ , \ y\_2 \rangle \ \ , \ \ \vec{c} \ = \ \langle x\_2 - x\_1 \ , \ y\_2 - y\_1 \rangle \ \ . $$ It is convenient to use $ \ \vec{a} \ $ as the "initial" vector with a parameterization that places $ \ t = 0 \ $ there (point A) and places $ \ t = 1 \ $ at $ \ \vec{b} \ $ (point B) , with the direction given by $ \ \vec{c} \ $ . The vector $ \ \vec{c} \ $ then lies along the line AB having parametric equation $$ \ \vec{r} \ = \ \vec{a} \ + \ t \ \vec{c} \ = \ \langle x\_1 \ , \ y\_1 \rangle \ + \ t \ \langle x\_2 - x\_1 \ , \ y\_2 - y\_1 \rangle \ \ . $$ The midpoint is then located at $ \ t = \frac{1}{2} \ $ , said point being at the head of position vector $ \ \langle \frac{x\_1 \ + \ x\_2}{2} \ , $ $ \ \frac{y\_1 \ + \ y\_2}{2} \rangle \ $ . The perpendicular bisector of $ \ \overline{AB} \ $ can be defined by a vector which has a zero "dot product" (scalar product) with $ \ \vec{c} \ $ . If we say that this line has a slope $ \ m \ $ , we can write its direction as $ \ \langle 1 \ , \ m \rangle \ $ , and so $$ \langle x\_2 - x\_1 \ , \ y\_2 - y\_1 \rangle \ \cdot \ \langle 1 \ , \ m \rangle \ \ = \ \ (x\_2 - x\_1 ) \ + \ m \ (y\_2 - y\_1) \ \ = \ \ 0 $$ $$ \Rightarrow \ \ m \ \ = \ \ - \frac{x\_2 - x\_1}{y\_2 - y\_1} \ \ . $$ (Note that this is just what we expect from the "product of slopes of perpendicular lines" theorem, since the direction $ \ \vec{c} \ $ has slope $ \ \frac{y\_2 - y\_1}{x\_2 - x\_1} \ $ . ) Since $ \ y\_2 - y\_1 \ \neq \ 0 \ $ , we can then also write the direction for the perpendicular bisector as $ \ \langle y\_2 - y\_1 \ , \ x\_1 - x\_2 \rangle \ $ . (It is also acceptable to attach the "minus sign" to the first component instead -- thus, $ \ \langle y\_1 - y\_2 \ , \ x\_2 - x\_1 \rangle \ $ -- which is a vector pointing in the opposite direction on the perpendicular bisector line. Finally, we can establish a parametrization of the perpendicular bisector with the midpoint of $ \ \overline{AB} \ $ at $ \ \tau = 0 \ $ , making it the "initial" vector for the bisector. The vector form for this line may then be written as $$ \vec{R} \ = \ \langle \frac{x\_1 \ + \ x\_2}{2} \ , \ \frac{y\_1 \ + \ y\_2}{2} \rangle \ + \ \tau \ \langle y\_2 - y\_1 \ , \ x\_1 - x\_2 \rangle \ \ . $$ This method can be extended to $ \ \mathbb{R}^3 \ $ , except that the perpendicular bisector is ambiguous to the extent that it lies in a plane for which $ \ \vec{AB} \ $ is its normal. To pin things down, we would need to specify a point in that plane that the bisector passes through. (This is sometimes given as a textbook or exam problem.)
**Hint**: The geometrical meaning of the formula $\vec r=\vec r\_0+t\vec v$ is a line that passes in $\vec r\_0$ (for $t=0$) and is directed along $\vec v$. So what you need is a point that the line goes through, and a direction. The point is easy - that's simply the midpoint between $\vec a$ and $\vec b$. The direction is a bit more subtle. Are you familiar with [cross products][1]? [1]: <http://en.wikipedia.org/wiki/Cross_product> im just kidding this isn't right :'D I have no idea what im doing my bad person :'D
672,721
I am trying to solve the problem: A, B are given point. **a** is the position vector of A, and **b** is the position vector of B. I want to find the equation of perpendicular bisector of AB in a vector form. I solved this problem in a regular form, which I first set A $(x\_1,y\_1)$ B $(x\_2,y\_2)$, then the equation of this line is $$ (x\_2-x\_1)x+(y\_2-y\_1)y-\dfrac{x\_2^2-x\_1^2}{2}-\dfrac{y\_2^2-y\_1^2}{2}=0$$ But I don't know how to convert it in to something in the form of $$\vec{r}=\vec{r}\_0+t\vec{v}=\langle x\_0,y\_0,z\_0\rangle+t\langle a,b,c\rangle $$ Would someone give me a hint? Thanks in advance.
2014/02/11
[ "https://math.stackexchange.com/questions/672721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/95064/" ]
It *is* likely more helpful to set out the problem using vector forms for the relevant lines. The vector $ \ \vec{c} \ = \ \vec{AB} \ $ is $ \ \vec{c} \ = \ \vec{b} \ - \ \vec{a} \ $ (since $ \ \vec{a} \ + \ \vec{c} \ = \ \vec{b} \ $ ) . It appears that you are working in $ \ \mathbb{R}^2 \ $ , so we have $$ \vec{a} \ = \ \langle x\_1 \ , \ y\_1 \rangle \ \ , \ \ \vec{b} \ = \ \langle x\_2 \ , \ y\_2 \rangle \ \ , \ \ \vec{c} \ = \ \langle x\_2 - x\_1 \ , \ y\_2 - y\_1 \rangle \ \ . $$ It is convenient to use $ \ \vec{a} \ $ as the "initial" vector with a parameterization that places $ \ t = 0 \ $ there (point A) and places $ \ t = 1 \ $ at $ \ \vec{b} \ $ (point B) , with the direction given by $ \ \vec{c} \ $ . The vector $ \ \vec{c} \ $ then lies along the line AB having parametric equation $$ \ \vec{r} \ = \ \vec{a} \ + \ t \ \vec{c} \ = \ \langle x\_1 \ , \ y\_1 \rangle \ + \ t \ \langle x\_2 - x\_1 \ , \ y\_2 - y\_1 \rangle \ \ . $$ The midpoint is then located at $ \ t = \frac{1}{2} \ $ , said point being at the head of position vector $ \ \langle \frac{x\_1 \ + \ x\_2}{2} \ , $ $ \ \frac{y\_1 \ + \ y\_2}{2} \rangle \ $ . The perpendicular bisector of $ \ \overline{AB} \ $ can be defined by a vector which has a zero "dot product" (scalar product) with $ \ \vec{c} \ $ . If we say that this line has a slope $ \ m \ $ , we can write its direction as $ \ \langle 1 \ , \ m \rangle \ $ , and so $$ \langle x\_2 - x\_1 \ , \ y\_2 - y\_1 \rangle \ \cdot \ \langle 1 \ , \ m \rangle \ \ = \ \ (x\_2 - x\_1 ) \ + \ m \ (y\_2 - y\_1) \ \ = \ \ 0 $$ $$ \Rightarrow \ \ m \ \ = \ \ - \frac{x\_2 - x\_1}{y\_2 - y\_1} \ \ . $$ (Note that this is just what we expect from the "product of slopes of perpendicular lines" theorem, since the direction $ \ \vec{c} \ $ has slope $ \ \frac{y\_2 - y\_1}{x\_2 - x\_1} \ $ . ) Since $ \ y\_2 - y\_1 \ \neq \ 0 \ $ , we can then also write the direction for the perpendicular bisector as $ \ \langle y\_2 - y\_1 \ , \ x\_1 - x\_2 \rangle \ $ . (It is also acceptable to attach the "minus sign" to the first component instead -- thus, $ \ \langle y\_1 - y\_2 \ , \ x\_2 - x\_1 \rangle \ $ -- which is a vector pointing in the opposite direction on the perpendicular bisector line. Finally, we can establish a parametrization of the perpendicular bisector with the midpoint of $ \ \overline{AB} \ $ at $ \ \tau = 0 \ $ , making it the "initial" vector for the bisector. The vector form for this line may then be written as $$ \vec{R} \ = \ \langle \frac{x\_1 \ + \ x\_2}{2} \ , \ \frac{y\_1 \ + \ y\_2}{2} \rangle \ + \ \tau \ \langle y\_2 - y\_1 \ , \ x\_1 - x\_2 \rangle \ \ . $$ This method can be extended to $ \ \mathbb{R}^3 \ $ , except that the perpendicular bisector is ambiguous to the extent that it lies in a plane for which $ \ \vec{AB} \ $ is its normal. To pin things down, we would need to specify a point in that plane that the bisector passes through. (This is sometimes given as a textbook or exam problem.)
Note, for the question to be meaningful, we must be working in a plane (otherwise 'the' perpendicular bisector is not defined). Let $\hat{z}$ be a vector pointing out of the plane. We want the equation of a line which passes through the midpoint of $\mathbf{a}$ and $\mathbf{b}$ and is perpendicular to $\mathbf{a}-\mathbf{b}$ and perpendicular to $\hat{z}$. Such a line is given by: $$\frac12(\mathbf{a}+\mathbf{b})+\lambda (\mathbf{a}-\mathbf{b})\times \hat{z} $$
110,748
How do I use relational operators on vectors? ``` {1, 2, 3} > {0, 1, 2} (*outputs {1, 2, 3} > {0, 1, 2}*) ``` More generally, I want `{a,b}>{c,d}` to be equivalent to `a>c && b>d`. Or, I would want to say `vars>0` where `vars` is a vector of my variables and that one constraint forces them all to be strictly positive. How might I achieve that?
2016/03/22
[ "https://mathematica.stackexchange.com/questions/110748", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/25422/" ]
``` And @@ Thread[{a, b} > {c, d}] (* a > c && b > d *) ```
You can also use the [BoolEval](http://packagedata.net/index.php/links/examples/id/31) package. You'd use it like this: ``` Needs["BoolEval`"] FreeQ[BoolEval[{1, 2, 3} > {0, 1, 2}], 0] (* True *) ``` Or ``` Times @@ BoolEval[{1, 2, 3} > {0, 1, 2}] == 1 ``` The point being that `BoolEval` returns a 1 or a 0 for each comparison, representing true or false. If there are no zeroes that means that all comparisons were true. > > How do I use relational operators on vectors? > > > `BoolEval` is a general answer to this question. If you want a more compact syntax you could implement `BoolEvalAnd`, `BoolEvalOr` etc. along the lines of the solution above.
110,748
How do I use relational operators on vectors? ``` {1, 2, 3} > {0, 1, 2} (*outputs {1, 2, 3} > {0, 1, 2}*) ``` More generally, I want `{a,b}>{c,d}` to be equivalent to `a>c && b>d`. Or, I would want to say `vars>0` where `vars` is a vector of my variables and that one constraint forces them all to be strictly positive. How might I achieve that?
2016/03/22
[ "https://mathematica.stackexchange.com/questions/110748", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/25422/" ]
``` And @@ Thread[{a, b} > {c, d}] (* a > c && b > d *) ```
Here is a new operator ( `⪢`,alias `\[NestedGreaterGreater] )` that is a generalisation of the built-in `>` : ``` NestedGreaterGreater[x___] := And @@ Thread[Greater[x]] ``` This permits interesting operations : * `{a, b} ⪢ {c, d}` > > (a > c) && (b > d) > > > * `{a, b} ⪢ {c, d} ⪢ {e, f}` > > (a > c > e) && (b > d > f) > > > * `{a, b} ⪢ c ⪢ {d, e}` > > (a > c > d) && (b > c > e) > > > For clearity some parenthesis have been added in the previous results.
110,748
How do I use relational operators on vectors? ``` {1, 2, 3} > {0, 1, 2} (*outputs {1, 2, 3} > {0, 1, 2}*) ``` More generally, I want `{a,b}>{c,d}` to be equivalent to `a>c && b>d`. Or, I would want to say `vars>0` where `vars` is a vector of my variables and that one constraint forces them all to be strictly positive. How might I achieve that?
2016/03/22
[ "https://mathematica.stackexchange.com/questions/110748", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/25422/" ]
Here is a new operator ( `⪢`,alias `\[NestedGreaterGreater] )` that is a generalisation of the built-in `>` : ``` NestedGreaterGreater[x___] := And @@ Thread[Greater[x]] ``` This permits interesting operations : * `{a, b} ⪢ {c, d}` > > (a > c) && (b > d) > > > * `{a, b} ⪢ {c, d} ⪢ {e, f}` > > (a > c > e) && (b > d > f) > > > * `{a, b} ⪢ c ⪢ {d, e}` > > (a > c > d) && (b > c > e) > > > For clearity some parenthesis have been added in the previous results.
You can also use the [BoolEval](http://packagedata.net/index.php/links/examples/id/31) package. You'd use it like this: ``` Needs["BoolEval`"] FreeQ[BoolEval[{1, 2, 3} > {0, 1, 2}], 0] (* True *) ``` Or ``` Times @@ BoolEval[{1, 2, 3} > {0, 1, 2}] == 1 ``` The point being that `BoolEval` returns a 1 or a 0 for each comparison, representing true or false. If there are no zeroes that means that all comparisons were true. > > How do I use relational operators on vectors? > > > `BoolEval` is a general answer to this question. If you want a more compact syntax you could implement `BoolEvalAnd`, `BoolEvalOr` etc. along the lines of the solution above.
311,701
Usually we use the word "breakfast" in the morning to mean to eat something, but what word do we use to mean "afternoon breakfast" and "evening breakfast"?
2022/03/19
[ "https://ell.stackexchange.com/questions/311701", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/152969/" ]
The expression "falling (or going) down a rabbit hole" does refer to Alice in Wonderland, but specifically it means getting sucked into a never-ending activity - similar to the seemingly bottomless hole that Alice falls down. In this case the activity is Googling all the jazz clubs in Paris. The only relevance of "drunk" here is that Mindy only got started doing this because she had been drinking.
"Going down the rabbit hole" is an allusion to *Alice in Wonderland*, and means "begin a process that is strange, complex or chaotic". So Mindy means that the Jazz clubs are strange or chaotic. But she is entering this situation when drunk (and therefore less able to deal with complexity). It is just expressing that Mindy had been drinking. "Go down the rabbit hole" is an expression, but adding "drunk" to it is not a standard expression.
19,926
I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat. I'm using an Arduino Uno's `digitalWrite()` feature to activate a transistor, allowing the external 9V battery to turn on the motor. Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that. Here's the schematic of my circuit: ![schematic](https://i.stack.imgur.com/EoTLx.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fEoTLx.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) **Code:** ``` void setup(){ pinMode(9, OUTPUT); } void loop(){ digitalWrite(9, HIGH); delay(1000); digitalWrite(9, LOW); delay(1000); } ``` Why isn't the motor completely turning off?
2016/01/24
[ "https://arduino.stackexchange.com/questions/19926", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/16697/" ]
I can't make much sense of your diagram- but this is the correct way to do it: ![schematic](https://i.stack.imgur.com/cGWWK.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fcGWWK.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on. You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.
There are multiple things wrong with your drawn schematic: * The ground symbol is not wrong but really misleading. * You forgot to add a flyback diode. * You wired the load the wrong way: the load is placed between the collector and VCC, not between emitter and GND. * The base resistor is way too high.
5,027,999
Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and `the GetAwaiter()` / `BeginAwait()` / `EndAwait()` calls. We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand: * Why the generated class contains a `Dispose()` method and a `$__disposing` variable, which never appear to be used (and the class doesn't implement `IDisposable`). * Why the internal `state` variable is set to 0 before any call to `EndAwait()`, when 0 normally appears to mean "this is the initial entry point". I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however. Here's a very simple piece of sample code: ``` using System.Threading.Tasks; class Test { static async Task<int> Sum(Task<int> t1, Task<int> t2) { return await t1 + await t2; } } ``` ... and here's the code which gets generated for the `MoveNext()` method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names: ``` public void MoveNext() { try { this.$__doFinallyBodies = true; switch (this.<>1__state) { case 1: break; case 2: goto Label_00DA; case -1: return; default: this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; break; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); this.<a2>t__$await4 = this.t2.GetAwaiter<int>(); this.<>1__state = 2; this.$__doFinallyBodies = false; if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; Label_00DA: this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); this.<>1__state = -1; this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3); } catch (Exception exception) { this.<>1__state = -1; this.$builder.SetException(exception); } } ``` It's long, but the important lines for this question are these: ``` // End of awaiting t1 this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); // End of awaiting t2 this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); ``` In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If `MoveNext()` were called again at this point (either directly or via `Dispose`) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and `MoveNext()` *isn't* called, the change in state is irrelevant. Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation? **Important disclaimer** Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)
2011/02/17
[ "https://Stackoverflow.com/questions/5027999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22656/" ]
if it was kept at 1 (first case) you would get a call to `EndAwait` without a call to `BeginAwait`. If it's kept at 2 (second case) you'd get the same result just on the other awaiter. I'm guessing that calling the BeginAwait returns false if it has be started already (a guess from my side) and keeps the original value to return at the EndAwait. If that's the case it would work correctly whereas if you set it to -1 you might have an uninitialized `this.<1>t__$await1` for the first case. This however assumes that BeginAwaiter won't actually start the action on any calls after the first and that it will return false in those cases. Starting would of course be unacceptable since it could have side effect or simply give a different result. It also assumpes that the EndAwaiter will always return the same value no matter how many times it's called and that is can be called when BeginAwait returns false (as per the above assumption) It would seem to be a guard against race conditions If we inline the statements where movenext is called by a different thread after the state = 0 in questions it woule look something like the below ``` this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate) this.<>1__state = 0; //second thread this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate) this.$__doFinallyBodies = true; this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); //other thread this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); ``` If the assumptions above are correct the there's some unneeded work done such as get sawiater and reassigning the same value to <1>t\_\_$await1. If the state was kept at 1 then the last part would in stead be: ``` //second thread //I suppose this un matched call to EndAwait will fail this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); ``` further if it was set to 2 the state machine would assume it already had gotten the value of the first action which would be untrue and a (potentially) unassigned variable would be used to calculate the result
Could it be something to do with stacked/nested async calls ?.. i.e: ``` async Task m1() { await m2; } async Task m2() { await m3(); } async Task m3() { Thread.Sleep(10000); } ``` Does the movenext delegate get called multiple times in this situation ? Just a punt really?
5,027,999
Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and `the GetAwaiter()` / `BeginAwait()` / `EndAwait()` calls. We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand: * Why the generated class contains a `Dispose()` method and a `$__disposing` variable, which never appear to be used (and the class doesn't implement `IDisposable`). * Why the internal `state` variable is set to 0 before any call to `EndAwait()`, when 0 normally appears to mean "this is the initial entry point". I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however. Here's a very simple piece of sample code: ``` using System.Threading.Tasks; class Test { static async Task<int> Sum(Task<int> t1, Task<int> t2) { return await t1 + await t2; } } ``` ... and here's the code which gets generated for the `MoveNext()` method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names: ``` public void MoveNext() { try { this.$__doFinallyBodies = true; switch (this.<>1__state) { case 1: break; case 2: goto Label_00DA; case -1: return; default: this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; break; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); this.<a2>t__$await4 = this.t2.GetAwaiter<int>(); this.<>1__state = 2; this.$__doFinallyBodies = false; if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; Label_00DA: this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); this.<>1__state = -1; this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3); } catch (Exception exception) { this.<>1__state = -1; this.$builder.SetException(exception); } } ``` It's long, but the important lines for this question are these: ``` // End of awaiting t1 this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); // End of awaiting t2 this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); ``` In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If `MoveNext()` were called again at this point (either directly or via `Dispose`) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and `MoveNext()` *isn't* called, the change in state is irrelevant. Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation? **Important disclaimer** Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)
2011/02/17
[ "https://Stackoverflow.com/questions/5027999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22656/" ]
Could it be something to do with stacked/nested async calls ?.. i.e: ``` async Task m1() { await m2; } async Task m2() { await m3(); } async Task m3() { Thread.Sleep(10000); } ``` Does the movenext delegate get called multiple times in this situation ? Just a punt really?
Explanation of actual states: possible states: * **0** Initialized (i think so) **or** waiting for end of operation * **>0** just called MoveNext, chosing next state * **-1** ended Is it possible that this implementation just wants to assure that if another Call to MoveNext from whereever happens (while waiting) it will reevaluate the whole state-chain again from the beginning, **to reevaluate results which could be in the mean time already outdated?**
5,027,999
Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and `the GetAwaiter()` / `BeginAwait()` / `EndAwait()` calls. We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand: * Why the generated class contains a `Dispose()` method and a `$__disposing` variable, which never appear to be used (and the class doesn't implement `IDisposable`). * Why the internal `state` variable is set to 0 before any call to `EndAwait()`, when 0 normally appears to mean "this is the initial entry point". I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however. Here's a very simple piece of sample code: ``` using System.Threading.Tasks; class Test { static async Task<int> Sum(Task<int> t1, Task<int> t2) { return await t1 + await t2; } } ``` ... and here's the code which gets generated for the `MoveNext()` method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names: ``` public void MoveNext() { try { this.$__doFinallyBodies = true; switch (this.<>1__state) { case 1: break; case 2: goto Label_00DA; case -1: return; default: this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; break; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); this.<a2>t__$await4 = this.t2.GetAwaiter<int>(); this.<>1__state = 2; this.$__doFinallyBodies = false; if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; Label_00DA: this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); this.<>1__state = -1; this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3); } catch (Exception exception) { this.<>1__state = -1; this.$builder.SetException(exception); } } ``` It's long, but the important lines for this question are these: ``` // End of awaiting t1 this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); // End of awaiting t2 this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); ``` In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If `MoveNext()` were called again at this point (either directly or via `Dispose`) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and `MoveNext()` *isn't* called, the change in state is irrelevant. Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation? **Important disclaimer** Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)
2011/02/17
[ "https://Stackoverflow.com/questions/5027999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22656/" ]
Okay, I finally have a real answer. I sort of worked it out on my own, but only after Lucian Wischik from the VB part of the team confirmed that there really is a good reason for it. Many thanks to him - and please visit [his blog](https://learn.microsoft.com/en-us/archive/blogs/lucian/) (on [archive.org](https://web.archive.org/web/20160216063203/http://blogs.msdn.com:80/b/lucian)), which rocks. The value 0 here is only special because it's *not* a valid state which you might be in just before the `await` in a normal case. In particular, it's not a state which the state machine may end up testing for elsewhere. I believe that using any non-positive value would work just as well: -1 isn't used for this as it's *logically* incorrect, as -1 normally means "finished". I could argue that we're giving an extra meaning to state 0 at the moment, but ultimately it doesn't really matter. The point of this question was finding out why the state is being set at all. The value is relevant if the await ends in an exception which is caught. We can end up coming back to the same await statement again, but we *mustn't* be in the state meaning "I'm just about to come back from that await" as otherwise all kinds of code would be skipped. It's simplest to show this with an example. Note that I'm now using the second CTP, so the generated code is slightly different to that in the question. Here's the async method: ``` static async Task<int> FooAsync() { var t = new SimpleAwaitable(); for (int i = 0; i < 3; i++) { try { Console.WriteLine("In Try"); return await t; } catch (Exception) { Console.WriteLine("Trying again..."); } } return 0; } ``` Conceptually, the `SimpleAwaitable` can be any awaitable - maybe a task, maybe something else. For the purposes of my tests, it always returns false for `IsCompleted`, and throws an exception in `GetResult`. Here's the generated code for `MoveNext`: ``` public void MoveNext() { int returnValue; try { int num3 = state; if (num3 == 1) { goto Label_ContinuationPoint; } if (state == -1) { return; } t = new SimpleAwaitable(); i = 0; Label_ContinuationPoint: while (i < 3) { // Label_ContinuationPoint: should be here try { num3 = state; if (num3 != 1) { Console.WriteLine("In Try"); awaiter = t.GetAwaiter(); if (!awaiter.IsCompleted) { state = 1; awaiter.OnCompleted(MoveNextDelegate); return; } } else { state = 0; } int result = awaiter.GetResult(); awaiter = null; returnValue = result; goto Label_ReturnStatement; } catch (Exception) { Console.WriteLine("Trying again..."); } i++; } returnValue = 0; } catch (Exception exception) { state = -1; Builder.SetException(exception); return; } Label_ReturnStatement: state = -1; Builder.SetResult(returnValue); } ``` I had to move `Label_ContinuationPoint` to make it valid code - otherwise it's not in the scope of the `goto` statement - but that doesn't affect the answer. Think about what happens when `GetResult` throws its exception. We'll go through the catch block, increment `i`, and then loop round again (assuming `i` is still less than 3). We're still in whatever state we were before the `GetResult` call... but when we get inside the `try` block we *must* print "In Try" and call `GetAwaiter` again... and we'll only do that if state isn't 1. Without the `state = 0` assignment, it will use the existing awaiter and skip the `Console.WriteLine` call. It's a fairly tortuous bit of code to work through, but that just goes to show the kinds of thing that the team has to think about. I'm glad I'm not responsible for implementing this :)
Could it be something to do with stacked/nested async calls ?.. i.e: ``` async Task m1() { await m2; } async Task m2() { await m3(); } async Task m3() { Thread.Sleep(10000); } ``` Does the movenext delegate get called multiple times in this situation ? Just a punt really?
5,027,999
Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and `the GetAwaiter()` / `BeginAwait()` / `EndAwait()` calls. We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand: * Why the generated class contains a `Dispose()` method and a `$__disposing` variable, which never appear to be used (and the class doesn't implement `IDisposable`). * Why the internal `state` variable is set to 0 before any call to `EndAwait()`, when 0 normally appears to mean "this is the initial entry point". I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however. Here's a very simple piece of sample code: ``` using System.Threading.Tasks; class Test { static async Task<int> Sum(Task<int> t1, Task<int> t2) { return await t1 + await t2; } } ``` ... and here's the code which gets generated for the `MoveNext()` method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names: ``` public void MoveNext() { try { this.$__doFinallyBodies = true; switch (this.<>1__state) { case 1: break; case 2: goto Label_00DA; case -1: return; default: this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; break; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); this.<a2>t__$await4 = this.t2.GetAwaiter<int>(); this.<>1__state = 2; this.$__doFinallyBodies = false; if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; Label_00DA: this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); this.<>1__state = -1; this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3); } catch (Exception exception) { this.<>1__state = -1; this.$builder.SetException(exception); } } ``` It's long, but the important lines for this question are these: ``` // End of awaiting t1 this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); // End of awaiting t2 this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); ``` In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If `MoveNext()` were called again at this point (either directly or via `Dispose`) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and `MoveNext()` *isn't* called, the change in state is irrelevant. Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation? **Important disclaimer** Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)
2011/02/17
[ "https://Stackoverflow.com/questions/5027999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22656/" ]
if it was kept at 1 (first case) you would get a call to `EndAwait` without a call to `BeginAwait`. If it's kept at 2 (second case) you'd get the same result just on the other awaiter. I'm guessing that calling the BeginAwait returns false if it has be started already (a guess from my side) and keeps the original value to return at the EndAwait. If that's the case it would work correctly whereas if you set it to -1 you might have an uninitialized `this.<1>t__$await1` for the first case. This however assumes that BeginAwaiter won't actually start the action on any calls after the first and that it will return false in those cases. Starting would of course be unacceptable since it could have side effect or simply give a different result. It also assumpes that the EndAwaiter will always return the same value no matter how many times it's called and that is can be called when BeginAwait returns false (as per the above assumption) It would seem to be a guard against race conditions If we inline the statements where movenext is called by a different thread after the state = 0 in questions it woule look something like the below ``` this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate) this.<>1__state = 0; //second thread this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate) this.$__doFinallyBodies = true; this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); //other thread this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); ``` If the assumptions above are correct the there's some unneeded work done such as get sawiater and reassigning the same value to <1>t\_\_$await1. If the state was kept at 1 then the last part would in stead be: ``` //second thread //I suppose this un matched call to EndAwait will fail this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); ``` further if it was set to 2 the state machine would assume it already had gotten the value of the first action which would be untrue and a (potentially) unassigned variable would be used to calculate the result
Explanation of actual states: possible states: * **0** Initialized (i think so) **or** waiting for end of operation * **>0** just called MoveNext, chosing next state * **-1** ended Is it possible that this implementation just wants to assure that if another Call to MoveNext from whereever happens (while waiting) it will reevaluate the whole state-chain again from the beginning, **to reevaluate results which could be in the mean time already outdated?**
5,027,999
Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and `the GetAwaiter()` / `BeginAwait()` / `EndAwait()` calls. We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand: * Why the generated class contains a `Dispose()` method and a `$__disposing` variable, which never appear to be used (and the class doesn't implement `IDisposable`). * Why the internal `state` variable is set to 0 before any call to `EndAwait()`, when 0 normally appears to mean "this is the initial entry point". I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however. Here's a very simple piece of sample code: ``` using System.Threading.Tasks; class Test { static async Task<int> Sum(Task<int> t1, Task<int> t2) { return await t1 + await t2; } } ``` ... and here's the code which gets generated for the `MoveNext()` method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names: ``` public void MoveNext() { try { this.$__doFinallyBodies = true; switch (this.<>1__state) { case 1: break; case 2: goto Label_00DA; case -1: return; default: this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; break; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); this.<a2>t__$await4 = this.t2.GetAwaiter<int>(); this.<>1__state = 2; this.$__doFinallyBodies = false; if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; Label_00DA: this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); this.<>1__state = -1; this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3); } catch (Exception exception) { this.<>1__state = -1; this.$builder.SetException(exception); } } ``` It's long, but the important lines for this question are these: ``` // End of awaiting t1 this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); // End of awaiting t2 this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); ``` In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If `MoveNext()` were called again at this point (either directly or via `Dispose`) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and `MoveNext()` *isn't* called, the change in state is irrelevant. Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation? **Important disclaimer** Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)
2011/02/17
[ "https://Stackoverflow.com/questions/5027999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22656/" ]
Okay, I finally have a real answer. I sort of worked it out on my own, but only after Lucian Wischik from the VB part of the team confirmed that there really is a good reason for it. Many thanks to him - and please visit [his blog](https://learn.microsoft.com/en-us/archive/blogs/lucian/) (on [archive.org](https://web.archive.org/web/20160216063203/http://blogs.msdn.com:80/b/lucian)), which rocks. The value 0 here is only special because it's *not* a valid state which you might be in just before the `await` in a normal case. In particular, it's not a state which the state machine may end up testing for elsewhere. I believe that using any non-positive value would work just as well: -1 isn't used for this as it's *logically* incorrect, as -1 normally means "finished". I could argue that we're giving an extra meaning to state 0 at the moment, but ultimately it doesn't really matter. The point of this question was finding out why the state is being set at all. The value is relevant if the await ends in an exception which is caught. We can end up coming back to the same await statement again, but we *mustn't* be in the state meaning "I'm just about to come back from that await" as otherwise all kinds of code would be skipped. It's simplest to show this with an example. Note that I'm now using the second CTP, so the generated code is slightly different to that in the question. Here's the async method: ``` static async Task<int> FooAsync() { var t = new SimpleAwaitable(); for (int i = 0; i < 3; i++) { try { Console.WriteLine("In Try"); return await t; } catch (Exception) { Console.WriteLine("Trying again..."); } } return 0; } ``` Conceptually, the `SimpleAwaitable` can be any awaitable - maybe a task, maybe something else. For the purposes of my tests, it always returns false for `IsCompleted`, and throws an exception in `GetResult`. Here's the generated code for `MoveNext`: ``` public void MoveNext() { int returnValue; try { int num3 = state; if (num3 == 1) { goto Label_ContinuationPoint; } if (state == -1) { return; } t = new SimpleAwaitable(); i = 0; Label_ContinuationPoint: while (i < 3) { // Label_ContinuationPoint: should be here try { num3 = state; if (num3 != 1) { Console.WriteLine("In Try"); awaiter = t.GetAwaiter(); if (!awaiter.IsCompleted) { state = 1; awaiter.OnCompleted(MoveNextDelegate); return; } } else { state = 0; } int result = awaiter.GetResult(); awaiter = null; returnValue = result; goto Label_ReturnStatement; } catch (Exception) { Console.WriteLine("Trying again..."); } i++; } returnValue = 0; } catch (Exception exception) { state = -1; Builder.SetException(exception); return; } Label_ReturnStatement: state = -1; Builder.SetResult(returnValue); } ``` I had to move `Label_ContinuationPoint` to make it valid code - otherwise it's not in the scope of the `goto` statement - but that doesn't affect the answer. Think about what happens when `GetResult` throws its exception. We'll go through the catch block, increment `i`, and then loop round again (assuming `i` is still less than 3). We're still in whatever state we were before the `GetResult` call... but when we get inside the `try` block we *must* print "In Try" and call `GetAwaiter` again... and we'll only do that if state isn't 1. Without the `state = 0` assignment, it will use the existing awaiter and skip the `Console.WriteLine` call. It's a fairly tortuous bit of code to work through, but that just goes to show the kinds of thing that the team has to think about. I'm glad I'm not responsible for implementing this :)
if it was kept at 1 (first case) you would get a call to `EndAwait` without a call to `BeginAwait`. If it's kept at 2 (second case) you'd get the same result just on the other awaiter. I'm guessing that calling the BeginAwait returns false if it has be started already (a guess from my side) and keeps the original value to return at the EndAwait. If that's the case it would work correctly whereas if you set it to -1 you might have an uninitialized `this.<1>t__$await1` for the first case. This however assumes that BeginAwaiter won't actually start the action on any calls after the first and that it will return false in those cases. Starting would of course be unacceptable since it could have side effect or simply give a different result. It also assumpes that the EndAwaiter will always return the same value no matter how many times it's called and that is can be called when BeginAwait returns false (as per the above assumption) It would seem to be a guard against race conditions If we inline the statements where movenext is called by a different thread after the state = 0 in questions it woule look something like the below ``` this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate) this.<>1__state = 0; //second thread this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate) this.$__doFinallyBodies = true; this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); //other thread this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); ``` If the assumptions above are correct the there's some unneeded work done such as get sawiater and reassigning the same value to <1>t\_\_$await1. If the state was kept at 1 then the last part would in stead be: ``` //second thread //I suppose this un matched call to EndAwait will fail this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); ``` further if it was set to 2 the state machine would assume it already had gotten the value of the first action which would be untrue and a (potentially) unassigned variable would be used to calculate the result
5,027,999
Yesterday I was giving a talk about the new C# "async" feature, in particular delving into what the generated code looked like, and `the GetAwaiter()` / `BeginAwait()` / `EndAwait()` calls. We looked in some detail at the state machine generated by the C# compiler, and there were two aspects we couldn't understand: * Why the generated class contains a `Dispose()` method and a `$__disposing` variable, which never appear to be used (and the class doesn't implement `IDisposable`). * Why the internal `state` variable is set to 0 before any call to `EndAwait()`, when 0 normally appears to mean "this is the initial entry point". I suspect the first point could be answered by doing something more interesting within the async method, although if anyone has any further information I'd be glad to hear it. This question is more about the second point, however. Here's a very simple piece of sample code: ``` using System.Threading.Tasks; class Test { static async Task<int> Sum(Task<int> t1, Task<int> t2) { return await t1 + await t2; } } ``` ... and here's the code which gets generated for the `MoveNext()` method which implements the state machine. This is copied directly from Reflector - I haven't fixed up the unspeakable variable names: ``` public void MoveNext() { try { this.$__doFinallyBodies = true; switch (this.<>1__state) { case 1: break; case 2: goto Label_00DA; case -1: return; default: this.<a1>t__$await2 = this.t1.GetAwaiter<int>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; break; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); this.<a2>t__$await4 = this.t2.GetAwaiter<int>(); this.<>1__state = 2; this.$__doFinallyBodies = false; if (this.<a2>t__$await4.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; Label_00DA: this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); this.<>1__state = -1; this.$builder.SetResult(this.<1>t__$await1 + this.<2>t__$await3); } catch (Exception exception) { this.<>1__state = -1; this.$builder.SetException(exception); } } ``` It's long, but the important lines for this question are these: ``` // End of awaiting t1 this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); // End of awaiting t2 this.<>1__state = 0; this.<2>t__$await3 = this.<a2>t__$await4.EndAwait(); ``` In both cases the state is changed again afterwards before it's next obviously observed... so why set it to 0 at all? If `MoveNext()` were called again at this point (either directly or via `Dispose`) it would effectively start the async method again, which would be wholly inappropriate as far as I can tell... if and `MoveNext()` *isn't* called, the change in state is irrelevant. Is this simply a side-effect of the compiler reusing iterator block generation code for async, where it may have a more obvious explanation? **Important disclaimer** Obviously this is just a CTP compiler. I fully expect things to change before the final release - and possibly even before the next CTP release. This question is in no way trying to claim this is a flaw in the C# compiler or anything like that. I'm just trying to work out whether there's a subtle reason for this that I've missed :)
2011/02/17
[ "https://Stackoverflow.com/questions/5027999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22656/" ]
Okay, I finally have a real answer. I sort of worked it out on my own, but only after Lucian Wischik from the VB part of the team confirmed that there really is a good reason for it. Many thanks to him - and please visit [his blog](https://learn.microsoft.com/en-us/archive/blogs/lucian/) (on [archive.org](https://web.archive.org/web/20160216063203/http://blogs.msdn.com:80/b/lucian)), which rocks. The value 0 here is only special because it's *not* a valid state which you might be in just before the `await` in a normal case. In particular, it's not a state which the state machine may end up testing for elsewhere. I believe that using any non-positive value would work just as well: -1 isn't used for this as it's *logically* incorrect, as -1 normally means "finished". I could argue that we're giving an extra meaning to state 0 at the moment, but ultimately it doesn't really matter. The point of this question was finding out why the state is being set at all. The value is relevant if the await ends in an exception which is caught. We can end up coming back to the same await statement again, but we *mustn't* be in the state meaning "I'm just about to come back from that await" as otherwise all kinds of code would be skipped. It's simplest to show this with an example. Note that I'm now using the second CTP, so the generated code is slightly different to that in the question. Here's the async method: ``` static async Task<int> FooAsync() { var t = new SimpleAwaitable(); for (int i = 0; i < 3; i++) { try { Console.WriteLine("In Try"); return await t; } catch (Exception) { Console.WriteLine("Trying again..."); } } return 0; } ``` Conceptually, the `SimpleAwaitable` can be any awaitable - maybe a task, maybe something else. For the purposes of my tests, it always returns false for `IsCompleted`, and throws an exception in `GetResult`. Here's the generated code for `MoveNext`: ``` public void MoveNext() { int returnValue; try { int num3 = state; if (num3 == 1) { goto Label_ContinuationPoint; } if (state == -1) { return; } t = new SimpleAwaitable(); i = 0; Label_ContinuationPoint: while (i < 3) { // Label_ContinuationPoint: should be here try { num3 = state; if (num3 != 1) { Console.WriteLine("In Try"); awaiter = t.GetAwaiter(); if (!awaiter.IsCompleted) { state = 1; awaiter.OnCompleted(MoveNextDelegate); return; } } else { state = 0; } int result = awaiter.GetResult(); awaiter = null; returnValue = result; goto Label_ReturnStatement; } catch (Exception) { Console.WriteLine("Trying again..."); } i++; } returnValue = 0; } catch (Exception exception) { state = -1; Builder.SetException(exception); return; } Label_ReturnStatement: state = -1; Builder.SetResult(returnValue); } ``` I had to move `Label_ContinuationPoint` to make it valid code - otherwise it's not in the scope of the `goto` statement - but that doesn't affect the answer. Think about what happens when `GetResult` throws its exception. We'll go through the catch block, increment `i`, and then loop round again (assuming `i` is still less than 3). We're still in whatever state we were before the `GetResult` call... but when we get inside the `try` block we *must* print "In Try" and call `GetAwaiter` again... and we'll only do that if state isn't 1. Without the `state = 0` assignment, it will use the existing awaiter and skip the `Console.WriteLine` call. It's a fairly tortuous bit of code to work through, but that just goes to show the kinds of thing that the team has to think about. I'm glad I'm not responsible for implementing this :)
Explanation of actual states: possible states: * **0** Initialized (i think so) **or** waiting for end of operation * **>0** just called MoveNext, chosing next state * **-1** ended Is it possible that this implementation just wants to assure that if another Call to MoveNext from whereever happens (while waiting) it will reevaluate the whole state-chain again from the beginning, **to reevaluate results which could be in the mean time already outdated?**
71,624,954
So Currently, I am creating a modal that is centered in the middle of the page by position absolute. The problem is when I adjust my broswer height and only the height, it will push the modal up and touch the top of the screen and even go pass it. I just want to know how to stop that from helping. ``` .modal-container { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.7); z-index: 9; } ``` ``` .callLogForm__container { position: absolute; top: 0; left: 0; right: 0; bottom: 0; max-width: 55rem; max-height: 65rem; margin: auto; background-color: white; border-radius: 11px; display: flex; flex-direction: column; align-items: center; } ``` ``` Parent of modal-container <> {navRoutes.includes(location.pathname) ? <NavBar /> : null} <main className={ sideMenuRoutes.includes(location.pathname) ? "main-container flex-box" : "main-container" } > {sideMenuRoutes.includes(location.pathname) ? <Sidemenu /> : null} <Routes /> </main> <Modal /> </> ``` [![Problem One](https://i.stack.imgur.com/vUwWB.png)](https://i.stack.imgur.com/vUwWB.png) This is what is doing when I shrink the browswer's height and only the height.
2022/03/26
[ "https://Stackoverflow.com/questions/71624954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17159523/" ]
You could use viewport unit for the height. Viewport units are based on the dimensions of the viewport (width and height of the visible browser page, excluding toolbars, search bars). * vh - viewport height * vw - viewport width 1vh - 1% of viewport's height. So in your modal you can do something like, ``` .modal-container { ... height: 75vh; .... } ``` It will make sure that the height of the modal is always 75% of the screen's height. Also you wanna handle the overflowing scenario. So that the content inside the modal will always be visible to the user. Try this, ``` .modal-container { ... height: 75vh; overflow-y: auto .... } ``` You can also use "vw" (viewport width) to the modal container to control the width in the same way.
You can use the flex property to align content in the center of the model so it will automatically adjust the browser height. Please check the below example ``` .modal-container { position: absolute; width: 500px; margin: 0 auto; left: 0; right: 0; bottom: 0; top: 0; display: flex; align-items: center; justify-content: center; flex-flow: column wrap; background-color: #f00; } ``` <https://codepen.io/ashok-kannan-dev/pen/jOYBwRe>
36,603,715
I'm trying to concatenate two column values inside a list and respectively select all columns but all I can achieve is get a concatenated column inside list with no other existing columns data .As I loose other columns data inside list because I'm using `select` to concatenate . **Linq Query:** ``` data = data.Select(m => m.Name = m.Id + m.Place).ToList(); // m=>m kindoff with concatenation ``` I need data to be modified like column name `Name` will hold `Id+Place` and I get all columns data intact (`Place`,`Address`,etc) can be many more .
2016/04/13
[ "https://Stackoverflow.com/questions/36603715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3460734/" ]
Try something like this... ``` data = data.Select(m => new { Name = $"{m.Id} {m.Place}", // Edit to add string interpolation Place = m.Place, Address = m.Address, etc = m.etc }); ``` While you don't "need" to include a name for m.Place, m.Address, etc. (Visual Studio will name them appropriately based off the of the property name), I find that it's easier to read if you keep the syntax consistent.
Use `select new`: ``` var data2 = from c in data select new { Name = c.Id + " " + c.Place, Place = c.Place, Address = c.Address }; ``` Or: ``` var data3 = data.Select(c => new { c.Address, Name = string.Format("{0} {1}", c.Id, c.Place)}); ```
36,603,715
I'm trying to concatenate two column values inside a list and respectively select all columns but all I can achieve is get a concatenated column inside list with no other existing columns data .As I loose other columns data inside list because I'm using `select` to concatenate . **Linq Query:** ``` data = data.Select(m => m.Name = m.Id + m.Place).ToList(); // m=>m kindoff with concatenation ``` I need data to be modified like column name `Name` will hold `Id+Place` and I get all columns data intact (`Place`,`Address`,etc) can be many more .
2016/04/13
[ "https://Stackoverflow.com/questions/36603715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3460734/" ]
Assuming you want to update specific fields you could use the foreach clause. This will update the values in place without needing to call ToList as well. ``` data.ForEach(m => m.Name = m.Id + m.Place); ```
Use `select new`: ``` var data2 = from c in data select new { Name = c.Id + " " + c.Place, Place = c.Place, Address = c.Address }; ``` Or: ``` var data3 = data.Select(c => new { c.Address, Name = string.Format("{0} {1}", c.Id, c.Place)}); ```
36,603,715
I'm trying to concatenate two column values inside a list and respectively select all columns but all I can achieve is get a concatenated column inside list with no other existing columns data .As I loose other columns data inside list because I'm using `select` to concatenate . **Linq Query:** ``` data = data.Select(m => m.Name = m.Id + m.Place).ToList(); // m=>m kindoff with concatenation ``` I need data to be modified like column name `Name` will hold `Id+Place` and I get all columns data intact (`Place`,`Address`,etc) can be many more .
2016/04/13
[ "https://Stackoverflow.com/questions/36603715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3460734/" ]
Try something like this... ``` data = data.Select(m => new { Name = $"{m.Id} {m.Place}", // Edit to add string interpolation Place = m.Place, Address = m.Address, etc = m.etc }); ``` While you don't "need" to include a name for m.Place, m.Address, etc. (Visual Studio will name them appropriately based off the of the property name), I find that it's easier to read if you keep the syntax consistent.
There are already two answers which should work for you. But they give you a list of anonymous objects. The below will give a list of your custom class(*instead of anonymous object*) with the desired result. ``` var result = data.Select(m => new Category { Name = m.Name = m.Id + m.Place, Place = m.Place} ).ToList(); ``` Update `Category` with your class name (*the same class which data is a collection of* or a different DTO/View model with those property names).
36,603,715
I'm trying to concatenate two column values inside a list and respectively select all columns but all I can achieve is get a concatenated column inside list with no other existing columns data .As I loose other columns data inside list because I'm using `select` to concatenate . **Linq Query:** ``` data = data.Select(m => m.Name = m.Id + m.Place).ToList(); // m=>m kindoff with concatenation ``` I need data to be modified like column name `Name` will hold `Id+Place` and I get all columns data intact (`Place`,`Address`,etc) can be many more .
2016/04/13
[ "https://Stackoverflow.com/questions/36603715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3460734/" ]
Assuming you want to update specific fields you could use the foreach clause. This will update the values in place without needing to call ToList as well. ``` data.ForEach(m => m.Name = m.Id + m.Place); ```
There are already two answers which should work for you. But they give you a list of anonymous objects. The below will give a list of your custom class(*instead of anonymous object*) with the desired result. ``` var result = data.Select(m => new Category { Name = m.Name = m.Id + m.Place, Place = m.Place} ).ToList(); ``` Update `Category` with your class name (*the same class which data is a collection of* or a different DTO/View model with those property names).
25,177,004
I was hoping this would be really simple in angular. I have an list with translators and other users ``` [{user: 'a',languages:['french','english','spanish']}, {user: 'b'}] ``` I then have an ng-repeat where I only want to display the users who have languages ``` ng-repeat="translator in users | filter: {languages}" ``` but unfortunately, I can't seem to figure out how to filter by the existence of an attribute. I've tried all manner of ``` {languages:'!undefined'} {languages.length > 0} {languages.length:'!0'} ``` I don't want to have to write an external filter for this as I'm sure it's possible in angular, I'm just not able to get the lingo right.
2014/08/07
[ "https://Stackoverflow.com/questions/25177004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48067/" ]
``` <div ng-repeat="translator in users | filter : { languages : '!!' }"> ``` Explanation: ------------ Consider a list as below: ``` $scope.items = [ { propertyOne: 'a', propertyTwo: 'hello' }, { propertyOne: 'b', propertyTwo: null }, { propertyOne: 'c', propertyTwo: undefined }, { propertyOne: 'd' } ]; ``` `'!!'` filters out objects having a certain property or objects having a certain property that is not undefined or null: ``` <div ng-repeat="item in items | filter : { propertyTwo : '!!' }"> {{item.propertyOne}} </div> <!-- outputs: a --> ``` `'!'` filters out objects not having certain property or objects having a certain property that is undefined or null: ``` <div ng-repeat="item in items | filter : { propertyTwo : '!' }"> {{item.propertyOne}} </div> <!-- outputs: b c d --> ``` **[Plnkr](http://plnkr.co/edit/EEokRlO2GoEgvge6iBAC?p=preview)** Note: It does not work for properties with values like 0, false or empty string(''). EDIT: previous answer was different from the plunkr example. I fixed them by swapping '!!' and '!'.
Controller: ``` var app = angular.module('app',[]); app.controller('ctrl', function($scope) { $scope.hasLanguage = function(user) { return user.hasOwnProperty('languages'); } }); ``` HTML: ``` ng-repeat="translator in users | filter: hasLanguage" ```
11,968,403
I want to show current date and time in my c++ program. I did this simply by these lines of code: ``` char date[9], time[9]; _strdate( date ); _strtime( time ); cout << "Current date and time: " << date << " " << time << endl; ``` This perfectly worked in MS Visual C++ 2010 and Dev C++ 4.9.9.2. But this doesn't work in Xcode! It says that I'm using undeclared identifiers 'strdate' and 'strtime'. I have included *iostream* and *ctime* libraries, but this didn't help. What's the problem? Thanks in advance.
2012/08/15
[ "https://Stackoverflow.com/questions/11968403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570812/" ]
These functions are not part of standard C++; they are Microsoft-specific extensions, and thus may not be available everywhere. For similar functionality, you may try combining `time`, `localtime` and `strftime`.
The function you are looking for is [`strftime`](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strftime.3.html).
11,968,403
I want to show current date and time in my c++ program. I did this simply by these lines of code: ``` char date[9], time[9]; _strdate( date ); _strtime( time ); cout << "Current date and time: " << date << " " << time << endl; ``` This perfectly worked in MS Visual C++ 2010 and Dev C++ 4.9.9.2. But this doesn't work in Xcode! It says that I'm using undeclared identifiers 'strdate' and 'strtime'. I have included *iostream* and *ctime* libraries, but this didn't help. What's the problem? Thanks in advance.
2012/08/15
[ "https://Stackoverflow.com/questions/11968403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570812/" ]
``` std::string _strdate_alternative() { char cptime[50]; time_t now = time(NULL); strftime(cptime, 50, "%b. %d, %Y", localtime(&now)); //short month name return std::string(cptime); } ``` As said before, there is no such function in standard c/c++ library. You can use this alternative. Code is based on some info found on the Internet. I didn't compile it.
These functions are not part of standard C++; they are Microsoft-specific extensions, and thus may not be available everywhere. For similar functionality, you may try combining `time`, `localtime` and `strftime`.
11,968,403
I want to show current date and time in my c++ program. I did this simply by these lines of code: ``` char date[9], time[9]; _strdate( date ); _strtime( time ); cout << "Current date and time: " << date << " " << time << endl; ``` This perfectly worked in MS Visual C++ 2010 and Dev C++ 4.9.9.2. But this doesn't work in Xcode! It says that I'm using undeclared identifiers 'strdate' and 'strtime'. I have included *iostream* and *ctime* libraries, but this didn't help. What's the problem? Thanks in advance.
2012/08/15
[ "https://Stackoverflow.com/questions/11968403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570812/" ]
``` std::string _strdate_alternative() { char cptime[50]; time_t now = time(NULL); strftime(cptime, 50, "%b. %d, %Y", localtime(&now)); //short month name return std::string(cptime); } ``` As said before, there is no such function in standard c/c++ library. You can use this alternative. Code is based on some info found on the Internet. I didn't compile it.
The function you are looking for is [`strftime`](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strftime.3.html).
2,496,512
Let $exp(k)$ be the exponential distribution, $k>0$. Then it has density $$ f(x)= \begin{cases} ke^{-kx} & \text{ if } 0\leq x < \infty\\ 0 &\text{otherwise} \end{cases} $$ I want to find the convolution of $n$ exponential distributions. For $n=2$ I have $$ \int\_{\mathbb{R}} f(x-t)f(t) dt =\int\_0^x (k e^{-k(x-t)}ke^{-kt}) dt=\int\_0^x k^2e^{-kx} dt=k^2e^{-kx} \int\_0^x dt= k^2xe^{-kx}. $$ For $n \geq 3$ I would like to take convolutions inductively, but I am not even sure what my inductive hypothesis would be. Some help?
2017/10/30
[ "https://math.stackexchange.com/questions/2496512", "https://math.stackexchange.com", "https://math.stackexchange.com/users/104220/" ]
For $n=2$, you found that $$f\_2(x)=k^2x^{2-1}e^{-kx}$$ The tricky part is that actually there is also a hidden $1/(2-1)!=1$. (you couldn't have known that, unless you calculated also the $n=3$ case). So, the inductive hypothesis for $n\ge 3$: $$f\_n(x)=\frac{1}{(n-1)!}k^{n}x^{n-1}e^{-kx}$$ for $0\le x<+\infty$ and $f\_n(x)=0$ otherwise. This is the [Erlang distribution](https://en.wikipedia.org/wiki/Erlang_distribution) (or a particular instance of the Gamma distribution) with parameters: shape $n$ and rate $k$.
We have that for a R.V. $X$ exponentially distributed that it´s density function is given by: $$ \\ f\_X(x)=\begin{cases} \lambda e^{-\lambda x} & x\geq 0\\ 0 & x<0 \end{cases} $$ Define $S\_n=\sum\_{k=1}^n X\_k$. Then, as You have already shown, the sum of two exponential R.V´s has density $$ \begin{aligned} f\_{S\_2}&=f\_{X\_1+X\_2}(t)\\ &=\int\_0^t \lambda e^{-\lambda(t-s)}\lambda e^{-\lambda s} \,ds\\ &=\lambda^2 e^{-\lambda t}\int\_0^t \,ds\\ &=\lambda^2 t e^{-\lambda t} \qquad \blacksquare \end{aligned} $$ For the sum of three R.V´s $$ \begin{aligned} f\_{X\_1+X\_2+X\_3}(t)&=f\_{S\_2+X\_3}(t)\\ &=\int\_{-\infty}^\infty f\_{S\_2}(t-s)f\_{X\_3}(s)\,ds \\ &=\int\_{-\infty}^\infty f\_{X\_3}(t-s)f\_{S\_2}(s)\,ds \\ &=\int\_0^t \lambda e^{-\lambda(t-s)}\lambda^2 s\, e^{-\lambda s} \,ds\\ &=\lambda^3 e^{-\lambda t}\int\_0^t s \,ds\\ &=\frac{\lambda^3 t^2 e^{-\lambda t}}{2!} \qquad \blacksquare \end{aligned} $$ Where we used the result for $f\_{S\_2}=\lambda^2 t e^{-\lambda t}$ and that $F\_1\*F\_2=F\_2\*F\_1$. For the sum of four R.V´s we have: $$ \begin{aligned} f\_{X\_1+X\_2+X\_3+X\_4}(t)&=f\_{S\_3+X\_4}(t)\\ &=\int\_{-\infty}^\infty f\_{S\_3}(t-s)f\_{X\_4}(s)\,ds \\ &=\int\_{-\infty}^\infty f\_{X\_4}(t-s)f\_{S\_3}(s)\,ds \\ &=\int\_0^t \lambda e^{-\lambda(t-s)} \frac{\lambda^3 s^2\, e^{-\lambda s} }{2!}\,ds\\ &=\frac{\lambda^4 e^{-\lambda t}}{2!}\int\_0^t s^2 \,ds\\ &=\frac{\lambda^4 t^3 e^{-\lambda t}}{3!} \qquad \blacksquare \end{aligned} $$ Can you see a pattern emerging? --- Claim: ------ $$f\_{S\_n}(t)=f\_{X\_1+\cdots+X\_n}(t)=\frac{\lambda^n t^{n-1}\,e^{-\lambda t}}{(n-1)!}$$ ### Proof: Assume that $$f\_{S\_{n-1}}(t)=f\_{X\_1+\cdots+X\_{n-1}}(t)=\frac{\lambda^{n-1} t^{n-2}\,e^{-\lambda t}}{(n-2)!}$$ Than $$ \begin{aligned} f\_{S\_{n}}(t)&=f\_{X\_1+\cdots+X\_n}(t)\\ &=f\_{S\_{n-1}+X\_n}(t)\\ &=\int\_{-\infty}^\infty f\_{S\_{n-1}}(t-s)f\_{X\_n}(s)\,ds \\ &=\int\_{-\infty}^\infty f\_{X\_n}(t-s)f\_{S\_{n-1}}(s)\,ds \\ &=\int\_0^t \lambda e^{-\lambda(t-s)} \frac{\lambda^{n-1} s^{n-2}\, e^{-\lambda s} }{(n-2)!}\,ds\\ &=\frac{\lambda^n e^{-\lambda t}}{(n-2)!}\int\_0^t s^{n-2} \,ds\\ &=\frac{\lambda^n t^{n-1} e^{-\lambda t}}{(n-1)!} \\ &=\frac{\lambda^n t^{n-1} e^{-\lambda t}}{\Gamma(n)} \qquad \blacksquare \end{aligned} $$
276,347
I am not a techie but using ubuntu for the last 3 years now I have a question to ask...I am translating a book so I need two screens opening at the same time one opening into the pdf file from the pc other opening into the web for researching side by side I went thru the web but could not find an answer help me my ubuntu version is 12.10
2013/03/31
[ "https://askubuntu.com/questions/276347", "https://askubuntu.com", "https://askubuntu.com/users/145668/" ]
If you have a additional monitor, then you can connect it to the CPU/Laptop with a VGA cable. Then in your Ubuntu system, * Open “**System Settings**” from “**Dash Home**” and there select “**Displays**”. * If your monitor does not appear there, click on “**Detect Displays**”. Now you’ll see two monitors. ![](https://i.stack.imgur.com/fYU1Q.jpg) * According to the position of monitors on the table, arrange their positions on the screen by drag and drop. * Select each monitor, enable it by “**on-off**” and change its resolution to its actual resolution. Also uncheck “**Mirror displays**” box which is for duplicating the main screen. And finally click on “**Apply**”.
Just don't maximize your applications. Make them half screen-width and position the windows beside each other.
13,826,881
What I want is when add a element is clicked all the elements in div with `class="clLeft"` is copied in div with `class="clRow"`. ``` <div class="clRow" > <div class="clLeft"> <label >Question Type </label> <select name="selquetypen" class="clsvtext clsvtextempty" id="selquetype"> <option value="-">Question Type</option> <option value="1">MCQ</option> <option value="2">True/False</option> </select> <a id="adddivcleft">add</a> </div> </div> ```
2012/12/11
[ "https://Stackoverflow.com/questions/13826881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180150/" ]
I think it would be best to split the code into Subs. The table you loop through would have a *Sub-Name* field and a *blnSuccess* field. Your code would loop though the table running each sub and then updating *blnSuccess* based on any errors you receive. This would give you queryable result set when you try to see what happened.
Consider using macros. You shouldn't need a table. Also, consider moving your hard-coded SQL to queries.
13,826,881
What I want is when add a element is clicked all the elements in div with `class="clLeft"` is copied in div with `class="clRow"`. ``` <div class="clRow" > <div class="clLeft"> <label >Question Type </label> <select name="selquetypen" class="clsvtext clsvtextempty" id="selquetype"> <option value="-">Question Type</option> <option value="1">MCQ</option> <option value="2">True/False</option> </select> <a id="adddivcleft">add</a> </div> </div> ```
2012/12/11
[ "https://Stackoverflow.com/questions/13826881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180150/" ]
I think it would be best to split the code into Subs. The table you loop through would have a *Sub-Name* field and a *blnSuccess* field. Your code would loop though the table running each sub and then updating *blnSuccess* based on any errors you receive. This would give you queryable result set when you try to see what happened.
I think that you shouldn't use a table, just create a module with different subs for each operation. On your button event, after the combo selections, I would do a case statement. ``` dim strOperation as string strOperation = me!selectionOne Select Case strOperation Case "delete": deleteTable(me!selectionTwo) Case "export": export(me!selectionTwo) case "acquire": acquire(me!selectionTwo) End Select ``` Of course, you'd have your acquire, delete, and export methods written in a module and have whatever parameters you need for each operation there. This is just one idea of many that you could use to approach this.
13,826,881
What I want is when add a element is clicked all the elements in div with `class="clLeft"` is copied in div with `class="clRow"`. ``` <div class="clRow" > <div class="clLeft"> <label >Question Type </label> <select name="selquetypen" class="clsvtext clsvtextempty" id="selquetype"> <option value="-">Question Type</option> <option value="1">MCQ</option> <option value="2">True/False</option> </select> <a id="adddivcleft">add</a> </div> </div> ```
2012/12/11
[ "https://Stackoverflow.com/questions/13826881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180150/" ]
I think it would be best to split the code into Subs. The table you loop through would have a *Sub-Name* field and a *blnSuccess* field. Your code would loop though the table running each sub and then updating *blnSuccess* based on any errors you receive. This would give you queryable result set when you try to see what happened.
I was going to edit the original answer but this seems to be off on a different tack.... I think it would be best to split the code into functions that return a string if there is an error. The table you loop through would have a *strFunction,strError* and *strObject* fields. Your code would loop though the table running each function based on the case statement while passing the *strObject* as a string and then updating *strError* based on any errors you receive. You could query the table after this process to see which records have errors in them. If the button is called cmdRunAll here is the code for it. ``` Private Sub cmdRunAll_Click() On Error GoTo ErrHandler Dim rst As DAO.Recordset Set rst = CurrentDb.OpenRecordset("tblCode", dbOpenDynaset, dbSeeChanges) If Not rst.EOF Then With rst .MoveFirst Do While Not .EOF .Edit Select Case !strFunction Case "fExport" !strError = fExport(!strObject) End Select .Update .MoveNext Loop End With End If rst.Close Set rst = Nothing MsgBox "Processes complete" Exit Sub ErrHandler: Debug.Print Err.Description & " cmdRunAll_Click " & Me.Name Resume Next End Sub ``` Here is a simple sample function ``` Public Function fExport(strTable As String) As String On Error GoTo ErrHandler Dim strError As String strError = "" DoCmd.TransferText acExportDelim, , strTable, "C:\users\IusedMyUserNameHere\" & strTable & ".txt" fExport = strError Exit Function ErrHandler: strError = Err.Description Resume Next End Function ```
13,826,881
What I want is when add a element is clicked all the elements in div with `class="clLeft"` is copied in div with `class="clRow"`. ``` <div class="clRow" > <div class="clLeft"> <label >Question Type </label> <select name="selquetypen" class="clsvtext clsvtextempty" id="selquetype"> <option value="-">Question Type</option> <option value="1">MCQ</option> <option value="2">True/False</option> </select> <a id="adddivcleft">add</a> </div> </div> ```
2012/12/11
[ "https://Stackoverflow.com/questions/13826881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180150/" ]
Consider using macros. You shouldn't need a table. Also, consider moving your hard-coded SQL to queries.
I was going to edit the original answer but this seems to be off on a different tack.... I think it would be best to split the code into functions that return a string if there is an error. The table you loop through would have a *strFunction,strError* and *strObject* fields. Your code would loop though the table running each function based on the case statement while passing the *strObject* as a string and then updating *strError* based on any errors you receive. You could query the table after this process to see which records have errors in them. If the button is called cmdRunAll here is the code for it. ``` Private Sub cmdRunAll_Click() On Error GoTo ErrHandler Dim rst As DAO.Recordset Set rst = CurrentDb.OpenRecordset("tblCode", dbOpenDynaset, dbSeeChanges) If Not rst.EOF Then With rst .MoveFirst Do While Not .EOF .Edit Select Case !strFunction Case "fExport" !strError = fExport(!strObject) End Select .Update .MoveNext Loop End With End If rst.Close Set rst = Nothing MsgBox "Processes complete" Exit Sub ErrHandler: Debug.Print Err.Description & " cmdRunAll_Click " & Me.Name Resume Next End Sub ``` Here is a simple sample function ``` Public Function fExport(strTable As String) As String On Error GoTo ErrHandler Dim strError As String strError = "" DoCmd.TransferText acExportDelim, , strTable, "C:\users\IusedMyUserNameHere\" & strTable & ".txt" fExport = strError Exit Function ErrHandler: strError = Err.Description Resume Next End Function ```
13,826,881
What I want is when add a element is clicked all the elements in div with `class="clLeft"` is copied in div with `class="clRow"`. ``` <div class="clRow" > <div class="clLeft"> <label >Question Type </label> <select name="selquetypen" class="clsvtext clsvtextempty" id="selquetype"> <option value="-">Question Type</option> <option value="1">MCQ</option> <option value="2">True/False</option> </select> <a id="adddivcleft">add</a> </div> </div> ```
2012/12/11
[ "https://Stackoverflow.com/questions/13826881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180150/" ]
I think that you shouldn't use a table, just create a module with different subs for each operation. On your button event, after the combo selections, I would do a case statement. ``` dim strOperation as string strOperation = me!selectionOne Select Case strOperation Case "delete": deleteTable(me!selectionTwo) Case "export": export(me!selectionTwo) case "acquire": acquire(me!selectionTwo) End Select ``` Of course, you'd have your acquire, delete, and export methods written in a module and have whatever parameters you need for each operation there. This is just one idea of many that you could use to approach this.
I was going to edit the original answer but this seems to be off on a different tack.... I think it would be best to split the code into functions that return a string if there is an error. The table you loop through would have a *strFunction,strError* and *strObject* fields. Your code would loop though the table running each function based on the case statement while passing the *strObject* as a string and then updating *strError* based on any errors you receive. You could query the table after this process to see which records have errors in them. If the button is called cmdRunAll here is the code for it. ``` Private Sub cmdRunAll_Click() On Error GoTo ErrHandler Dim rst As DAO.Recordset Set rst = CurrentDb.OpenRecordset("tblCode", dbOpenDynaset, dbSeeChanges) If Not rst.EOF Then With rst .MoveFirst Do While Not .EOF .Edit Select Case !strFunction Case "fExport" !strError = fExport(!strObject) End Select .Update .MoveNext Loop End With End If rst.Close Set rst = Nothing MsgBox "Processes complete" Exit Sub ErrHandler: Debug.Print Err.Description & " cmdRunAll_Click " & Me.Name Resume Next End Sub ``` Here is a simple sample function ``` Public Function fExport(strTable As String) As String On Error GoTo ErrHandler Dim strError As String strError = "" DoCmd.TransferText acExportDelim, , strTable, "C:\users\IusedMyUserNameHere\" & strTable & ".txt" fExport = strError Exit Function ErrHandler: strError = Err.Description Resume Next End Function ```
30,601
Do items with [Magic Find](http://diablo2.diablowiki.net/Magic_Find) bonuses (such as [topaz socketed helms](http://diablo2.diablowiki.net/Magic_Find#Magic_Find_Equipment)) increase rune and gem drop rates?
2011/09/17
[ "https://gaming.stackexchange.com/questions/30601", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/121/" ]
No, they do not affect runes or gems. [So sayeth the Arreat Summit](http://classic.battle.net/diablo2exp/items/magic/magicfind.shtml): > > What exactly are "Magic Items" > > > Magic Items in this definition include > Magic Items, Set Items, Unique Items and Rare Items. > > >
No, magic find has no affect at all on [rune drops](http://diablo2.diablowiki.net/Rune_hunting). You are just as likely to get an Ist from a countess with 0% mf and 400% mf. I do not know if MF has an effect on gems, I don't think this has been looked in to in as much detail as gems are fairly common, especially by doing the forge quest or farming the secret cow level.
30,601
Do items with [Magic Find](http://diablo2.diablowiki.net/Magic_Find) bonuses (such as [topaz socketed helms](http://diablo2.diablowiki.net/Magic_Find#Magic_Find_Equipment)) increase rune and gem drop rates?
2011/09/17
[ "https://gaming.stackexchange.com/questions/30601", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/121/" ]
No, they do not affect runes or gems. [So sayeth the Arreat Summit](http://classic.battle.net/diablo2exp/items/magic/magicfind.shtml): > > What exactly are "Magic Items" > > > Magic Items in this definition include > Magic Items, Set Items, Unique Items and Rare Items. > > >
Magic find only affects what "color" an item is, after it is already determined what kind of item is to be dropped. Therefore, it cannot increase the chance that you get runes, gems, rings, amulets, charms, or whatever else. Those will drop completely randomly, based only on the drop tables. Once an item that can have color (blue = magic, yellow = rare, green = set, gold = unique) is determined to have dropped, *then* magic find comes into play and helps determine what color that item should be. More magic find will skew the item results more towards the gold end of the spectrum.
11,609,480
My application is a Windows Forms one. I tried using the windows wallpaper, but this depends on the "Fill", "Stretch", "Fit" or "Tile" settings. I just need the image as it is on the desktop, but including the part "under" the taskbar, because this part is visible in case of transparent taskbar. Why I need this? Because I have a tray application which slides from under the taskbar when opening. And I need to set a mask there, so it can't be seen sliding, until it reaches the top of the taskbar. Again, this is only a problem when the taskbar is transparent.
2012/07/23
[ "https://Stackoverflow.com/questions/11609480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521446/" ]
You need to cast the bit field to an integer. ``` mysql> select hasMultipleColors+0 from pumps where id = 1; ``` This is because of a bug, see: <http://bugs.mysql.com/bug.php?id=43670>. The status says: Won't fix.
You need to perform a conversion as `bit 1` is not printable. `SELECT hasMultipleColors+0 from pumps where id = 1;` See more here: <http://dev.mysql.com/doc/refman/5.0/en/bit-field-literals.html>
11,609,480
My application is a Windows Forms one. I tried using the windows wallpaper, but this depends on the "Fill", "Stretch", "Fit" or "Tile" settings. I just need the image as it is on the desktop, but including the part "under" the taskbar, because this part is visible in case of transparent taskbar. Why I need this? Because I have a tray application which slides from under the taskbar when opening. And I need to set a mask there, so it can't be seen sliding, until it reaches the top of the taskbar. Again, this is only a problem when the taskbar is transparent.
2012/07/23
[ "https://Stackoverflow.com/questions/11609480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521446/" ]
You need to perform a conversion as `bit 1` is not printable. `SELECT hasMultipleColors+0 from pumps where id = 1;` See more here: <http://dev.mysql.com/doc/refman/5.0/en/bit-field-literals.html>
The actual reason for the effect you see, is that it's done right and as expected. The `bit` field has bits and thus return bits, and trying to output a single bit as a character will show the character with the given bit-value – in this case a zero-width control character. Some software may handle this automagically, but for command line MySQL you'll have to cast it as int in some way (e.g. by adding zero). In languages like PHP the ordinal value of the character will give you the right value, using the `ord()` function (though to be really proper, it would have to be converted from decimal to binary string, to work for bit fields longer than one character). **EDIT:** Found a quite old source saying that it changed, so a MySQL upgrade might make everything work more as expected: <http://gphemsley.wordpress.com/2010/02/08/php-mysql-and-the-bit-field-type/>
11,609,480
My application is a Windows Forms one. I tried using the windows wallpaper, but this depends on the "Fill", "Stretch", "Fit" or "Tile" settings. I just need the image as it is on the desktop, but including the part "under" the taskbar, because this part is visible in case of transparent taskbar. Why I need this? Because I have a tray application which slides from under the taskbar when opening. And I need to set a mask there, so it can't be seen sliding, until it reaches the top of the taskbar. Again, this is only a problem when the taskbar is transparent.
2012/07/23
[ "https://Stackoverflow.com/questions/11609480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521446/" ]
You need to cast the bit field to an integer. ``` mysql> select hasMultipleColors+0 from pumps where id = 1; ``` This is because of a bug, see: <http://bugs.mysql.com/bug.php?id=43670>. The status says: Won't fix.
The actual reason for the effect you see, is that it's done right and as expected. The `bit` field has bits and thus return bits, and trying to output a single bit as a character will show the character with the given bit-value – in this case a zero-width control character. Some software may handle this automagically, but for command line MySQL you'll have to cast it as int in some way (e.g. by adding zero). In languages like PHP the ordinal value of the character will give you the right value, using the `ord()` function (though to be really proper, it would have to be converted from decimal to binary string, to work for bit fields longer than one character). **EDIT:** Found a quite old source saying that it changed, so a MySQL upgrade might make everything work more as expected: <http://gphemsley.wordpress.com/2010/02/08/php-mysql-and-the-bit-field-type/>
11,609,480
My application is a Windows Forms one. I tried using the windows wallpaper, but this depends on the "Fill", "Stretch", "Fit" or "Tile" settings. I just need the image as it is on the desktop, but including the part "under" the taskbar, because this part is visible in case of transparent taskbar. Why I need this? Because I have a tray application which slides from under the taskbar when opening. And I need to set a mask there, so it can't be seen sliding, until it reaches the top of the taskbar. Again, this is only a problem when the taskbar is transparent.
2012/07/23
[ "https://Stackoverflow.com/questions/11609480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521446/" ]
You need to cast the bit field to an integer. ``` mysql> select hasMultipleColors+0 from pumps where id = 1; ``` This is because of a bug, see: <http://bugs.mysql.com/bug.php?id=43670>. The status says: Won't fix.
You can cast BIT field to unsigned. ``` SELECT CAST(hasMultipleColors AS UNSIGNED) AS hasMultipleColors FROM pumps WHERE id = 1 ``` It will return 1 or 0 based on the value of `hasMultipleColors`.
11,609,480
My application is a Windows Forms one. I tried using the windows wallpaper, but this depends on the "Fill", "Stretch", "Fit" or "Tile" settings. I just need the image as it is on the desktop, but including the part "under" the taskbar, because this part is visible in case of transparent taskbar. Why I need this? Because I have a tray application which slides from under the taskbar when opening. And I need to set a mask there, so it can't be seen sliding, until it reaches the top of the taskbar. Again, this is only a problem when the taskbar is transparent.
2012/07/23
[ "https://Stackoverflow.com/questions/11609480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521446/" ]
You can cast BIT field to unsigned. ``` SELECT CAST(hasMultipleColors AS UNSIGNED) AS hasMultipleColors FROM pumps WHERE id = 1 ``` It will return 1 or 0 based on the value of `hasMultipleColors`.
The actual reason for the effect you see, is that it's done right and as expected. The `bit` field has bits and thus return bits, and trying to output a single bit as a character will show the character with the given bit-value – in this case a zero-width control character. Some software may handle this automagically, but for command line MySQL you'll have to cast it as int in some way (e.g. by adding zero). In languages like PHP the ordinal value of the character will give you the right value, using the `ord()` function (though to be really proper, it would have to be converted from decimal to binary string, to work for bit fields longer than one character). **EDIT:** Found a quite old source saying that it changed, so a MySQL upgrade might make everything work more as expected: <http://gphemsley.wordpress.com/2010/02/08/php-mysql-and-the-bit-field-type/>
39,521,243
I just can't get QtConcurrent::run working with an overloaded static method: ``` class Foobar { public: static ResType foo(const cv::Mat& data, const QStringList& names, int clusters = 5); static ResType foo(const cv::Mat& data, const cv::TermCriteria& tc, const QStringList& names, const QStringList& otherNames, int clusters, int covType = 2); } QtConcurrent::run( static_cast<ResType (*)(const cv::Mat&, const cv::TermCriteria&, const QStringList&, const QStringList&, int, int)>(&Foobar::foo), sampleData, tc, mDimNames, mGmmNames, mClusterN, mCovType); ``` I get: > > error: no matching function for call to ‘run(ResType (\*)(const cv::Mat&, const cv::TermCriteria&, const QStringList&, const QStringList&, int, int), cv::Mat&, cv::TermCriteria&, QStringList&, QStringList&, int&, int&)’ > sampleData, tc, mDimNames, mGmmNames, mClusterN, mCovType); > > > Note the ref (&) in the error message for the integer parameters. This baffles me.... Types of params: ``` cv::Mat sampleData, cv::TermCriteria tc, QStringList mDimNames, QStringList mGmmNames, int mClusterN, int mCovType ``` I thought the static\_cast would help with distinguishing the overloads. The only difference I can see is, that the params are partly not const. But you can take a const ref of a Value type param, so why would that matter...
2016/09/15
[ "https://Stackoverflow.com/questions/39521243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/768656/" ]
The answer is that static member function type is a regular function, not a member function, because it doesn't have the implicit `this`, so removing the `Foobar::` part before `*` should since the compilation issue. Edit: After the question edition and the answer added by OP, I want to mention that `std::bind` is not a great solution. It's very error-prone, especially around the "get by ref" which easily becomes a copy if you are not very careful. The better solution is to use a lambda instead. E.g: ``` auto future = QtConcurrent::run([&]{ DkGmm::fromData(sampleData, tc, mDimNames, mGmmNames, mClusterN, mCovType); }); ``` (In the actual code, I'd probably capture each of the arguments explicitly, as I think that using the default capturing is Bad Practice™.)
std::bind to the rescue. For some reason, it can figure out the right type: ``` #include <functional> void test() { auto fn = std::bind( static_cast<DkGmm (*)(const cv::Mat&, const cv::TermCriteria&, const QStringList&, const QStringList&, int, int)>(&DkGmm::fromData), sampleData, tc, mDimNames, mGmmNames, mClusterN, mCovType); auto future = QtConcurrent::run(fn); // ...code... } ```
18,259,228
I'm not sure if this is possible ... but I'd like to use the autoComplete component, where the value attribute is of type String and where the completeMethod returns a List of some heavy object. It is also a requirement for me to use `forceSelection="false"` This is what I think should work (but doesn't): ``` <p:autoComplete id="it_demandeur" value="#{utilisateurDemandeurCtrl.critereRechercheDemandeur}" var="demandeurItem" itemLabel="#{demandeurItem ne null ? demandeurItem.numeroOW.toString().concat(' - ').concat(demandeurItem.nom) : ''}" itemValue="#{demandeurItem.nom}" completeMethod="#{utilisateurDemandeurCtrl.completeDemandeur}" minQueryLength="3" cacheTimeout="10000"> <p:column> #{demandeurItem.numeroOW} - #{demandeurItem.nom} </p:column> </p:autoComplete> ``` This is the method that returns the list of suggestions: ``` @SuppressWarnings("unchecked") public List<Demandeur> completeDemandeur(String query) { StringBuilder jpql = new StringBuilder(128); jpql.append("SELECT d"); jpql.append(" FROM Demandeur d"); jpql.append(" WHERE UPPER(d.nom) LIKE :query"); jpql.append(" OR d.numeroOW LIKE :query"); Query demandeurQuery = em.createQuery(jpql.toString()); demandeurQuery.setParameter("query", "%" + query.toUpperCase() + "%"); return (List<Demandeur>) demandeurQuery.getResultList(); } ``` If the user selects a suggestion, it would set the itemValue to the name of the selected suggestion, but display a concatenated string of 2 values from the Demandeur object. The suggestions do appear and I can select them, but unfortunely, I get this error when submitting the page: ``` Exception message: /page/utilisateur.xhtml at line 27 and column 50 itemLabel="#{demandeurItem ne null ? demandeurItem.numeroOW.toString().concat(' - ').concat(demandeurItem.nom) : ''}": Property 'numeroOW' not found on type java.lang.String ``` My understanding is that the var attribute of the autoComplete component is an iterator on the suggestions, so in my case of type Demandeur, not String. Any help would be appreciated! Thanks I am using primefaces 3.5.11, MyFaces implementation for JSF on Websphere 8.5.5.0 Edit: Here is the converter I tried with ``` @FacesConverter(value = "demandeurUIConverter") public class DemandeurConverter implements Serializable, Converter { private static final long serialVersionUID = 1L; @Override public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) throws ConverterException { if (value == null || value.length() == 0) { return null; } ConverterCtrl cc = EJB.lookup(ConverterCtrl.class); Demandeur d = cc.getDemandeurFromCle(value); if (d == null) { d = new Demandeur(); d.setNom(value); d.setNumeroOW(value); } return d; } @Override public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) throws ConverterException { if (value == null) { return ""; } Demandeur demandeur = (Demandeur) value; return demandeur.getNom(); } } ```
2013/08/15
[ "https://Stackoverflow.com/questions/18259228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524381/" ]
It would be very helpful if you could be a little more precise in the following areas: * Can the application survive if the background process gets terminated WHILE the main application is running? * Does the background process get terminated and begun multiple times WHILE the main application is running? * Do you have full internal control of the background process (ability to modify code in it)? * Do you have partial internal control of the background process (send commands to redirect, etc)? * Do you have external flow control of the background process (ability to start/stop)? Supposing based on your question that ... * The application **CANNOT** survive if the background process gets terminated WHILE the main application is running? * You **DO NOT** have full internal control of the background process (no ability to modify code in it) * You **DO NOT** have partial internal control of the background process (no ability to send commands to redirect) * You **DO** have external flow control of the background process (ability to start/stop) Then your only real solution is to have the client stop the main process, go to the background process and restart it manually. While this is less than ideal, it is an unfortunate reality when you don't have internal control of either the application or background process.
first of all why you are not using hostname? it seems that your app read the IP at startup and keep it without refreshing
112,191
yesterday I was shooting as a eventphotographer and suddenly my IR beam of the flash didn't work anymore. (Probably I changed some settings while talking with someone? Idk...) Some quick facts: * The flash is newer than 6 months old * Unfortunately I don't have the YN wireless device to update to the latest version * The IR flash works on an other (borrowed) Nikon Speedlight SB-600, so probably the camera settings are okay * In the extra menu settings under "C.n04" -> AF is on 0:ON.. My camera is the Nikon D7100. does anyone have some ideas to help me? Thank you very much, bernd
2019/09/22
[ "https://photo.stackexchange.com/questions/112191", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/87090/" ]
It's a Yongnuo, a/k/a a "disposable flash." Some last longer than others, but you should always have one more than you need with you when using them for a shoot. Eventually, you'll need the extra one.
Check your camera settings anyway, they have to be just right for AF Assist light to work. See D7100 manual page 233 about option A4, which has to be ON. And then it must be AF-S mode (or Single Servo if AF-A). And also, Center focus point selected in Single Point mode, or Auto Area mode. See page 233 to ensure they are still right.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
**A set number of Demon Seeds (and social issues):** These are solid answers, but I have a slightly different take. Since the demon places a seed in a new recruit, which expands over time, make each demon only able to generate a set number of seeds. This can be according to ability (people have 10 fingers, Demons have 20 seeds) or by agreement (treaty obligations say each coven can have no more than 30 members). It could even be by competition - Different covens COMPETE for the best new members, but are only allowed so many competitors in the competitions. Demons with big teams don't get the best players at draft time (so to speak) because they have emphasized quantity over quality. This could also be due to side-effects on society. Maybe the rulers don't like souls going to demons. Maybe there is a church out-competing demons for common souls, and only those with sufficient inherent power can break away. Maybe the witches children turn out mutated by Mana, and the human population was plummeting as a significant portion of the populus gave birth to monsters. Covens themselves may want to be exclusive (to concentrate their power) and if everyone has magic, the competition for (fill in the blank, Ley lines, spell components, special favors from demons) becomes too fierce and the strongest witches decided to eliminate the competition. Finally, these are DEMONS we're talking about. Perhaps all this warfare has given rise to a system where newly admitted members (acolytes) are not fully admitted until they have captured and sacrificed a rival coven's acolyte as an offering to their demon. New acolytes who aren't very good are going to get killed, and no one really WANTS to die at the hands of a rival gang - I mean, coven. This screens out witches who are afraid of death, or are unwilling to commit murder, and those who's magic isn't strong enough to compete with other acolytes. Covens don't want RIVAL covens to grow stronger, and selecting weaklings just feeds the membership of rival covens. Ruthless covens may even enter into arrangements together, so select acolytes are recruited purely as molech - offerings to be given to the other coven so chosen acolytes aren't at risk (this could even be punishment for poorly performing acolytes).
**The power curve for highly skilled witches is quadratic in nature.** A lowly acolyte witch is worth barely even enough to replace the power given with her soul. This will be our unit of measure, AP (acolyte power). So our lowly acolyte, works hard but doesn't manage to learn much and only becomes a tier 2 acolyte netting our demon 4 AP for his trouble. over the course of the acolytes life she may even have cost him more power from the spells she used. The demon gets a net increase of 2 or less based on how much the witch used minus his initial investment (1AP). Picking a high quality acolyte, that acolyte might become a tier 7 witch accumulating 49 AP! Assuming that the ratio to demon power spent in the lifetime to AP is about 1/2, after the initial investment of 1 AP, 48/2 = 24 AP for our demon! It also took a lot less effort than having 12 different crappy acolytes.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
I'm half tempted to post this as a comment, because it's *obvious*, but... Make "mana return" correlated to skill, such that the soul of a highly talented witch is more valuable than that of a mediocre witch. Properly tuned, this can easily have the desired effect. For instance, say it takes ten times as much effort to produce a skilled witch, but yields a hundred times the benefit. No demon is going to want to recruit (and train) ten mediocre witches when they can get the same benefit from one skilled witch at a tenth the effort.
Witches are Fast Food --------------------- --- [![enter image description here](https://i.stack.imgur.com/T5rti.png)](https://i.stack.imgur.com/T5rti.png) > > Human beings contain mana, which is the energy required for life. Mana > grows over the course of a person's life, being released at the moment > of death. Demons can feed on this energy to increase their power > through the creation of pacts with humans in exchange for magical > power. > > > Mana is to demons, as food is to humans. Initially, Demons competed with one another in recruiting as many humans as possible, seeking to consume as many souls as possible, as quickly as possible. However, the demons quickly realized, not only is the 'texture', or taste, of mana in the soul determined by its concentration and purity, low-quality mana also serves the same role as cholesterol in the human body. Human souls are not just composed of mana. They are also filled with emotions and feelings, an accumulation of their lives and memories. If the human suffers throughout their life, or their life end with extreme tragedy, **the negative emotions will condense into grudges, becoming a 'tortured soul'**. By enlisting a large quantity of humans and driving them to quick deaths to harvest their souls, a majority of these souls will also become tortured souls. Not only would the 'taste' of such souls be less savoury, there would also be deadly side-effects. Demon nobles would never be satisfied with feeding off these tortured souls, but the low-caste demons have no choice but to consume them. This is why many lower-caste demons have no sense of self, and consumed by negative human emotions, they live only as thralls for use in blood and war. Bottlenecks ----------- --- Another major reason, looking past the gruesome side-effects of impure souls, is that **over-consumption of low quality mana contributes to bottlenecks in power increase.** This is because demons have a limited mana capacity. If low-concentration mana is worth one magic unit per mana volume, and high-concentration mana is worth 10 magic units per mana volume, **a demon that only feeds on high-concentration mana will be 10 times as powerful as a demon that only feeds on low-concentration mana.** When the mana has saturated, a 'bottleneck' is reached, and only by obtaining purer sources of mana can the impure mana be forced out, and the bottleneck be broken through. On top of that, by putting greater pressure on their mana storage, high-quality souls allow demons to increase their capacity through the pressure over time, especially applicable to younger demons. By having both a higher capacity and higher concentration of magic, demons can become even more powerful. Powerful souls are both rarer and harder to cultivate, resulting in lower quantities, just like fine dining, but by cultivating the most powerful souls, the nobles not only avoid bottlenecks, but also train themselves to become the most powerful beings in their society. The exceedingly large power difference between demons fed by pure souls and demons fed by tainted, tortured souls, allows the nobles to keep both the lower-caste demons, and other lower-power nobles in check. As such, both noble demons and common demons alike are in need of high-purity souls, not only to avoid the nasty side-effects of tortured souls, but also to cement their power and status.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
**Learning takes time and devotion and getting more witches reduces power** There's two things at work here. Demons give their power and after death witches give their power. At first a demon might not notice, but giving more and more power to more and more witches reduces their own power, weakening them. This can be exponential, making any growing in power from dying witches less substantial, unless they reduce the size of a coven again. Secondly, they receive the power of the witches. But this requires an investment in time, effort and economics. Time and effort for a lot of training, in which the demon might be necessary. But also in food and housing and the like. It is an investment that you hope to get a return on. But if you don't or barely train them, the amount of energy received at death might be many times worse than one well trained witch might offer. If this wasn't the case, demons would fast forward to the logical conclusion. Pose as a well respected powerful covenant that everybody wants to join. They join, sign, and are immediately killed. This would reduce the time bound to the demon and the witch has probably *some* power that can immediately be assimilated. Finally the witches might grow weary and malcontent in bad conditions. Overcrowded, not enough attention of the demon for training, not enough food, power gained is low etc. This might provoke them to try to nullify the contract. For example by cleverly using the power of the demon itself at an unguarded moment to try and kill him.
Witches are Fast Food --------------------- --- [![enter image description here](https://i.stack.imgur.com/T5rti.png)](https://i.stack.imgur.com/T5rti.png) > > Human beings contain mana, which is the energy required for life. Mana > grows over the course of a person's life, being released at the moment > of death. Demons can feed on this energy to increase their power > through the creation of pacts with humans in exchange for magical > power. > > > Mana is to demons, as food is to humans. Initially, Demons competed with one another in recruiting as many humans as possible, seeking to consume as many souls as possible, as quickly as possible. However, the demons quickly realized, not only is the 'texture', or taste, of mana in the soul determined by its concentration and purity, low-quality mana also serves the same role as cholesterol in the human body. Human souls are not just composed of mana. They are also filled with emotions and feelings, an accumulation of their lives and memories. If the human suffers throughout their life, or their life end with extreme tragedy, **the negative emotions will condense into grudges, becoming a 'tortured soul'**. By enlisting a large quantity of humans and driving them to quick deaths to harvest their souls, a majority of these souls will also become tortured souls. Not only would the 'taste' of such souls be less savoury, there would also be deadly side-effects. Demon nobles would never be satisfied with feeding off these tortured souls, but the low-caste demons have no choice but to consume them. This is why many lower-caste demons have no sense of self, and consumed by negative human emotions, they live only as thralls for use in blood and war. Bottlenecks ----------- --- Another major reason, looking past the gruesome side-effects of impure souls, is that **over-consumption of low quality mana contributes to bottlenecks in power increase.** This is because demons have a limited mana capacity. If low-concentration mana is worth one magic unit per mana volume, and high-concentration mana is worth 10 magic units per mana volume, **a demon that only feeds on high-concentration mana will be 10 times as powerful as a demon that only feeds on low-concentration mana.** When the mana has saturated, a 'bottleneck' is reached, and only by obtaining purer sources of mana can the impure mana be forced out, and the bottleneck be broken through. On top of that, by putting greater pressure on their mana storage, high-quality souls allow demons to increase their capacity through the pressure over time, especially applicable to younger demons. By having both a higher capacity and higher concentration of magic, demons can become even more powerful. Powerful souls are both rarer and harder to cultivate, resulting in lower quantities, just like fine dining, but by cultivating the most powerful souls, the nobles not only avoid bottlenecks, but also train themselves to become the most powerful beings in their society. The exceedingly large power difference between demons fed by pure souls and demons fed by tainted, tortured souls, allows the nobles to keep both the lower-caste demons, and other lower-power nobles in check. As such, both noble demons and common demons alike are in need of high-purity souls, not only to avoid the nasty side-effects of tortured souls, but also to cement their power and status.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
Adding to Matthew's excellent answer, throw in a risk factor to sweeten the value of existing vetted witches over untested recruits. For example, imagine that a demon must invest three unit of power into a potential witch just to give her the possibility of reaching mediocre level, but that there is a 75% chance that she will fail to achieve that lowest fruitful proficiency, loosing the entire investment in the process. Additionally a proven mediocre level witch is assured of achieving the one hundred fold return level of mastery for only one unit of power each year for a decade. In such an environment, demons might invest some of their power in recruiting new potential witches, but only when they have power to spare from nurturing their proven crop. That more conservative method is their only real hope for consistently rising in power.
**Learning takes time and devotion and getting more witches reduces power** There's two things at work here. Demons give their power and after death witches give their power. At first a demon might not notice, but giving more and more power to more and more witches reduces their own power, weakening them. This can be exponential, making any growing in power from dying witches less substantial, unless they reduce the size of a coven again. Secondly, they receive the power of the witches. But this requires an investment in time, effort and economics. Time and effort for a lot of training, in which the demon might be necessary. But also in food and housing and the like. It is an investment that you hope to get a return on. But if you don't or barely train them, the amount of energy received at death might be many times worse than one well trained witch might offer. If this wasn't the case, demons would fast forward to the logical conclusion. Pose as a well respected powerful covenant that everybody wants to join. They join, sign, and are immediately killed. This would reduce the time bound to the demon and the witch has probably *some* power that can immediately be assimilated. Finally the witches might grow weary and malcontent in bad conditions. Overcrowded, not enough attention of the demon for training, not enough food, power gained is low etc. This might provoke them to try to nullify the contract. For example by cleverly using the power of the demon itself at an unguarded moment to try and kill him.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
Adding to Matthew's excellent answer, throw in a risk factor to sweeten the value of existing vetted witches over untested recruits. For example, imagine that a demon must invest three unit of power into a potential witch just to give her the possibility of reaching mediocre level, but that there is a 75% chance that she will fail to achieve that lowest fruitful proficiency, loosing the entire investment in the process. Additionally a proven mediocre level witch is assured of achieving the one hundred fold return level of mastery for only one unit of power each year for a decade. In such an environment, demons might invest some of their power in recruiting new potential witches, but only when they have power to spare from nurturing their proven crop. That more conservative method is their only real hope for consistently rising in power.
**A set number of Demon Seeds (and social issues):** These are solid answers, but I have a slightly different take. Since the demon places a seed in a new recruit, which expands over time, make each demon only able to generate a set number of seeds. This can be according to ability (people have 10 fingers, Demons have 20 seeds) or by agreement (treaty obligations say each coven can have no more than 30 members). It could even be by competition - Different covens COMPETE for the best new members, but are only allowed so many competitors in the competitions. Demons with big teams don't get the best players at draft time (so to speak) because they have emphasized quantity over quality. This could also be due to side-effects on society. Maybe the rulers don't like souls going to demons. Maybe there is a church out-competing demons for common souls, and only those with sufficient inherent power can break away. Maybe the witches children turn out mutated by Mana, and the human population was plummeting as a significant portion of the populus gave birth to monsters. Covens themselves may want to be exclusive (to concentrate their power) and if everyone has magic, the competition for (fill in the blank, Ley lines, spell components, special favors from demons) becomes too fierce and the strongest witches decided to eliminate the competition. Finally, these are DEMONS we're talking about. Perhaps all this warfare has given rise to a system where newly admitted members (acolytes) are not fully admitted until they have captured and sacrificed a rival coven's acolyte as an offering to their demon. New acolytes who aren't very good are going to get killed, and no one really WANTS to die at the hands of a rival gang - I mean, coven. This screens out witches who are afraid of death, or are unwilling to commit murder, and those who's magic isn't strong enough to compete with other acolytes. Covens don't want RIVAL covens to grow stronger, and selecting weaklings just feeds the membership of rival covens. Ruthless covens may even enter into arrangements together, so select acolytes are recruited purely as molech - offerings to be given to the other coven so chosen acolytes aren't at risk (this could even be punishment for poorly performing acolytes).
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
Witches are Fast Food --------------------- --- [![enter image description here](https://i.stack.imgur.com/T5rti.png)](https://i.stack.imgur.com/T5rti.png) > > Human beings contain mana, which is the energy required for life. Mana > grows over the course of a person's life, being released at the moment > of death. Demons can feed on this energy to increase their power > through the creation of pacts with humans in exchange for magical > power. > > > Mana is to demons, as food is to humans. Initially, Demons competed with one another in recruiting as many humans as possible, seeking to consume as many souls as possible, as quickly as possible. However, the demons quickly realized, not only is the 'texture', or taste, of mana in the soul determined by its concentration and purity, low-quality mana also serves the same role as cholesterol in the human body. Human souls are not just composed of mana. They are also filled with emotions and feelings, an accumulation of their lives and memories. If the human suffers throughout their life, or their life end with extreme tragedy, **the negative emotions will condense into grudges, becoming a 'tortured soul'**. By enlisting a large quantity of humans and driving them to quick deaths to harvest their souls, a majority of these souls will also become tortured souls. Not only would the 'taste' of such souls be less savoury, there would also be deadly side-effects. Demon nobles would never be satisfied with feeding off these tortured souls, but the low-caste demons have no choice but to consume them. This is why many lower-caste demons have no sense of self, and consumed by negative human emotions, they live only as thralls for use in blood and war. Bottlenecks ----------- --- Another major reason, looking past the gruesome side-effects of impure souls, is that **over-consumption of low quality mana contributes to bottlenecks in power increase.** This is because demons have a limited mana capacity. If low-concentration mana is worth one magic unit per mana volume, and high-concentration mana is worth 10 magic units per mana volume, **a demon that only feeds on high-concentration mana will be 10 times as powerful as a demon that only feeds on low-concentration mana.** When the mana has saturated, a 'bottleneck' is reached, and only by obtaining purer sources of mana can the impure mana be forced out, and the bottleneck be broken through. On top of that, by putting greater pressure on their mana storage, high-quality souls allow demons to increase their capacity through the pressure over time, especially applicable to younger demons. By having both a higher capacity and higher concentration of magic, demons can become even more powerful. Powerful souls are both rarer and harder to cultivate, resulting in lower quantities, just like fine dining, but by cultivating the most powerful souls, the nobles not only avoid bottlenecks, but also train themselves to become the most powerful beings in their society. The exceedingly large power difference between demons fed by pure souls and demons fed by tainted, tortured souls, allows the nobles to keep both the lower-caste demons, and other lower-power nobles in check. As such, both noble demons and common demons alike are in need of high-purity souls, not only to avoid the nasty side-effects of tortured souls, but also to cement their power and status.
**The power curve for highly skilled witches is quadratic in nature.** A lowly acolyte witch is worth barely even enough to replace the power given with her soul. This will be our unit of measure, AP (acolyte power). So our lowly acolyte, works hard but doesn't manage to learn much and only becomes a tier 2 acolyte netting our demon 4 AP for his trouble. over the course of the acolytes life she may even have cost him more power from the spells she used. The demon gets a net increase of 2 or less based on how much the witch used minus his initial investment (1AP). Picking a high quality acolyte, that acolyte might become a tier 7 witch accumulating 49 AP! Assuming that the ratio to demon power spent in the lifetime to AP is about 1/2, after the initial investment of 1 AP, 48/2 = 24 AP for our demon! It also took a lot less effort than having 12 different crappy acolytes.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
I'm half tempted to post this as a comment, because it's *obvious*, but... Make "mana return" correlated to skill, such that the soul of a highly talented witch is more valuable than that of a mediocre witch. Properly tuned, this can easily have the desired effect. For instance, say it takes ten times as much effort to produce a skilled witch, but yields a hundred times the benefit. No demon is going to want to recruit (and train) ten mediocre witches when they can get the same benefit from one skilled witch at a tenth the effort.
**Learning takes time and devotion and getting more witches reduces power** There's two things at work here. Demons give their power and after death witches give their power. At first a demon might not notice, but giving more and more power to more and more witches reduces their own power, weakening them. This can be exponential, making any growing in power from dying witches less substantial, unless they reduce the size of a coven again. Secondly, they receive the power of the witches. But this requires an investment in time, effort and economics. Time and effort for a lot of training, in which the demon might be necessary. But also in food and housing and the like. It is an investment that you hope to get a return on. But if you don't or barely train them, the amount of energy received at death might be many times worse than one well trained witch might offer. If this wasn't the case, demons would fast forward to the logical conclusion. Pose as a well respected powerful covenant that everybody wants to join. They join, sign, and are immediately killed. This would reduce the time bound to the demon and the witch has probably *some* power that can immediately be assimilated. Finally the witches might grow weary and malcontent in bad conditions. Overcrowded, not enough attention of the demon for training, not enough food, power gained is low etc. This might provoke them to try to nullify the contract. For example by cleverly using the power of the demon itself at an unguarded moment to try and kill him.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
Witches are Fast Food --------------------- --- [![enter image description here](https://i.stack.imgur.com/T5rti.png)](https://i.stack.imgur.com/T5rti.png) > > Human beings contain mana, which is the energy required for life. Mana > grows over the course of a person's life, being released at the moment > of death. Demons can feed on this energy to increase their power > through the creation of pacts with humans in exchange for magical > power. > > > Mana is to demons, as food is to humans. Initially, Demons competed with one another in recruiting as many humans as possible, seeking to consume as many souls as possible, as quickly as possible. However, the demons quickly realized, not only is the 'texture', or taste, of mana in the soul determined by its concentration and purity, low-quality mana also serves the same role as cholesterol in the human body. Human souls are not just composed of mana. They are also filled with emotions and feelings, an accumulation of their lives and memories. If the human suffers throughout their life, or their life end with extreme tragedy, **the negative emotions will condense into grudges, becoming a 'tortured soul'**. By enlisting a large quantity of humans and driving them to quick deaths to harvest their souls, a majority of these souls will also become tortured souls. Not only would the 'taste' of such souls be less savoury, there would also be deadly side-effects. Demon nobles would never be satisfied with feeding off these tortured souls, but the low-caste demons have no choice but to consume them. This is why many lower-caste demons have no sense of self, and consumed by negative human emotions, they live only as thralls for use in blood and war. Bottlenecks ----------- --- Another major reason, looking past the gruesome side-effects of impure souls, is that **over-consumption of low quality mana contributes to bottlenecks in power increase.** This is because demons have a limited mana capacity. If low-concentration mana is worth one magic unit per mana volume, and high-concentration mana is worth 10 magic units per mana volume, **a demon that only feeds on high-concentration mana will be 10 times as powerful as a demon that only feeds on low-concentration mana.** When the mana has saturated, a 'bottleneck' is reached, and only by obtaining purer sources of mana can the impure mana be forced out, and the bottleneck be broken through. On top of that, by putting greater pressure on their mana storage, high-quality souls allow demons to increase their capacity through the pressure over time, especially applicable to younger demons. By having both a higher capacity and higher concentration of magic, demons can become even more powerful. Powerful souls are both rarer and harder to cultivate, resulting in lower quantities, just like fine dining, but by cultivating the most powerful souls, the nobles not only avoid bottlenecks, but also train themselves to become the most powerful beings in their society. The exceedingly large power difference between demons fed by pure souls and demons fed by tainted, tortured souls, allows the nobles to keep both the lower-caste demons, and other lower-power nobles in check. As such, both noble demons and common demons alike are in need of high-purity souls, not only to avoid the nasty side-effects of tortured souls, but also to cement their power and status.
Instead of a cost, it can be a special reward. Some demons have figured out that if they help the seed growths on particularly gifted individuals, the quantity of mana liberated is astronomical. But it only happens with the finest, even a very strong selection of witches does not guarantee this effect. Furthermore, to help the growth of the seed the demons must limit the number of people they turn into witches. (more people less likelihood of mana big-bang) Regularly, once a year, or a decade demons must send more mana to the seeds in order to strengthen the link with the hosts. Witches created this way are more powerful but, less numerous. Demons carefully cherry-pick each of them hoping that one out of 10, 100, 1000 will create the mana equivalent of thousands of normal witches. It is a risk versus reward approach as some demons will take the risk and limit their power in the short term while hoping that in long term it will pay off.
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
**Learning takes time and devotion and getting more witches reduces power** There's two things at work here. Demons give their power and after death witches give their power. At first a demon might not notice, but giving more and more power to more and more witches reduces their own power, weakening them. This can be exponential, making any growing in power from dying witches less substantial, unless they reduce the size of a coven again. Secondly, they receive the power of the witches. But this requires an investment in time, effort and economics. Time and effort for a lot of training, in which the demon might be necessary. But also in food and housing and the like. It is an investment that you hope to get a return on. But if you don't or barely train them, the amount of energy received at death might be many times worse than one well trained witch might offer. If this wasn't the case, demons would fast forward to the logical conclusion. Pose as a well respected powerful covenant that everybody wants to join. They join, sign, and are immediately killed. This would reduce the time bound to the demon and the witch has probably *some* power that can immediately be assimilated. Finally the witches might grow weary and malcontent in bad conditions. Overcrowded, not enough attention of the demon for training, not enough food, power gained is low etc. This might provoke them to try to nullify the contract. For example by cleverly using the power of the demon itself at an unguarded moment to try and kill him.
**A set number of Demon Seeds (and social issues):** These are solid answers, but I have a slightly different take. Since the demon places a seed in a new recruit, which expands over time, make each demon only able to generate a set number of seeds. This can be according to ability (people have 10 fingers, Demons have 20 seeds) or by agreement (treaty obligations say each coven can have no more than 30 members). It could even be by competition - Different covens COMPETE for the best new members, but are only allowed so many competitors in the competitions. Demons with big teams don't get the best players at draft time (so to speak) because they have emphasized quantity over quality. This could also be due to side-effects on society. Maybe the rulers don't like souls going to demons. Maybe there is a church out-competing demons for common souls, and only those with sufficient inherent power can break away. Maybe the witches children turn out mutated by Mana, and the human population was plummeting as a significant portion of the populus gave birth to monsters. Covens themselves may want to be exclusive (to concentrate their power) and if everyone has magic, the competition for (fill in the blank, Ley lines, spell components, special favors from demons) becomes too fierce and the strongest witches decided to eliminate the competition. Finally, these are DEMONS we're talking about. Perhaps all this warfare has given rise to a system where newly admitted members (acolytes) are not fully admitted until they have captured and sacrificed a rival coven's acolyte as an offering to their demon. New acolytes who aren't very good are going to get killed, and no one really WANTS to die at the hands of a rival gang - I mean, coven. This screens out witches who are afraid of death, or are unwilling to commit murder, and those who's magic isn't strong enough to compete with other acolytes. Covens don't want RIVAL covens to grow stronger, and selecting weaklings just feeds the membership of rival covens. Ruthless covens may even enter into arrangements together, so select acolytes are recruited purely as molech - offerings to be given to the other coven so chosen acolytes aren't at risk (this could even be punishment for poorly performing acolytes).
185,366
Human beings contain mana, which is the energy required for life. Mana grows over the course of a person's life, being released at the moment of death. Demons can feed on this energy to increase their power through the creation of pacts with humans in exchange for magical power. When a demon makes a pact with a witch, the human is rewarded with a boon that allows them access to spells. In exchange, her soul goes to the demon after death. The number of souls a demon can collect, the more it can increase its own power. This competition between demons for human souls culminated into many wars and much bloodshed among witches, which led to the detriment of everyone. To end the wars in the human world, demons agreed to a treaty amongst themselves. Instead of warring with each other for a piece of each others pie, they would share the spoils. Witches would be divided up into families called covens, each with their own patron demon. When a witch came of age or joined the family, they would sign a pact with that coven's specific demon. She would gain access to magic in exchange for her soul. Each pact is an investment for the demon, which places a seed of their power into the individual. As their Mana increases with age, the seed grows in tandem. When the witch dies and their soul is claimed by the demon, the seed has multiplied in strength, returning on the demon's investment tenfold. Through this method, a demon would be guaranteed a steady stream of souls as the coven expanded either through birth or recruitment. This business model soon produced flaws however. It didn't take long for demons to realize that increasing the number of witches in their family as fast as possible was in their best interest. This led to a massive increase in recruitment, as many individuals among the population would simply be inducted into these covens. Potential witches were eager to sign away their souls in exchange for power from a patron, and demons were just as eager to collect more souls than their rivals. This led to a race to the bottom, as covens lowered their standards to try to outdo other covens, creating a generation of crappy witches. What I want is for demons to value producing witches of high quality and skill, rather than turning covens into basically recruiting centers. However, it is natural for standards to be sacrificed in the name of producing content if the latter is in one's best interest. This is similiar to the streaming wars, in which most of Netflix's movies and series are crap, but it is made in such high quantities that they outpace the competition. How can I make this happen?
2020/09/12
[ "https://worldbuilding.stackexchange.com/questions/185366", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/52361/" ]
Adding to Matthew's excellent answer, throw in a risk factor to sweeten the value of existing vetted witches over untested recruits. For example, imagine that a demon must invest three unit of power into a potential witch just to give her the possibility of reaching mediocre level, but that there is a 75% chance that she will fail to achieve that lowest fruitful proficiency, loosing the entire investment in the process. Additionally a proven mediocre level witch is assured of achieving the one hundred fold return level of mastery for only one unit of power each year for a decade. In such an environment, demons might invest some of their power in recruiting new potential witches, but only when they have power to spare from nurturing their proven crop. That more conservative method is their only real hope for consistently rising in power.
Witches are Fast Food --------------------- --- [![enter image description here](https://i.stack.imgur.com/T5rti.png)](https://i.stack.imgur.com/T5rti.png) > > Human beings contain mana, which is the energy required for life. Mana > grows over the course of a person's life, being released at the moment > of death. Demons can feed on this energy to increase their power > through the creation of pacts with humans in exchange for magical > power. > > > Mana is to demons, as food is to humans. Initially, Demons competed with one another in recruiting as many humans as possible, seeking to consume as many souls as possible, as quickly as possible. However, the demons quickly realized, not only is the 'texture', or taste, of mana in the soul determined by its concentration and purity, low-quality mana also serves the same role as cholesterol in the human body. Human souls are not just composed of mana. They are also filled with emotions and feelings, an accumulation of their lives and memories. If the human suffers throughout their life, or their life end with extreme tragedy, **the negative emotions will condense into grudges, becoming a 'tortured soul'**. By enlisting a large quantity of humans and driving them to quick deaths to harvest their souls, a majority of these souls will also become tortured souls. Not only would the 'taste' of such souls be less savoury, there would also be deadly side-effects. Demon nobles would never be satisfied with feeding off these tortured souls, but the low-caste demons have no choice but to consume them. This is why many lower-caste demons have no sense of self, and consumed by negative human emotions, they live only as thralls for use in blood and war. Bottlenecks ----------- --- Another major reason, looking past the gruesome side-effects of impure souls, is that **over-consumption of low quality mana contributes to bottlenecks in power increase.** This is because demons have a limited mana capacity. If low-concentration mana is worth one magic unit per mana volume, and high-concentration mana is worth 10 magic units per mana volume, **a demon that only feeds on high-concentration mana will be 10 times as powerful as a demon that only feeds on low-concentration mana.** When the mana has saturated, a 'bottleneck' is reached, and only by obtaining purer sources of mana can the impure mana be forced out, and the bottleneck be broken through. On top of that, by putting greater pressure on their mana storage, high-quality souls allow demons to increase their capacity through the pressure over time, especially applicable to younger demons. By having both a higher capacity and higher concentration of magic, demons can become even more powerful. Powerful souls are both rarer and harder to cultivate, resulting in lower quantities, just like fine dining, but by cultivating the most powerful souls, the nobles not only avoid bottlenecks, but also train themselves to become the most powerful beings in their society. The exceedingly large power difference between demons fed by pure souls and demons fed by tainted, tortured souls, allows the nobles to keep both the lower-caste demons, and other lower-power nobles in check. As such, both noble demons and common demons alike are in need of high-purity souls, not only to avoid the nasty side-effects of tortured souls, but also to cement their power and status.
38,821,297
I am new to Python and I am trying to install scrapy, I have python 2.7.12 and pip 8.1.2 on windows 10. when I give the command 'pip install scrapy' it tries to install lxml and gives the below error. I downloaded the libxml2 binary, extracted to a folder and added the bin folder in path variable.But still the same issue. Please guide me with this issue, I am stuck with this. The error message is mentioned below. ``` cl : Command line warning D9025 : overriding '/W3' with '/w' lxml.etree.c src\lxml\includes\etree_defs.h(14) : fatal error C1083: Cannot open include file: 'libxml/xmlversion.h': No such file or directory Compile failed: command 'C:\\Users\\myuserid\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 creating users creating users\myuser~1 creating users\myuser~1\appdata creating users\myuser~1\appdata\local creating users\myuser~1\appdata\local\temp C:\Users\myuserid\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I/usr/include/libxml2 /Tcc:\users\myuser~1\appdata\local\temp\xmlXPathInita7i8_a.c /Fousers\myuser~1\appdata\local\temp\xmlXPathInita7i8_a.obj xmlXPathInita7i8_a.c c:\users\myuser~1\appdata\local\temp\xmlXPathInita7i8_a.c(1) : fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* error: command 'C:\\Users\\myuserid\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 ---------------------------------------- Command "c:\softwares\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\myuser~1\\appdata\\local\\temp\\pip-build-m4bvsr\\lxml\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\myuser~1\appdata\local\temp\pip-dnttln-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\myuser~1\appdata\local\temp\pip-build-m4bvsr\lxml\ ```
2016/08/08
[ "https://Stackoverflow.com/questions/38821297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2928913/" ]
you can simply use one of these [whl files](http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml), based on your system. After download it, use these command in where you download that file: ``` pip install ***.whl ```
Scrapy's docummentation [recommends using Anaconda](http://doc.scrapy.org/en/latest/intro/install.html#anaconda) to install the package. Lxml package is really tricky to install on windows and anaconda is a really straigh-forward shortcut. There's also unnoficial binaries of lxml [mentioned in lxml's docummentation](http://lxml.de/installation.html#ms-windows) that you can use to install already compiled lxml package. There are more instructions as well, how to install lxml on windows os there too.
38,821,297
I am new to Python and I am trying to install scrapy, I have python 2.7.12 and pip 8.1.2 on windows 10. when I give the command 'pip install scrapy' it tries to install lxml and gives the below error. I downloaded the libxml2 binary, extracted to a folder and added the bin folder in path variable.But still the same issue. Please guide me with this issue, I am stuck with this. The error message is mentioned below. ``` cl : Command line warning D9025 : overriding '/W3' with '/w' lxml.etree.c src\lxml\includes\etree_defs.h(14) : fatal error C1083: Cannot open include file: 'libxml/xmlversion.h': No such file or directory Compile failed: command 'C:\\Users\\myuserid\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 creating users creating users\myuser~1 creating users\myuser~1\appdata creating users\myuser~1\appdata\local creating users\myuser~1\appdata\local\temp C:\Users\myuserid\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I/usr/include/libxml2 /Tcc:\users\myuser~1\appdata\local\temp\xmlXPathInita7i8_a.c /Fousers\myuser~1\appdata\local\temp\xmlXPathInita7i8_a.obj xmlXPathInita7i8_a.c c:\users\myuser~1\appdata\local\temp\xmlXPathInita7i8_a.c(1) : fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* error: command 'C:\\Users\\myuserid\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 ---------------------------------------- Command "c:\softwares\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\myuser~1\\appdata\\local\\temp\\pip-build-m4bvsr\\lxml\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\myuser~1\appdata\local\temp\pip-dnttln-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\myuser~1\appdata\local\temp\pip-build-m4bvsr\lxml\ ```
2016/08/08
[ "https://Stackoverflow.com/questions/38821297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2928913/" ]
you can simply use one of these [whl files](http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml), based on your system. After download it, use these command in where you download that file: ``` pip install ***.whl ```
What version of pip do you have? Just upgrading pip helps in my case ``` pip install --upgrade pip ```
43,001,690
I found this project on the web: <http://cyntss.github.io/Parallax-img-scroll/> And I am wondering if I want to change the `data-ps-vertical-position""` on resize how can I do that? I have tried updating the data value using the following approach: `$('div#frame-1').attr( 'data-ps-vertical-position','1900');` however it did not change the position of the element. If I reload the page with the right screen size it gets applied. Please see below my approach of handling the responsive behaviour ```js (function($) { $(document).ready(function() { var width = $(document).width(); $(window).resize(function() { //do something if (width < 900) { $('div#frame-1').css('bottom', 1900); $('div#frame-1').attr('data-ps-vertical-position', '1900'); } else if (width > 901) { $('div#frame-1').css('bottom', 2500); $('div#frame-1').attr('data-ps-vertical-position', '2500'); } }).resize(); }); })(jQuery); ``` Link to the [JS file](https://github.com/cyntss/Parallax-img-scroll/blob/master/demo/js/parallaxImg.js)
2017/03/24
[ "https://Stackoverflow.com/questions/43001690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974930/" ]
The solution described in the accepted answer gets the job done but for the cost of losing type safety. **If you want to keep the type-safety** going I would suggest the following: Create `dom.d.ts` file in `@types` folder in your sources (or configure [`typeRoots`](https://www.typescriptlang.org/tsconfig#typeRoots) to make sure that TS compiler will look there) with the following: ``` interface CustomEventMap { "customnumberevent": CustomEvent<number>; "anothercustomevent": CustomEvent<CustomParams>; } declare global { interface Document { //adds definition to Document, but you can do the same with HTMLElement addEventListener<K extends keyof CustomEventMap>(type: K, listener: (this: Document, ev: CustomEventMap[K]) => void): void; dispatchEvent<K extends keyof CustomEventMap>(ev: CustomEventMap[K]): void; } } export { }; //keep that for TS compiler. ``` This will augment [global definition](https://fettblog.eu/typescript-augmenting-global-lib-dom/) of `document`'s `addEventListener` function to accept your synthetic event and its typed params. now you can do: ``` function onCustomEvent(event: CustomEvent<CustomParams>){ this.[...] // this is Document event.detail ... //is your CustomParams type. } document.addEventListener('anothercustomevent', onCustomEvent); ``` This way you will have everything typed and under control.
I ended up taking a different approach. Instead, I made a wrapper class that extended EventTarget. ``` type AudioEvent = {bytes: Uint8Array}; interface IAudioEventTarget { addListener(callback: (evt: CustomEvent<AudioEvent>) => void): void dispatch(event: AudioEvent): boolean; removeListener(callback: (evt: CustomEvent<AudioEvent>) => void): void } class AudioEventTarget extends EventTarget implements IAudioEventTarget { private readonly targetType = 'audio-event'; addListener(callback: (evt: CustomEvent<AudioEvent>) => void): void { return this.addEventListener(this.targetType, callback as (evt: Event) => void); } dispatch(event: AudioEvent): boolean { return this.dispatchEvent(new CustomEvent(this.targetType, { detail: event })); } removeListener(callback: (evt: CustomEvent<AudioEvent>) => void): void { return this.removeEventListener(this.targetType, callback as (evt: Event) => void); } }; ``` And usage is as follows: ``` const audioEventTarget = new AudioEventTarget(); const listener = (audioEvent: CustomEvent<AudioEvent>) => { console.log(`Received ${audioEvent.detail.bytes.length} bytes`); } audioEventTarget.addListener(listener); audioEventTarget.dispatch({bytes: new Uint8Array(10)}); audioEventTarget.removeListener(listener); ```
43,001,690
I found this project on the web: <http://cyntss.github.io/Parallax-img-scroll/> And I am wondering if I want to change the `data-ps-vertical-position""` on resize how can I do that? I have tried updating the data value using the following approach: `$('div#frame-1').attr( 'data-ps-vertical-position','1900');` however it did not change the position of the element. If I reload the page with the right screen size it gets applied. Please see below my approach of handling the responsive behaviour ```js (function($) { $(document).ready(function() { var width = $(document).width(); $(window).resize(function() { //do something if (width < 900) { $('div#frame-1').css('bottom', 1900); $('div#frame-1').attr('data-ps-vertical-position', '1900'); } else if (width > 901) { $('div#frame-1').css('bottom', 2500); $('div#frame-1').attr('data-ps-vertical-position', '2500'); } }).resize(); }); })(jQuery); ``` Link to the [JS file](https://github.com/cyntss/Parallax-img-scroll/blob/master/demo/js/parallaxImg.js)
2017/03/24
[ "https://Stackoverflow.com/questions/43001690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974930/" ]
`CustomEvent` is a generic type. You can pass the type of the `detail` property as a parameter (it defaults to `any`). Here is how it is defined in [lib.dom.d.ts](https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts) (which is in the `lib` directory of your npm typescript installation): ```js interface CustomEvent<T = any> extends Event { /** * Returns any custom data event was created with. Typically used for synthetic events. */ readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } ``` In the OP's example, the type of `detail` is `number`. So, building on the answer from @Diullei: ```js let div: HTMLElement | null = document.getElementById("my_div"); let c_event = new CustomEvent<number>("build", {detail: 3}); div.addEventListener("build", function(e: CustomEvent<number>) { // change here Event to CustomEvent console.log(e.detail); }.bind(this)); div.dispatchEvent(c_event); ``` Above, I've also used the `HTMLElement` type from `lib.dom.d.ts`. As a newcomer to TypeScript, I found it very useful to scan this file, and search it for 'obvious' types.
maybe overly complicated but typesafe? ``` interface FizzInfo { amount: string; } interface BuzzInfo { level: number; } interface FizzBuzzEventMap { fizz: CustomEvent<FizzInfo>; buzz: CustomEvent<BuzzInfo>; } interface FizzerBuzzer extends EventTarget { addEventListener<K extends keyof FizzBuzzEventMap>(type: K, listener: (this: FizzerBuzzer, ev: FizzBuzzEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof FizzBuzzEventMap>(type: K, listener: (this: FizzerBuzzer, ev: FizzBuzzEventMap[K]) => void, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } class FizzerBuzzer extends EventTarget { numFizz: number = 0; numBuzz: number = 0; start(): void { setInterval(() => this.emitFizz(), 3000); setInterval(() => this.emitBuzz(), 5000); } emitFizz(): void { ++this.numFizz; this.dispatchEvent(new CustomEvent<FizzInfo>('fizz', { detail: { amount: this.numFizz.toString() }, })); } emitBuzz(): void { ++this.numBuzz; this.dispatchEvent(new CustomEvent<BuzzInfo>('buzz', { detail: { level: this.numBuzz }, })); } } const fb = new FizzerBuzzer(); fb.addEventListener('fizz', (ev) => { console.assert(typeof ev.detail.amount === 'string', 'bad!'); console.log(ev.detail.amount); }); fb.addEventListener('buzz', (ev) => { console.assert(typeof ev.detail.level === 'number', 'bad'); console.log(ev.detail.level); }); ```
43,001,690
I found this project on the web: <http://cyntss.github.io/Parallax-img-scroll/> And I am wondering if I want to change the `data-ps-vertical-position""` on resize how can I do that? I have tried updating the data value using the following approach: `$('div#frame-1').attr( 'data-ps-vertical-position','1900');` however it did not change the position of the element. If I reload the page with the right screen size it gets applied. Please see below my approach of handling the responsive behaviour ```js (function($) { $(document).ready(function() { var width = $(document).width(); $(window).resize(function() { //do something if (width < 900) { $('div#frame-1').css('bottom', 1900); $('div#frame-1').attr('data-ps-vertical-position', '1900'); } else if (width > 901) { $('div#frame-1').css('bottom', 2500); $('div#frame-1').attr('data-ps-vertical-position', '2500'); } }).resize(); }); })(jQuery); ``` Link to the [JS file](https://github.com/cyntss/Parallax-img-scroll/blob/master/demo/js/parallaxImg.js)
2017/03/24
[ "https://Stackoverflow.com/questions/43001690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974930/" ]
The solution described in the accepted answer gets the job done but for the cost of losing type safety. **If you want to keep the type-safety** going I would suggest the following: Create `dom.d.ts` file in `@types` folder in your sources (or configure [`typeRoots`](https://www.typescriptlang.org/tsconfig#typeRoots) to make sure that TS compiler will look there) with the following: ``` interface CustomEventMap { "customnumberevent": CustomEvent<number>; "anothercustomevent": CustomEvent<CustomParams>; } declare global { interface Document { //adds definition to Document, but you can do the same with HTMLElement addEventListener<K extends keyof CustomEventMap>(type: K, listener: (this: Document, ev: CustomEventMap[K]) => void): void; dispatchEvent<K extends keyof CustomEventMap>(ev: CustomEventMap[K]): void; } } export { }; //keep that for TS compiler. ``` This will augment [global definition](https://fettblog.eu/typescript-augmenting-global-lib-dom/) of `document`'s `addEventListener` function to accept your synthetic event and its typed params. now you can do: ``` function onCustomEvent(event: CustomEvent<CustomParams>){ this.[...] // this is Document event.detail ... //is your CustomParams type. } document.addEventListener('anothercustomevent', onCustomEvent); ``` This way you will have everything typed and under control.
maybe overly complicated but typesafe? ``` interface FizzInfo { amount: string; } interface BuzzInfo { level: number; } interface FizzBuzzEventMap { fizz: CustomEvent<FizzInfo>; buzz: CustomEvent<BuzzInfo>; } interface FizzerBuzzer extends EventTarget { addEventListener<K extends keyof FizzBuzzEventMap>(type: K, listener: (this: FizzerBuzzer, ev: FizzBuzzEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof FizzBuzzEventMap>(type: K, listener: (this: FizzerBuzzer, ev: FizzBuzzEventMap[K]) => void, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } class FizzerBuzzer extends EventTarget { numFizz: number = 0; numBuzz: number = 0; start(): void { setInterval(() => this.emitFizz(), 3000); setInterval(() => this.emitBuzz(), 5000); } emitFizz(): void { ++this.numFizz; this.dispatchEvent(new CustomEvent<FizzInfo>('fizz', { detail: { amount: this.numFizz.toString() }, })); } emitBuzz(): void { ++this.numBuzz; this.dispatchEvent(new CustomEvent<BuzzInfo>('buzz', { detail: { level: this.numBuzz }, })); } } const fb = new FizzerBuzzer(); fb.addEventListener('fizz', (ev) => { console.assert(typeof ev.detail.amount === 'string', 'bad!'); console.log(ev.detail.amount); }); fb.addEventListener('buzz', (ev) => { console.assert(typeof ev.detail.level === 'number', 'bad'); console.log(ev.detail.level); }); ```
43,001,690
I found this project on the web: <http://cyntss.github.io/Parallax-img-scroll/> And I am wondering if I want to change the `data-ps-vertical-position""` on resize how can I do that? I have tried updating the data value using the following approach: `$('div#frame-1').attr( 'data-ps-vertical-position','1900');` however it did not change the position of the element. If I reload the page with the right screen size it gets applied. Please see below my approach of handling the responsive behaviour ```js (function($) { $(document).ready(function() { var width = $(document).width(); $(window).resize(function() { //do something if (width < 900) { $('div#frame-1').css('bottom', 1900); $('div#frame-1').attr('data-ps-vertical-position', '1900'); } else if (width > 901) { $('div#frame-1').css('bottom', 2500); $('div#frame-1').attr('data-ps-vertical-position', '2500'); } }).resize(); }); })(jQuery); ``` Link to the [JS file](https://github.com/cyntss/Parallax-img-scroll/blob/master/demo/js/parallaxImg.js)
2017/03/24
[ "https://Stackoverflow.com/questions/43001690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974930/" ]
The property name is `detail` and not `details`. The correct code needs to be: ``` let div: any = document.getElementById("my_div"); let c_event = new CustomEvent("build",{detail: 3}); div.addEventListener("build", function(e: CustomEvent) { // change here Event to CustomEvent console.log(e.detail); }.bind(this)); div.dispatchEvent(c_event); ```
maybe overly complicated but typesafe? ``` interface FizzInfo { amount: string; } interface BuzzInfo { level: number; } interface FizzBuzzEventMap { fizz: CustomEvent<FizzInfo>; buzz: CustomEvent<BuzzInfo>; } interface FizzerBuzzer extends EventTarget { addEventListener<K extends keyof FizzBuzzEventMap>(type: K, listener: (this: FizzerBuzzer, ev: FizzBuzzEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof FizzBuzzEventMap>(type: K, listener: (this: FizzerBuzzer, ev: FizzBuzzEventMap[K]) => void, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } class FizzerBuzzer extends EventTarget { numFizz: number = 0; numBuzz: number = 0; start(): void { setInterval(() => this.emitFizz(), 3000); setInterval(() => this.emitBuzz(), 5000); } emitFizz(): void { ++this.numFizz; this.dispatchEvent(new CustomEvent<FizzInfo>('fizz', { detail: { amount: this.numFizz.toString() }, })); } emitBuzz(): void { ++this.numBuzz; this.dispatchEvent(new CustomEvent<BuzzInfo>('buzz', { detail: { level: this.numBuzz }, })); } } const fb = new FizzerBuzzer(); fb.addEventListener('fizz', (ev) => { console.assert(typeof ev.detail.amount === 'string', 'bad!'); console.log(ev.detail.amount); }); fb.addEventListener('buzz', (ev) => { console.assert(typeof ev.detail.level === 'number', 'bad'); console.log(ev.detail.level); }); ```
43,001,690
I found this project on the web: <http://cyntss.github.io/Parallax-img-scroll/> And I am wondering if I want to change the `data-ps-vertical-position""` on resize how can I do that? I have tried updating the data value using the following approach: `$('div#frame-1').attr( 'data-ps-vertical-position','1900');` however it did not change the position of the element. If I reload the page with the right screen size it gets applied. Please see below my approach of handling the responsive behaviour ```js (function($) { $(document).ready(function() { var width = $(document).width(); $(window).resize(function() { //do something if (width < 900) { $('div#frame-1').css('bottom', 1900); $('div#frame-1').attr('data-ps-vertical-position', '1900'); } else if (width > 901) { $('div#frame-1').css('bottom', 2500); $('div#frame-1').attr('data-ps-vertical-position', '2500'); } }).resize(); }); })(jQuery); ``` Link to the [JS file](https://github.com/cyntss/Parallax-img-scroll/blob/master/demo/js/parallaxImg.js)
2017/03/24
[ "https://Stackoverflow.com/questions/43001690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974930/" ]
The property name is `detail` and not `details`. The correct code needs to be: ``` let div: any = document.getElementById("my_div"); let c_event = new CustomEvent("build",{detail: 3}); div.addEventListener("build", function(e: CustomEvent) { // change here Event to CustomEvent console.log(e.detail); }.bind(this)); div.dispatchEvent(c_event); ```
I ended up taking a different approach. Instead, I made a wrapper class that extended EventTarget. ``` type AudioEvent = {bytes: Uint8Array}; interface IAudioEventTarget { addListener(callback: (evt: CustomEvent<AudioEvent>) => void): void dispatch(event: AudioEvent): boolean; removeListener(callback: (evt: CustomEvent<AudioEvent>) => void): void } class AudioEventTarget extends EventTarget implements IAudioEventTarget { private readonly targetType = 'audio-event'; addListener(callback: (evt: CustomEvent<AudioEvent>) => void): void { return this.addEventListener(this.targetType, callback as (evt: Event) => void); } dispatch(event: AudioEvent): boolean { return this.dispatchEvent(new CustomEvent(this.targetType, { detail: event })); } removeListener(callback: (evt: CustomEvent<AudioEvent>) => void): void { return this.removeEventListener(this.targetType, callback as (evt: Event) => void); } }; ``` And usage is as follows: ``` const audioEventTarget = new AudioEventTarget(); const listener = (audioEvent: CustomEvent<AudioEvent>) => { console.log(`Received ${audioEvent.detail.bytes.length} bytes`); } audioEventTarget.addListener(listener); audioEventTarget.dispatch({bytes: new Uint8Array(10)}); audioEventTarget.removeListener(listener); ```
43,001,690
I found this project on the web: <http://cyntss.github.io/Parallax-img-scroll/> And I am wondering if I want to change the `data-ps-vertical-position""` on resize how can I do that? I have tried updating the data value using the following approach: `$('div#frame-1').attr( 'data-ps-vertical-position','1900');` however it did not change the position of the element. If I reload the page with the right screen size it gets applied. Please see below my approach of handling the responsive behaviour ```js (function($) { $(document).ready(function() { var width = $(document).width(); $(window).resize(function() { //do something if (width < 900) { $('div#frame-1').css('bottom', 1900); $('div#frame-1').attr('data-ps-vertical-position', '1900'); } else if (width > 901) { $('div#frame-1').css('bottom', 2500); $('div#frame-1').attr('data-ps-vertical-position', '2500'); } }).resize(); }); })(jQuery); ``` Link to the [JS file](https://github.com/cyntss/Parallax-img-scroll/blob/master/demo/js/parallaxImg.js)
2017/03/24
[ "https://Stackoverflow.com/questions/43001690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974930/" ]
The solution described in the accepted answer gets the job done but for the cost of losing type safety. **If you want to keep the type-safety** going I would suggest the following: Create `dom.d.ts` file in `@types` folder in your sources (or configure [`typeRoots`](https://www.typescriptlang.org/tsconfig#typeRoots) to make sure that TS compiler will look there) with the following: ``` interface CustomEventMap { "customnumberevent": CustomEvent<number>; "anothercustomevent": CustomEvent<CustomParams>; } declare global { interface Document { //adds definition to Document, but you can do the same with HTMLElement addEventListener<K extends keyof CustomEventMap>(type: K, listener: (this: Document, ev: CustomEventMap[K]) => void): void; dispatchEvent<K extends keyof CustomEventMap>(ev: CustomEventMap[K]): void; } } export { }; //keep that for TS compiler. ``` This will augment [global definition](https://fettblog.eu/typescript-augmenting-global-lib-dom/) of `document`'s `addEventListener` function to accept your synthetic event and its typed params. now you can do: ``` function onCustomEvent(event: CustomEvent<CustomParams>){ this.[...] // this is Document event.detail ... //is your CustomParams type. } document.addEventListener('anothercustomevent', onCustomEvent); ``` This way you will have everything typed and under control.
`CustomEvent` is a generic type. You can pass the type of the `detail` property as a parameter (it defaults to `any`). Here is how it is defined in [lib.dom.d.ts](https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts) (which is in the `lib` directory of your npm typescript installation): ```js interface CustomEvent<T = any> extends Event { /** * Returns any custom data event was created with. Typically used for synthetic events. */ readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } ``` In the OP's example, the type of `detail` is `number`. So, building on the answer from @Diullei: ```js let div: HTMLElement | null = document.getElementById("my_div"); let c_event = new CustomEvent<number>("build", {detail: 3}); div.addEventListener("build", function(e: CustomEvent<number>) { // change here Event to CustomEvent console.log(e.detail); }.bind(this)); div.dispatchEvent(c_event); ``` Above, I've also used the `HTMLElement` type from `lib.dom.d.ts`. As a newcomer to TypeScript, I found it very useful to scan this file, and search it for 'obvious' types.