qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
154,695 | There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts.
Initially, barter is the primary form of trade but this quickly becomes cumbersome.
How would the two economies first establish a currency exchange and exchange rate?
Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other.
Some restrictions:
* Both planets have one currency or at least a dominant currency (like the USD)
* Neither planet is in a "dominant" economic or technological position.
* Travel between the planets takes a few days
* There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet.
Ideas I've toyed with:
* comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet
* some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates | 2019/09/07 | [
"https://worldbuilding.stackexchange.com/questions/154695",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/5101/"
]
| Why have an exchange rate?
Just deal in the local currency on whichever end of the trip I am at, and carry my wealth in the form of goods that will sell well at my next stop. Freight carriers don't like to run with empty holds, it is a waste of resources to sit still longer than necessary to unload and reload, and an even bigger waste to move while empty.
I leave A with a hold full of cargo bound for B. When I get there I sell my cargo for B coin. I then turn around and buy new cargo using said B coin for my trip back to A. On the A side I do the same thing but with A dollars. If I am doing this regularly, I keep accounts on both ends of the trip in that planets currency. When I am ready to retire, or otherwise have a need to consolidate my wealth, I deliberately skew the relative value of my cargos so that A>B just covers the costs, while B>A lets me extract my savings and bring my profits home.
Money is just a convenient means of representing the time and energy that goes into producing something. It only has value as long as all parties agree on what a unit represents. People on A will never see value in B coins, and B will never value A dollars, because they have a different reference base. The only ones who will see value in both are the people who move between places, and they will naturally define their own formula for relative worth base on what they can do with each currency in it's own place. | As bitcoin history shows, currency exchanges will emerge very quickly as soon as the currency is considered to have some nonzero value, despite exchange rate fluctuations. The rates on all these exchanges tend to quickly converge, and are used as a basis even for other people who trade directly. Even after failures of large exchanges like MtGox, the trade went on.
Unlike Bitcoin, you have equivalent goods on both planets (gold, drinking water, rocket fuel, ...), so trader can use them to calculate the estimated value of foreign currency.
When the interplanetary trade gets non-negligible and it gets regulated, these exchanges gradually enter the regulated regime and precautions to stabilize the exchange rate are made. I assume here both governemnts view the interplanetary trade as something good or neutral, not try to stop it. |
7,349,907 | I'm developing software that will utilize a config file. I don't know many syntaxes or formats of config files. Here are the two I know:
(common with .conf files)
```
[section]
key=value
#comment
```
or (common with .ini)
```
key value
; comment
```
My interest is something versatile that's almost a language. Let's say
```
[Default]
Start = 0
End = 10
Speed = 1
[Section 3-6]
Speed = 2
```
This would act as an override. However this isn't any convention that I know of. Is there a common syntax that allows for this? | 2011/09/08 | [
"https://Stackoverflow.com/questions/7349907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425380/"
]
| As of 2015, xml is no longer the de facto standard. Here are options.
[TOML](https://github.com/toml-lang/toml)
```
# This is a TOML document.
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00
[servers]
# tabs / spaces ok but not required
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
```
[YAML](https://yaml.org/)
```
%YAML 1.2
---
YAML: YAML Ain't Markup Language
Projects:
C/C++ Libraries:
- libyaml # "C" Fast YAML 1.1
- Syck # (dated) "C" YAML 1.0
- yaml-cpp # C++ YAML 1.2 implementation
```
[CSON](https://github.com/bevry/cson)
```
# Comments!!!
greatDocumentaries: [
'earthlings.com'
'forksoverknives.com'
]
importantFacts:
# Multi-Line Strings! Without Quote Escaping!
emissions: '''
Livestock and their byproducts account for at least 32,000 million tons of carbon dioxide (CO2) per year, or 51% of all worldwide greenhouse gas emissions.
'''
```
[JSON5](http://json5.org/) and [Human JSON](http://hjson.org/) - flexible json supersets
[Properties File](http://en.wikipedia.org/wiki/.properties) - used by java programs | This once-valid answer is being voted down in 2020, so I edited it.
In 2011, I suggested you use an xml format. This was the de-facto standard then.
The configuration document could have looked like this:
```
<?xml version="1.0" encoding="utf-8">
<configuraton>
<default>
<start>0</start>
<end>10</end>
<speed>1</speed>
</default>
<section from="3" to="6">
<speed>2</speed>
</section>
</configuration>
```
There are many libraries to parse such files. |
30,537 | ***In Jeremiah, which dreams is God saying to not listen to?***
>
> **NKJV, Jeremiah 29:8** - For thus says the Lord of hosts, the God of Israel: Do not let your prophets and your diviners who are in your midst deceive you, nor listen to your dreams which you cause to be dreamed.
>
>
>
In Hebrew, is God saying for Israel to not listen to any of their own dreams? Or, is God talking about a specific type of dream that is caused - perhaps through substances, lucid dreaming, or even daydreaming?
In Hebrew, how should Jeremiah 29:8 be translated and then interpreted?
* Should `"have dreamed"` be translated in 2nd, or 3rd Person Plural? `"... you all have dreamed"` ... or, `"... they have dreamed"`?
* Is the NKJV correct to imply an active sense of either making yourself dream, or even others causing themselves to dream?
* Is the NASB correct to imply that Israel was no longer to listen to anyone's dreams?
**Or, can the verses be validly / reasonably translated in multiple ways?** | 2017/11/19 | [
"https://hermeneutics.stackexchange.com/questions/30537",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/6338/"
]
| >
> Should "have dreamed" be translated in 2nd, or 3rd Person Plural? "... you all have dreamed" ... or, "... they have dreamed"?
>
>
>
The word is ืึทืึฐืึฐืึดืื, which is a masculine plural participle (which might be translated as "dream" in the present, or "dreamer," but certainly not "have dreamed" - on the exact translation see below), undeclined for person. However, the word ืึทืชึผึถื before ืึทืึฐืึฐืึดืื unambiguously makes it a second person plural address, that "you" are doing, and not the prophets mentioned previously.
>
> Is the NKJV correct to imply an active sense of either making yourself dream, or even others causing themselves to dream?
>
>
>
The word ืึทืึฐืึฐืึดืื is in the *hiph'il* form, which usually means causing someone to do something. For the translation, some ancient versions (LXX, Peshitta) ignore the different form and translate it as "dream" (as if it said ืืึนืึฐืึดืื), which might be a clue to confusion as how to translate, or possibly a different text (maybe it was erased due to being interpreted as an enclitic *mem*: rearranging the consonantal text gives ืืฉืจ ืืชื-ื ืืืืื).
However, according to the Masorah and the Targum, which echoes the *hiph'il* form of the Hebrew, it seems to be saying "which you cause to dream."
Some possible explanations:
* The explanation you propose, causing dreams through substances, is very creative, and fits the grammar, but I don't recall any mention of causing dreams through substances in the Bible
* One interpretation given is that "your dreams" are the dreams of the prophets with whom Jeremiah is disputing, and they are called "your dreams" because the people listened to them, and without their encouragement they wouldn't have continued to have those dreams ([Radaq](https://en.wikipedia.org/wiki/David_Kimhi)). This interpretation is seen as well in the NIV translation "Do not listen to the dreams you encourage them to have."
* I would like to propose reading ืึฐืึทืึฐึผืึดืื in the *pi''el* form, by analogy to ืึฐืึทืึตื (e.g. in Hosea 2:9), which differs from the *qal* ืืึนืึตื "lover" with the meaning "improper lover." Maybe ืึฐืึทืึฐึผืึดืื could also mean having an *improper* dream
>
> Is the NASB correct to imply that Israel was no longer to listen to anyone's dreams?
>
>
>
No. Jeremiah said the exile would last 70 years (29:10), and told them to build houses, marry, and pray for the welfare of their city (29:5-7). Other prophets were making the claim that the exile would be short and they would return to their land soon (28:3). This is the claim Jeremiah was disputing, which is far from saying "no longer to listen to anyone's dreams."
The dreams referred to here are those of a "ืึนืึตื ืึฒืืึนื" ("dreamer," Deuteronomy 13:2, in apposition to "ื ึธืึดืื," prophet). He was disputing very specific prophetic dreams, just as he disputes other prophets many other times in the book. The Greek and Aramaic translations tend to translate this sort of prophet as "false prophet" (unlike the Hebrew, which never says "false prophet"), and "dreams" in this context should be understood as "false dreams" - i.e., specifically the dreams Jeremiah was disputing. He is not addressing the reliability of dreams in general. | I think this verse may actually have to do with lucid dreaming. People recreationally did it in older times, and didn't have all of the odious New Age yoga alien content that a lot of people try to add to it nowadays. Lucid dreaming may have been something common amongst people from this certain time period as well, and this may have been saying something along the lines of "Don't alter your dream to where you're getting some prophecy you want." |
30,537 | ***In Jeremiah, which dreams is God saying to not listen to?***
>
> **NKJV, Jeremiah 29:8** - For thus says the Lord of hosts, the God of Israel: Do not let your prophets and your diviners who are in your midst deceive you, nor listen to your dreams which you cause to be dreamed.
>
>
>
In Hebrew, is God saying for Israel to not listen to any of their own dreams? Or, is God talking about a specific type of dream that is caused - perhaps through substances, lucid dreaming, or even daydreaming?
In Hebrew, how should Jeremiah 29:8 be translated and then interpreted?
* Should `"have dreamed"` be translated in 2nd, or 3rd Person Plural? `"... you all have dreamed"` ... or, `"... they have dreamed"`?
* Is the NKJV correct to imply an active sense of either making yourself dream, or even others causing themselves to dream?
* Is the NASB correct to imply that Israel was no longer to listen to anyone's dreams?
**Or, can the verses be validly / reasonably translated in multiple ways?** | 2017/11/19 | [
"https://hermeneutics.stackexchange.com/questions/30537",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/6338/"
]
| >
> Should "have dreamed" be translated in 2nd, or 3rd Person Plural? "... you all have dreamed" ... or, "... they have dreamed"?
>
>
>
The word is ืึทืึฐืึฐืึดืื, which is a masculine plural participle (which might be translated as "dream" in the present, or "dreamer," but certainly not "have dreamed" - on the exact translation see below), undeclined for person. However, the word ืึทืชึผึถื before ืึทืึฐืึฐืึดืื unambiguously makes it a second person plural address, that "you" are doing, and not the prophets mentioned previously.
>
> Is the NKJV correct to imply an active sense of either making yourself dream, or even others causing themselves to dream?
>
>
>
The word ืึทืึฐืึฐืึดืื is in the *hiph'il* form, which usually means causing someone to do something. For the translation, some ancient versions (LXX, Peshitta) ignore the different form and translate it as "dream" (as if it said ืืึนืึฐืึดืื), which might be a clue to confusion as how to translate, or possibly a different text (maybe it was erased due to being interpreted as an enclitic *mem*: rearranging the consonantal text gives ืืฉืจ ืืชื-ื ืืืืื).
However, according to the Masorah and the Targum, which echoes the *hiph'il* form of the Hebrew, it seems to be saying "which you cause to dream."
Some possible explanations:
* The explanation you propose, causing dreams through substances, is very creative, and fits the grammar, but I don't recall any mention of causing dreams through substances in the Bible
* One interpretation given is that "your dreams" are the dreams of the prophets with whom Jeremiah is disputing, and they are called "your dreams" because the people listened to them, and without their encouragement they wouldn't have continued to have those dreams ([Radaq](https://en.wikipedia.org/wiki/David_Kimhi)). This interpretation is seen as well in the NIV translation "Do not listen to the dreams you encourage them to have."
* I would like to propose reading ืึฐืึทืึฐึผืึดืื in the *pi''el* form, by analogy to ืึฐืึทืึตื (e.g. in Hosea 2:9), which differs from the *qal* ืืึนืึตื "lover" with the meaning "improper lover." Maybe ืึฐืึทืึฐึผืึดืื could also mean having an *improper* dream
>
> Is the NASB correct to imply that Israel was no longer to listen to anyone's dreams?
>
>
>
No. Jeremiah said the exile would last 70 years (29:10), and told them to build houses, marry, and pray for the welfare of their city (29:5-7). Other prophets were making the claim that the exile would be short and they would return to their land soon (28:3). This is the claim Jeremiah was disputing, which is far from saying "no longer to listen to anyone's dreams."
The dreams referred to here are those of a "ืึนืึตื ืึฒืืึนื" ("dreamer," Deuteronomy 13:2, in apposition to "ื ึธืึดืื," prophet). He was disputing very specific prophetic dreams, just as he disputes other prophets many other times in the book. The Greek and Aramaic translations tend to translate this sort of prophet as "false prophet" (unlike the Hebrew, which never says "false prophet"), and "dreams" in this context should be understood as "false dreams" - i.e., specifically the dreams Jeremiah was disputing. He is not addressing the reliability of dreams in general. | I suggest the answer is to be found in the previous chapter, when the false prophet Hananiah the son of Azzur was proclaiming as follows;
"Thus says the Lord of hosts, the God of Israel; I have broken the yoke of the king of Babylon. Within two years I will bring back to this place all the vessels of the Lord's house, which Nebuchadnezzar king of Babylon took away from this place. I will also bring back to this place Jeconiah the son of Jehoiakim, king of Judah, and all the exiles from Judah who went to Babylon." (Jeremiah ch29 vv2-4, RSV)
This could be called Hananiah's "dream". The historical context makes it probable that the false prophets amongst the exiles in Babylon were proclaiming the same dream. Of course this would be treason and subversion, from the king' of Babylon's point of view. That would explain why Jeremiah prophecies that Nebuchadnezzar would throw two of these prophets (Ahab the son of Kolaiah and Zedekiah the son of Maaseiah) into the fire to be roasted (ch29 vv21-22) |
4,672,619 | Yahoo blocks emails from our website. We've written them to reverse that decision without much luck. So we block site registrations from @yahoo.com emails. Our problem is Yahoo has other email domains besides @yahoo.com. For instance @ymail.com, @rocketmail.com, @btinternet.com, and I'm sure many more. Plus international domains.
So the question is, how do I check if an email domain belongs to Yahoo? I supposed I could try to find a definitive list of all Yahoo domains, but I'm sure there has to be a better way. For instance doing some kind of host lookup on the domain.
Are there any suggestions to do that in PHP? | 2011/01/12 | [
"https://Stackoverflow.com/questions/4672619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401019/"
]
| Definitive list is probably the best way to go. You don't want to have to do some kind of lookup every time someone registers for your site. But if you really don't want to use a static list, you should be able to use `getmxrr()` and see if the MX record is from yahoo. | ymail.com and rocketmail.com both list yahoo.com as their DNS MX servers, so that's an obvious giveaway. btinternet.com, however, doesn't.
You can use [`getmxrr()`](http://php.net/manual/en/function.getmxrr.php) to retrieve the MX list |
52,335,378 | I'm new to RxJS observables and I'm trying to resolve a rather simple use case.
In a service, I first make a http call that returns an item (as an observable). The item contains an array of ids, some of them repeated. For each distinct id, I need to call another http service (again returns an observable), and add its return value to the original item in place of the corresponding id. These calls should happen in parallel. Finally, once every call has completed, my service should return an observable of the original item, now with its sub-items in place.
To give a better idea, this is what it would look like with promises rather than observables:
```
MyService() {
return HttpGetMainItem()
.then(item => {
var promises = _.uniq(item.subItems)
.map(sid => HttpGetSubItem(sid)
.then(subItem => {
// add to matching item.subItems
}));
// wait for all promises to complete and return main item
return Promise.all(promises).then(() => item);
});
}
```
What would be the best way to accomplish this working with observables?
EDIT: from the answers it seems I wasn't very clear. The example with promises is just for clarity, in my case the http calls are actually Angular's HttpClient.get, so they return observables- I'm looking to do everything with observables. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52335378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463893/"
]
| I believe you need something like this:
```
import { from, forkJoin } from 'rxjs';
import { switchMap } from 'rxjs/operators';
itemWithSubItems$ = from(HttpGetMainItem()).pipe(
switchMap(item => {
const promises = _.uniq(item.subItems).map(item => HttpGetSubItem(item.sid));
return forkJoin(promises)
.map(resultArray => item.subItems = resultArray)
.map(_ => item);
})
);
```
First fetches the main item. Then use forkJoin to resolve all subqueries and enrich the main item. After that just return the main item. | Maybe you could use a lib like async.each -> <https://caolan.github.io/async/docs.html#each> (eachSeries maybe).
would be something like :
```
async.each(array, (obj, cb) => {
observable with obj in parameter and with subscriber result :
cb(err, subscriberRes);
}, (err, res) => {
console.log(res);
}
``` |
52,335,378 | I'm new to RxJS observables and I'm trying to resolve a rather simple use case.
In a service, I first make a http call that returns an item (as an observable). The item contains an array of ids, some of them repeated. For each distinct id, I need to call another http service (again returns an observable), and add its return value to the original item in place of the corresponding id. These calls should happen in parallel. Finally, once every call has completed, my service should return an observable of the original item, now with its sub-items in place.
To give a better idea, this is what it would look like with promises rather than observables:
```
MyService() {
return HttpGetMainItem()
.then(item => {
var promises = _.uniq(item.subItems)
.map(sid => HttpGetSubItem(sid)
.then(subItem => {
// add to matching item.subItems
}));
// wait for all promises to complete and return main item
return Promise.all(promises).then(() => item);
});
}
```
What would be the best way to accomplish this working with observables?
EDIT: from the answers it seems I wasn't very clear. The example with promises is just for clarity, in my case the http calls are actually Angular's HttpClient.get, so they return observables- I'm looking to do everything with observables. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52335378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463893/"
]
| Here's one way you can accomplish the above with rxjs.
1. Convert the promise to an observable using `from`.
2. In the outer pipe call `switchMap` so that you can call another observable and return that as the result of the outer observable. You're switching execution contexts.
3. Inside the switchMap do the map of subItems as you did before and then use `forkJoin` to create an Observable of all the elements' promise. ForkJoin will emit an array of all the results once all promise complete. It's like `promise.all`.
4. Add the items like you were planning to do before, and return the original item.
**Code**
```
from(HttpGetMainItem()).pipe(
switchMap(item =>
forkJoin(_.uniq(item.subItems).map(sid => HttpGetSubItem(sid)))
.pipe(
map(results => {
/* add results to matching items.subItems and */
return item;
})
)
)
);
```
I feel this looks a bit clunky, due to the need to retain the root item and the nesting it requires. You can use the selector parameter of switchMap to combine the outer and inner observable. You can use that parameter in place of the logic you had in `map()` and since both observables' results are passed you won't need any further nesting.
```
from(HttpGetMainItem()).pipe(
switchMap(
item => forkJoin(_.uniq(item.subItems).map(sid => HttpGetSubItem(sid))),
(item, results) => {
/* add results to matching items.subItems and */
return item;
}
)
);
``` | Maybe you could use a lib like async.each -> <https://caolan.github.io/async/docs.html#each> (eachSeries maybe).
would be something like :
```
async.each(array, (obj, cb) => {
observable with obj in parameter and with subscriber result :
cb(err, subscriberRes);
}, (err, res) => {
console.log(res);
}
``` |
52,335,378 | I'm new to RxJS observables and I'm trying to resolve a rather simple use case.
In a service, I first make a http call that returns an item (as an observable). The item contains an array of ids, some of them repeated. For each distinct id, I need to call another http service (again returns an observable), and add its return value to the original item in place of the corresponding id. These calls should happen in parallel. Finally, once every call has completed, my service should return an observable of the original item, now with its sub-items in place.
To give a better idea, this is what it would look like with promises rather than observables:
```
MyService() {
return HttpGetMainItem()
.then(item => {
var promises = _.uniq(item.subItems)
.map(sid => HttpGetSubItem(sid)
.then(subItem => {
// add to matching item.subItems
}));
// wait for all promises to complete and return main item
return Promise.all(promises).then(() => item);
});
}
```
What would be the best way to accomplish this working with observables?
EDIT: from the answers it seems I wasn't very clear. The example with promises is just for clarity, in my case the http calls are actually Angular's HttpClient.get, so they return observables- I'm looking to do everything with observables. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52335378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463893/"
]
| Here's one way you can accomplish the above with rxjs.
1. Convert the promise to an observable using `from`.
2. In the outer pipe call `switchMap` so that you can call another observable and return that as the result of the outer observable. You're switching execution contexts.
3. Inside the switchMap do the map of subItems as you did before and then use `forkJoin` to create an Observable of all the elements' promise. ForkJoin will emit an array of all the results once all promise complete. It's like `promise.all`.
4. Add the items like you were planning to do before, and return the original item.
**Code**
```
from(HttpGetMainItem()).pipe(
switchMap(item =>
forkJoin(_.uniq(item.subItems).map(sid => HttpGetSubItem(sid)))
.pipe(
map(results => {
/* add results to matching items.subItems and */
return item;
})
)
)
);
```
I feel this looks a bit clunky, due to the need to retain the root item and the nesting it requires. You can use the selector parameter of switchMap to combine the outer and inner observable. You can use that parameter in place of the logic you had in `map()` and since both observables' results are passed you won't need any further nesting.
```
from(HttpGetMainItem()).pipe(
switchMap(
item => forkJoin(_.uniq(item.subItems).map(sid => HttpGetSubItem(sid))),
(item, results) => {
/* add results to matching items.subItems and */
return item;
}
)
);
``` | I believe you need something like this:
```
import { from, forkJoin } from 'rxjs';
import { switchMap } from 'rxjs/operators';
itemWithSubItems$ = from(HttpGetMainItem()).pipe(
switchMap(item => {
const promises = _.uniq(item.subItems).map(item => HttpGetSubItem(item.sid));
return forkJoin(promises)
.map(resultArray => item.subItems = resultArray)
.map(_ => item);
})
);
```
First fetches the main item. Then use forkJoin to resolve all subqueries and enrich the main item. After that just return the main item. |
20,628,700 | I have the following (working) XAML for a ComboBox:
```
<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource MyEnumToStringConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
```
I don't like this code: In order to change how my enum is represented as a string, I also have to specify the look of the ComboBox ItemTemplate. What if I want to globally change the appearance of all my ComboBoxes?
Another solution is to specify the converter on the ItemSource binding:
```
<ComboBox
SelectedValue="{Binding SelectedItem}"
ItemsSource="{Binding Items, Converter={StaticResource MyEnumToStringConverter}}" />
```
I don't like this either since I want the ComboBox to store my real type, not the string representation of it.
What other alternatives do I have? | 2013/12/17 | [
"https://Stackoverflow.com/questions/20628700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/617658/"
]
| It is not necessary to set the `ItemTemplate` of each ComboBox, either in a Style or not.
Instead you could simply create a default DataTemplate for the enum type by setting its [DataType](http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype.aspx) property
```
<Window.Resources>
<local:MyEnumStringConverter x:Key="MyEnumStringConverter"/>
<DataTemplate DataType="{x:Type local:MyEnum}">
<TextBlock Text="{Binding Converter={StaticResource MyEnumStringConverter}}"/>
</DataTemplate>
...
</Window.Resources>
``` | You can create a new `MyEnumText` string based property that returns the `Description` attribute value of the enum value and bound your `TextBlock.Text` property to it as follows:
```
<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyEnumText}"/> <!--Bound to new Text property-->
</DataTemplate>
</ComboBox.ItemTemplate>
```
**Add `DescriptionAtrribute` attribute** to your enum values:
```
public enum MyEnum
{
[System.ComponentModel.Description("Value One")]
MyValue1 = 1,
[System.ComponentModel.Description("Value Two")]
MyValue2 = 2,
[System.ComponentModel.Description("Value Three")]
MyValue3 = 3
}
```
**Create an Extension method** for `Enum` class:
```
public static class EnumHelper
{
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
System.Reflection.FieldInfo field = type.GetField(name);
if (field != null)
{
System.ComponentModel.DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
}
```
**Add the new property `MyEnumText`** which returns a string, to your ViewModel:
```
public MyEnum MyEnumProperty { get; set; }
public string MyEnumText //New Property
{
get
{
return MyEnumProperty.GetDescription();
}
}
``` |
20,628,700 | I have the following (working) XAML for a ComboBox:
```
<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource MyEnumToStringConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
```
I don't like this code: In order to change how my enum is represented as a string, I also have to specify the look of the ComboBox ItemTemplate. What if I want to globally change the appearance of all my ComboBoxes?
Another solution is to specify the converter on the ItemSource binding:
```
<ComboBox
SelectedValue="{Binding SelectedItem}"
ItemsSource="{Binding Items, Converter={StaticResource MyEnumToStringConverter}}" />
```
I don't like this either since I want the ComboBox to store my real type, not the string representation of it.
What other alternatives do I have? | 2013/12/17 | [
"https://Stackoverflow.com/questions/20628700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/617658/"
]
| OP here. I reformulated the question [here](https://stackoverflow.com/questions/20635329/specify-converter-inside-datatemplate-in-usercontrol) and [got an answer](https://stackoverflow.com/questions/20635329/specify-converter-inside-datatemplate-in-usercontrol/#20638111) that applies also to this question. | You can create a new `MyEnumText` string based property that returns the `Description` attribute value of the enum value and bound your `TextBlock.Text` property to it as follows:
```
<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyEnumText}"/> <!--Bound to new Text property-->
</DataTemplate>
</ComboBox.ItemTemplate>
```
**Add `DescriptionAtrribute` attribute** to your enum values:
```
public enum MyEnum
{
[System.ComponentModel.Description("Value One")]
MyValue1 = 1,
[System.ComponentModel.Description("Value Two")]
MyValue2 = 2,
[System.ComponentModel.Description("Value Three")]
MyValue3 = 3
}
```
**Create an Extension method** for `Enum` class:
```
public static class EnumHelper
{
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
System.Reflection.FieldInfo field = type.GetField(name);
if (field != null)
{
System.ComponentModel.DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
}
```
**Add the new property `MyEnumText`** which returns a string, to your ViewModel:
```
public MyEnum MyEnumProperty { get; set; }
public string MyEnumText //New Property
{
get
{
return MyEnumProperty.GetDescription();
}
}
``` |
1,818,862 | ```
public AddressBookApp(){
frame = new JFrame("Address Book");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setBackground(Color.gray);
panel.setLayout(null);
frame.add(panel);
frame.setVisible(true);
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem insert = new JMenuItem("Import");
file.add(insert);
insert.addActionListener(this);
JMenuItem export = new JMenuItem("Export");
file.add(export);
export.addActionListener(this);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
exit.addActionListener(this);
Font f = new Font("Helvetica", Font.BOLD, 10);
btnadd = new JButton("Add");
btnadd.setFont(f);
btnadd.setBounds(200, 250, 80, 20);
panel.add(btnadd);
btnprev = new JButton("Previous");
btnprev.setBounds(40, 250, 80, 20);
btnprev.setFont(f);
btnprev.addActionListener(this);
panel.add(btnprev);
btnnxt = new JButton("Next");
btnnxt.setBounds(120, 250, 80, 20);
btnnxt.setFont(f);
btnnxt.addActionListener(this);
panel.add(btnnxt);
btndel = new JButton("Delete");
btndel.setBounds(280, 250, 80, 20);
btndel.setFont(f);
panel.add(btndel);
btnclear = new JButton("Clear");
btnclear.setBounds(360, 250, 80, 20);
btnclear.setFont(f);
btnclear.addActionListener(this);
panel.add(btnclear);
txtname = new JTextField("");
txtname.setBounds(210, 40, 160, 20);
txtname.setFont(f);
panel.add(txtname);
txtnum = new JTextField("");
txtnum.setBounds(210, 70, 160, 20);
txtnum.setFont(f);
panel.add(txtnum);
txtmob = new JTextField("");
txtmob.setBounds(210, 100, 160, 20);
txtmob.setFont(f);
panel.add(txtmob);
txtadd1 = new JTextField("");
txtadd1.setBounds(210, 130, 160, 20);
txtadd1.setFont(f);
panel.add(txtadd1);
lblname = new JLabel("Name");
lblname.setBounds(160, 40, 160, 20);
lblname.setFont(f);
panel.add(lblname);
lblnum = new JLabel("Number");
lblnum.setBounds(160, 70, 160, 20);
lblnum.setFont(f);
panel.add(lblnum);
lblmob = new JLabel("Mobile");
lblmob.setBounds(160, 100, 160, 20);
lblmob.setFont(f);
panel.add(lblmob);
lbladd1 = new JLabel("Address ");
lbladd1.setBounds(160, 130, 160, 20);
lbladd1.setFont(f);
panel.add(lbladd1);
}
public static void main(String[] args)
{
AddressBookApp ab = new AddressBookApp();
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Exit"))
System.exit(0);
else if (e.getActionCommand().equals("Import"))
{
importContacts();
}
else if (e.getActionCommand().equals("Export"));
{
exportContacts();
}
if (e.getSource() == btnnxt)
{
nextContact();
}
else if (e.getSource() == btnprev)
{
prevContact();
}
}
public void importContacts()
{
try{
BufferedReader fileSize = new BufferedReader(new FileReader("../files/example.buab"));
BufferedReader importContacts = new BufferedReader(new FileReader("../files/example.buab"));
int i = 0;
String contacts;
while (( fileSize.readLine()) !=null)
{
details.add(importContacts.readLine());
i++;
}
fileSize.close();
int x = 0;
int y = 0;
for (x = 0, y = 0; x < details.size(); x++, y++)
{
if (y == 4)
{
y = 0;
}
if (y == 0)
{
name.add(details.get(x));
}
if (y == 1)
{
phone.add(details.get(x));
}
if (y == 2)
{
mobile.add(details.get(x));
}
if (y == 3)
{
address.add(details.get(x));
}
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
txtname.setText(name.get(0));
txtnum.setText(phone.get(0));
txtmob.setText(mobile.get(0));
txtadd1.setText(address.get(0));
}
public void exportContacts()
{
FileOutputStream file;
PrintStream out;
try { file = new FileOutputStream("../files/example.buab", true);
out = new PrintStream(file);
out.println(txtname.getText());
out.println(txtnum.getText());
out.println(txtmob.getText());
out.println(txtadd1.getText());
System.err.println ("");
out.close();
}
catch (Exception e)
{
System.err.println ("Error in writing to file");
}
}
public void nextContact()
{
if(index < details.size() - 1)
{
index++;
txtname.setText(name.get(index));
txtnum.setText(phone.get(index));
txtmob.setText(mobile.get(index));
txtadd1.setText(address.get(index));
}
importContacts();
}
public void prevContact()
{
if (index > 0)
{
index--;
txtname.setText(name.get(index));
txtnum.setText(phone.get(index));
txtmob.setText(mobile.get(index));
txtadd1.setText(address.get(index));
}
importContacts();
}
```
} | 2009/11/30 | [
"https://Stackoverflow.com/questions/1818862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/221246/"
]
| From the code I see no reason, why it should export data after pressing the next or previous button. Don't forget to close the streams after reading.
Just for curiosity - I've seen a lot of partial solutions to this assignment from various new SO users - and they have in common, that the assignees *seems* to lack some basic OO knowledge. Who advised you to drop the contact details in separate lists rather then inventing a Contact class that holds all contact attributes and dropping contact objects in a single (sortable) list? Have you been forced to avoid classes or has your teacher simply left you alone, finding it out yourself?
Good luck anyway :) | Your problem is the semicolon at the end of this line:
```
else if (e.getActionCommand().equals("Export"));
``` |
57,512 | I plan on building a web based room booking application for meeting rooms at a company. The requirements are not set in stone and are pretty much left to me, as long as these core ones are met:
1. Users can view monthly schedule for meeting room, so see what days and times there are bookings for a particular room.
2. Users can book a meeting room
3. Users can edit,delete a booking once made.
4. Receptionists have power to cancel bookings, even though they were not the ones that made them.
If I have missed any obvious ones, please point them out.
So with the above in mind, I have come up with the following ERD.

Can you see any obvious issues with the above ERD? I have gone through the above scenarios / requirements, and I believe the above design satisfies them all, but it is possible that I am very much mistaken (has happened before).
Any help and feedback would be greatly appreciated. | 2014/01/24 | [
"https://dba.stackexchange.com/questions/57512",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/20381/"
]
| I agree with Wiggler Jtag's recommendation. Here's why:
Describe the relationship between `USER` and `ROOM`. If it is "a user can have zero, one, or more rooms booked" then you have a one to many relationship.
Describe the relationship between `ROOM` and `USER`. If it is "a room can have zero, one, or more bookings by a user" then this is also a one to many relationship.
Using normalization, you would define an intersection table. You have this defined as `BOOKING`. `BOOKING` should contain the PKs (primary keys) from `USER` and `ROOM`. PKs should be unique. The `BOOKING` entity would have attributes `USER_ID`, `ROOM_ID`, `DATETIME`, and `TITLE`.
If you wish to ensure that only one USER can book a ROOM for a particular `DATETIME`, then you can add a unique concatenated index on `BOOKING` of `ROOM_ID`, `DATETIME`. This will ensure that there will be only one row for a room at a particular time.
Primary index (or unique index) on the `PKs` of `USER` and `ROOM` will also ensure that you don't have more than one row per user or one row per room. | The problem with the current design is that we are unable to uniquely identify which room a user has booked if he has booked more than 1 room .
To solve the problem , we should add another column : **Room Number** to the TABLE ROOM
This allows the **composite key** : Room Number& ID to form a **primary key** which would uniquely identify any booking made by a user.
The Room Number & ID would be foreign keys in the TABLE BOOKING |
57,512 | I plan on building a web based room booking application for meeting rooms at a company. The requirements are not set in stone and are pretty much left to me, as long as these core ones are met:
1. Users can view monthly schedule for meeting room, so see what days and times there are bookings for a particular room.
2. Users can book a meeting room
3. Users can edit,delete a booking once made.
4. Receptionists have power to cancel bookings, even though they were not the ones that made them.
If I have missed any obvious ones, please point them out.
So with the above in mind, I have come up with the following ERD.

Can you see any obvious issues with the above ERD? I have gone through the above scenarios / requirements, and I believe the above design satisfies them all, but it is possible that I am very much mistaken (has happened before).
Any help and feedback would be greatly appreciated. | 2014/01/24 | [
"https://dba.stackexchange.com/questions/57512",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/20381/"
]
| How do you know how long a room is booked for? Your model indicates when a booking starts, but when does it end?
Also, your ERD shows foreign keys from `BOOKING` to `USER` and `ROOM` but these columns aren't acknowledged in your `BOOKING` table. Some other answers have interpreted that as the columns being missing. You should be explicit in your diagram to avoid confusion (or add the FK columns if you missed them!) | I agree with Wiggler Jtag's recommendation. Here's why:
Describe the relationship between `USER` and `ROOM`. If it is "a user can have zero, one, or more rooms booked" then you have a one to many relationship.
Describe the relationship between `ROOM` and `USER`. If it is "a room can have zero, one, or more bookings by a user" then this is also a one to many relationship.
Using normalization, you would define an intersection table. You have this defined as `BOOKING`. `BOOKING` should contain the PKs (primary keys) from `USER` and `ROOM`. PKs should be unique. The `BOOKING` entity would have attributes `USER_ID`, `ROOM_ID`, `DATETIME`, and `TITLE`.
If you wish to ensure that only one USER can book a ROOM for a particular `DATETIME`, then you can add a unique concatenated index on `BOOKING` of `ROOM_ID`, `DATETIME`. This will ensure that there will be only one row for a room at a particular time.
Primary index (or unique index) on the `PKs` of `USER` and `ROOM` will also ensure that you don't have more than one row per user or one row per room. |
57,512 | I plan on building a web based room booking application for meeting rooms at a company. The requirements are not set in stone and are pretty much left to me, as long as these core ones are met:
1. Users can view monthly schedule for meeting room, so see what days and times there are bookings for a particular room.
2. Users can book a meeting room
3. Users can edit,delete a booking once made.
4. Receptionists have power to cancel bookings, even though they were not the ones that made them.
If I have missed any obvious ones, please point them out.
So with the above in mind, I have come up with the following ERD.

Can you see any obvious issues with the above ERD? I have gone through the above scenarios / requirements, and I believe the above design satisfies them all, but it is possible that I am very much mistaken (has happened before).
Any help and feedback would be greatly appreciated. | 2014/01/24 | [
"https://dba.stackexchange.com/questions/57512",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/20381/"
]
| How do you know how long a room is booked for? Your model indicates when a booking starts, but when does it end?
Also, your ERD shows foreign keys from `BOOKING` to `USER` and `ROOM` but these columns aren't acknowledged in your `BOOKING` table. Some other answers have interpreted that as the columns being missing. You should be explicit in your diagram to avoid confusion (or add the FK columns if you missed them!) | The problem with the current design is that we are unable to uniquely identify which room a user has booked if he has booked more than 1 room .
To solve the problem , we should add another column : **Room Number** to the TABLE ROOM
This allows the **composite key** : Room Number& ID to form a **primary key** which would uniquely identify any booking made by a user.
The Room Number & ID would be foreign keys in the TABLE BOOKING |
16,976,335 | Assume we constructed a quicksort and the pivot value takes linear time. Find the recurrence for worst-case running time.
My answer:
T(n)= T(n-1) + T(1) + theta(n)
Worst case occurs when the subarrays are completely unbalanced.
There is 1 element in one subarray and (n-1) elements in the other subarray.
theta(n) because it takes running time n to find the pivot.
Am I doing this correctly? | 2013/06/07 | [
"https://Stackoverflow.com/questions/16976335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855045/"
]
| Your recurrence is mostly correct, but you don't actually have two recursive calls made. In the worst-case for quicksort, the pivot will be the largest or smallest element in the array, so you'll recur on one giant array of size n - 1. The other subarray has length 0, so no recursive calls are made. To top everything off, the total work done is ฮ(n) per level, so the recurrence relation would more appropriately be
>
> T(n) = T(n - 1) + ฮ(n)
>
>
>
This in turn then solves to ฮ(n2).
Hope this helps! | you cannot observe, because according to my research T(N)= T(N-K)+T(K-1)+n
we cannot observe exact value until we have
value of k, |
16,976,335 | Assume we constructed a quicksort and the pivot value takes linear time. Find the recurrence for worst-case running time.
My answer:
T(n)= T(n-1) + T(1) + theta(n)
Worst case occurs when the subarrays are completely unbalanced.
There is 1 element in one subarray and (n-1) elements in the other subarray.
theta(n) because it takes running time n to find the pivot.
Am I doing this correctly? | 2013/06/07 | [
"https://Stackoverflow.com/questions/16976335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855045/"
]
| Your recurrence is mostly correct, but you don't actually have two recursive calls made. In the worst-case for quicksort, the pivot will be the largest or smallest element in the array, so you'll recur on one giant array of size n - 1. The other subarray has length 0, so no recursive calls are made. To top everything off, the total work done is ฮ(n) per level, so the recurrence relation would more appropriately be
>
> T(n) = T(n - 1) + ฮ(n)
>
>
>
This in turn then solves to ฮ(n2).
Hope this helps! | T(n) = T(an/(a+b)) + T(bn/(a+b)) + n
Where a/(a+b) and b/(a+b) are fractions of array under consideration |
16,976,335 | Assume we constructed a quicksort and the pivot value takes linear time. Find the recurrence for worst-case running time.
My answer:
T(n)= T(n-1) + T(1) + theta(n)
Worst case occurs when the subarrays are completely unbalanced.
There is 1 element in one subarray and (n-1) elements in the other subarray.
theta(n) because it takes running time n to find the pivot.
Am I doing this correctly? | 2013/06/07 | [
"https://Stackoverflow.com/questions/16976335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855045/"
]
| you cannot observe, because according to my research T(N)= T(N-K)+T(K-1)+n
we cannot observe exact value until we have
value of k, | T(n) = T(an/(a+b)) + T(bn/(a+b)) + n
Where a/(a+b) and b/(a+b) are fractions of array under consideration |
18,393,312 | I have a simple button, and I want to use CSS to make it onhover, bring up a dropdown of a few more buttons with links, and when the button is pressed I want the button to stay at the onhover state. How can this be accomplished? For example a games button that when hovered over it drops down to buttons that have different links to games. Sorry if this is unclear. Thanks in advanced. | 2013/08/23 | [
"https://Stackoverflow.com/questions/18393312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565624/"
]
| When you make those two synchronized, the getter and setter themselves are thread-safe. More specifically:
- When you call the setter, you are guaranteed that the value of the variable is what you set it to when the method finishes.
- When you call the getter, you are guaranteed that the return value is the value of the variable when you made the call.
However, making the getter and setter *themselves* thread-safe does not mean that the application *as a whole* (i.e. whatever is using this class) is thread-safe. If your thread wants to call a setter then get the same value upon invoking the getter, that involves synchronization on a different level.
As far as thread-safety is concerned, a thread-safe class need not control **how** its methods are invoked (for example, it need not control which way the threads interleave their calls), but it needs to ensure that **when** they are, the methods do what they are supposed to. | `synchronized` in Java is an object-wide lock. Only one `synchronized` method of any given object can be executed on any given thread at a time. Let's have this class:
```
class Foo
{
private int bar;
public synchronized void SetBar() { ... }
public synchronized int GetBar() { ... }
}
```
* Thread 1 calls `SetBar()`. Thread 1 acquires the object lock.
* Thread 2 wants to call `SetBar()`, but Thread 1 holds the lock. Thread 2 is now queued to acquire the lock when Thread 1 will release it.
* Thread 1 finishes executing `SetBar()` and releases the lock.
* Thread 2 immediately acquires the lock and starts executing `SetBar()`.
* Thread 1 calls `GetBar()`. Thread 1 is now queued to acquire the lock when Thread 2 will release it.
* Thread 2 finishes executing `SetBar()` and releases the lock.
* Thread 1 acquires the lock, executes `GetBar()`, and is done with it.
You did the work twice, but you didn't cause any race condition. It may or may not be erroneous to do the work twice, depending on what it is.
A frequent pattern is to have one thread produce content and one other thread do something useful with it. This is called the producer-consumer pattern. In this case, there is no confusion over who or what tries to `SetBar()` and what tries to `GetBar()`. |
18,393,312 | I have a simple button, and I want to use CSS to make it onhover, bring up a dropdown of a few more buttons with links, and when the button is pressed I want the button to stay at the onhover state. How can this be accomplished? For example a games button that when hovered over it drops down to buttons that have different links to games. Sorry if this is unclear. Thanks in advanced. | 2013/08/23 | [
"https://Stackoverflow.com/questions/18393312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565624/"
]
| >
> I figured the class could not be made thread-safe since even if you synchronize both methods, you could have a situation that Thread1 would invoke the setter and before Thread1 could invoke the getter, Thread2 might execute and invoke the setter, so that when Thread1 went and retrieved the result it would get the wrong info. Is this the right way to look at things?
>
>
>
You are correct with this. There is no way to guarantee that a thread will not have called either of the methods in between your calls of each of the methods, **from within the class**.
If you do want to do this, that will require a wrapper class.
So if the class with the getter and setter is like so:
```
class Foo
{
private static int bar;
public static synchronized void SetBar(int z) { ... }
public static synchronized int GetBar() { ... }
}
```
The wrapper class would look something like this:
```
class FooWrapper
{
public synchronized int SetGetBar(int z)
{
Foo.SetBar(z);
return Foo.GetBar();
}
}
```
The only way to guarantee this will work is if you can guarantee that all calls will go through your wrapper class rather than directly to class Foo. | `synchronized` in Java is an object-wide lock. Only one `synchronized` method of any given object can be executed on any given thread at a time. Let's have this class:
```
class Foo
{
private int bar;
public synchronized void SetBar() { ... }
public synchronized int GetBar() { ... }
}
```
* Thread 1 calls `SetBar()`. Thread 1 acquires the object lock.
* Thread 2 wants to call `SetBar()`, but Thread 1 holds the lock. Thread 2 is now queued to acquire the lock when Thread 1 will release it.
* Thread 1 finishes executing `SetBar()` and releases the lock.
* Thread 2 immediately acquires the lock and starts executing `SetBar()`.
* Thread 1 calls `GetBar()`. Thread 1 is now queued to acquire the lock when Thread 2 will release it.
* Thread 2 finishes executing `SetBar()` and releases the lock.
* Thread 1 acquires the lock, executes `GetBar()`, and is done with it.
You did the work twice, but you didn't cause any race condition. It may or may not be erroneous to do the work twice, depending on what it is.
A frequent pattern is to have one thread produce content and one other thread do something useful with it. This is called the producer-consumer pattern. In this case, there is no confusion over who or what tries to `SetBar()` and what tries to `GetBar()`. |
65,743,711 | I'm building an app that detects sensors and shows the user information about the sensors automatically.
So I created a main page with a single tab to show a label saying "detecting", and when the system detects a sensor, a new page is opened with three tabs containing information about the sensor.
But I'm having some difficulties because I can't pass the sensor ID to the second page. I would like to know what am I doing wrong, and why the Props.params is undefined.
I'm trying to do something like that:
[](https://i.stack.imgur.com/pUfW3.png)
Main page tab navigator:
```
render() {
return (
<NavigationContainer independent={true} >
<Tab.Navigator>
<Tab.Screen
name="Detection"
component={DetectScreen}
options={{
tabBarLabel: 'Detect',
tabBarIcon: ({ color, size }) => (
<MaterialCommunityIcons name="motion-sensor" color={color} size={size} />
),
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
}
function DetectScreen() {
const Stack = createStackNavigator();
return (
<Stack.Navigator initialRouteName='Detect' screenOptions={{ headerShown: false }}>
<Stack.Screen name='Detect' component={DetectionScreen} />
<Stack.Screen name='Sensor' component={SensorScreen} />
</Stack.Navigator>
);
}
function DetectionScreen({ navigation }) {
return (
<SafeAreaView>
<LinearGradient
colors={['#000000', '#FFFFFF']}
style={styles.main_container}>
<SafeAreaView>
<Detect navigation={navigation} />
</SafeAreaView>
</LinearGradient>
</SafeAreaView>)
}
function SensorScreen({ navigation }) {
return (
<SafeAreaView>
<LinearGradient
colors={['#000000', '#FFFFFF']}
style={styles.main_container}>
<SafeAreaView style={styles.main_subcontainer}>
<Sensor navigation={navigation}/>
</SafeAreaView>
</LinearGradient>
</SafeAreaView>)
}
```
Detect class
```
export class Detect extends Component {
constructor(props) {
super(props);
startDetecting()
}
startDetecting(){
this.props.navigation.navigate("Sensor", {
params:{
sensorId: 123
}
})
}
}
```
Opening screen when the sensor is detected
```
const Stack = createStackNavigator();
const Tab = createMaterialTopTabNavigator();
function TabStack() {
return (
<Tab.Navigator
initialRouteName="Configurations"
>
<Tab.Screen
name="FirstScreen"
component={FirstScreen}
options={{
tabBarLabel: 'First'
}} />
<Tab.Screen
name="SecondScreen"
component={SecondScreen}
options={{
tabBarLabel: 'Second'
}} />
<Tab.Screen
name="ThirdScreen"
component={ThirdScreen}
options={{
tabBarLabel: 'Third'
}} />
</Tab.Navigator>
);
}
export class Sensor extends Component {
constructor(props) {
super(props);
console.log(props.params) //props.params is Undefined
}
render() {
return (
<NavigationContainer
independent={true}
>
<Stack.Navigator
initialRouteName="Sensor"
screenOptions={{
headerShown: false
}}>
<Stack.Screen
name="TabStack"
component={TabStack}
options={{ title: 'Tab Stack' }}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
}
``` | 2021/01/15 | [
"https://Stackoverflow.com/questions/65743711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6596416/"
]
| According to you the `heavyModule` is not a React component
>
> I have a very heavy raw file **parsed as string** (around 10 mb) and I would like to lazy load it
>
>
>
So you cannot use `React.lazy()`. Instead i would recommend to import the raw file only where you require it and then render that particular component lazily.
You can try this method :
```
useEffect(()=> {
import('./heavyModule').then(data=> {
// your code
},[])
``` | The official doc states that "In the future we plan to let Suspense handle more scenarios such as data fetching. You can read about this in our roadmap.". The Roadmap mentioned an update to expect in late 2019. But it still is not implemented. This is detailed in this recent issue <https://github.com/reactjs/reactjs.org/issues/4829>
All in all, if `heavyModule` does not contain any React component it is simpler to go back to a simpler approach to set the state when the `value` has been recovered.
```
componentDidMount() {
import("./heavyModule").then((heavyModule) => {
this.setState({value: heavyModule.value})
})
);
}
```
And in the view, you can have some conditional rendering
```
render() {
const valueRender = value ? <div>{value}</div> : <div>Loading...</div>
return ({valueRender})
}
``` |
4,287,814 | If the joint frequency function of random variables $X$ and $Y$ is given by:
$f\_{X,Y}(x,y)=\alpha \beta e^{-\alpha x-\beta y}$ $\,\,\,\,x\geq 0$ $\,\,\,\,y\geq 0$
then to get, for example, the marginal density function of $Y$ we would integrate the joint frequency function with respect to $X$.
This would give $f\_Y(y)=\beta e^{-\beta y}$.
What I'm not totally clear on is how you would use this. I understand the discrete case, where if you want the marginal density of $Y=2$, you sum the row or column of $Y=2$ across all the $X$ values.
Here, how would you get the marginal probability that $Y$ takes on a value in a certain interval? It seems like you should integrate but what would the bounds be? Any help is appreciated. | 2021/10/26 | [
"https://math.stackexchange.com/questions/4287814",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/904065/"
]
| $P(c<Y<d)=\int\_c^{d}\int\_{-\infty}^{\infty} f\_{X,Y}(x,y) dxdy$ | The marginal density is defined as $$f\_Y(y) = \int f(x, y) dx$$. In this case, you treat $y$ as a constant, giving you $$\int\_0^\infty \alpha \beta e^{-\alpha x - \beta y} dx = \beta e^{-\beta y} \int\_0^\infty \alpha e^{-\alpha x} dx = \beta e^{-\beta y}$$ |
4,287,814 | If the joint frequency function of random variables $X$ and $Y$ is given by:
$f\_{X,Y}(x,y)=\alpha \beta e^{-\alpha x-\beta y}$ $\,\,\,\,x\geq 0$ $\,\,\,\,y\geq 0$
then to get, for example, the marginal density function of $Y$ we would integrate the joint frequency function with respect to $X$.
This would give $f\_Y(y)=\beta e^{-\beta y}$.
What I'm not totally clear on is how you would use this. I understand the discrete case, where if you want the marginal density of $Y=2$, you sum the row or column of $Y=2$ across all the $X$ values.
Here, how would you get the marginal probability that $Y$ takes on a value in a certain interval? It seems like you should integrate but what would the bounds be? Any help is appreciated. | 2021/10/26 | [
"https://math.stackexchange.com/questions/4287814",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/904065/"
]
| the given density can be rewritten in the following way
$$f\_{XY}(x,y)=\alpha e^{-\alpha x}\times \beta e^{-\beta x}=f\_X(x)\times f\_Y(y)$$
thus you immediately get your marginals as independent exponentials | The marginal density is defined as $$f\_Y(y) = \int f(x, y) dx$$. In this case, you treat $y$ as a constant, giving you $$\int\_0^\infty \alpha \beta e^{-\alpha x - \beta y} dx = \beta e^{-\beta y} \int\_0^\infty \alpha e^{-\alpha x} dx = \beta e^{-\beta y}$$ |
4,287,814 | If the joint frequency function of random variables $X$ and $Y$ is given by:
$f\_{X,Y}(x,y)=\alpha \beta e^{-\alpha x-\beta y}$ $\,\,\,\,x\geq 0$ $\,\,\,\,y\geq 0$
then to get, for example, the marginal density function of $Y$ we would integrate the joint frequency function with respect to $X$.
This would give $f\_Y(y)=\beta e^{-\beta y}$.
What I'm not totally clear on is how you would use this. I understand the discrete case, where if you want the marginal density of $Y=2$, you sum the row or column of $Y=2$ across all the $X$ values.
Here, how would you get the marginal probability that $Y$ takes on a value in a certain interval? It seems like you should integrate but what would the bounds be? Any help is appreciated. | 2021/10/26 | [
"https://math.stackexchange.com/questions/4287814",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/904065/"
]
| $P(c<Y<d)=\int\_c^{d}\int\_{-\infty}^{\infty} f\_{X,Y}(x,y) dxdy$ | the given density can be rewritten in the following way
$$f\_{XY}(x,y)=\alpha e^{-\alpha x}\times \beta e^{-\beta x}=f\_X(x)\times f\_Y(y)$$
thus you immediately get your marginals as independent exponentials |
69,395 | In the context of the scholarly apparatus package [`ednotes`](http://www.ctan.org/pkg/ednotes) I would like to create a customized `\Bnote` which behaves like a normal LaTeX footnote; i.e., I would like to enter into the body of the text something like
```
blah blah.\Bnote{a}{This is the footnote text.} Blah blah blah...
```
And the footnote would appear below the `\Anote` layer and would look something like
>
> a This is the footnote text.
>
>
>
Within the `ednotes.sty` file there are a number of commands that can be modified to customize `\Bnote`, but I haven't been able to see how to get this behavior. Why, you ask, do I not just use the standard footnote utility? Because it comes out ABOVE the `\Anote` layer. Just to be clear, the default behavior in ednote that I am trying to override is using the line number as the footnote reference.
I am using LuaLaTeX and TeXShop. | 2012/08/30 | [
"https://tex.stackexchange.com/questions/69395",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/17054/"
]
| I suspect that it is possible to create a hack that puts "normal" footnotes below the "apparatus" notes of `ednotes`. As I don't know how to do that, here's a second-best solution that
* removes the line numbers from and changes the mark format of `\Bnote`;
* defines a new macro `\Bfootnote` that tinkers with the `footnote` counter to produce (hopefully) correct automatic numbering of "apparatus B" notes.
---
```
\documentclass{article}
\usepackage[Bplain]{ednotes}
\linenumbers
\newcommand{\Bnotefmt}{%
\renewcommand*{\sameline}[1]{\linesfmt{##1}}%
\renewcommand*{\differentlines}[2]{\linesfmt{##1\textendash##2}}%
% \renewcommand*{\linesfmt}[1]{\textbf{##1}\enspace}% DELETED
\renewcommand*{\linesfmt}[1]{}% NEW
\renewcommand*{\pageandline}[2]{##1.##2}% ##1 page, ##2 line.
\renewcommand*{\repeatref}[1]{##1}% E.g., ...
\renewcommand*{\repeatref}[1]{\textnormal{/}}% ... instead.
% \renewcommand{\lemmafmt}[1]{##1\thinspace]\enskip}% DELETED
\renewcommand{\lemmafmt}[1]
{\stepcounter{footnote}\textsuperscript{##1}\addtocounter{footnote}{-1}}% NEW
\renewcommand{\lemmaellipsis}{\textsymmdots}%
\renewcommand{\notefmt}[1]{##1}%
}
\newcommand*{\Bfootnote}[1]{%
\addtocounter{footnote}{-1}%
\Bnote{\footnotemark}{#1}%
}
\begin{document}
\null\vfill% just for the example
Some text \Anote{a}{An apparatus A note.}.
Some text.\Bfootnote{An apparatus B note that behaves like a normal footnote.}
Some text.\Bfootnote{And another one.}
\end{document}
```
 | In the meantime I (`ednotes`'s author) have told by mail: `ednotes` uses `manyfoot` as "footnote engine". `ednotes`'s setup of footnote layers uses `manyfoot`'s setup to create layers of footnotes without footnote marks. To get the footnote marks "back", I think one should not try from within `ednotes`, better use `manyfoot` directly.
In the previous solution, I see the redefinition of `\linesfmt`. That is very right, some seconds before I had looked at the code and discovered it myself. Paul had discovered `\lemmafmt` before. That above solution really looks like that it should work; but `manyfoot` already offers a counter that should better be used directly. |
69,395 | In the context of the scholarly apparatus package [`ednotes`](http://www.ctan.org/pkg/ednotes) I would like to create a customized `\Bnote` which behaves like a normal LaTeX footnote; i.e., I would like to enter into the body of the text something like
```
blah blah.\Bnote{a}{This is the footnote text.} Blah blah blah...
```
And the footnote would appear below the `\Anote` layer and would look something like
>
> a This is the footnote text.
>
>
>
Within the `ednotes.sty` file there are a number of commands that can be modified to customize `\Bnote`, but I haven't been able to see how to get this behavior. Why, you ask, do I not just use the standard footnote utility? Because it comes out ABOVE the `\Anote` layer. Just to be clear, the default behavior in ednote that I am trying to override is using the line number as the footnote reference.
I am using LuaLaTeX and TeXShop. | 2012/08/30 | [
"https://tex.stackexchange.com/questions/69395",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/17054/"
]
| I suspect that it is possible to create a hack that puts "normal" footnotes below the "apparatus" notes of `ednotes`. As I don't know how to do that, here's a second-best solution that
* removes the line numbers from and changes the mark format of `\Bnote`;
* defines a new macro `\Bfootnote` that tinkers with the `footnote` counter to produce (hopefully) correct automatic numbering of "apparatus B" notes.
---
```
\documentclass{article}
\usepackage[Bplain]{ednotes}
\linenumbers
\newcommand{\Bnotefmt}{%
\renewcommand*{\sameline}[1]{\linesfmt{##1}}%
\renewcommand*{\differentlines}[2]{\linesfmt{##1\textendash##2}}%
% \renewcommand*{\linesfmt}[1]{\textbf{##1}\enspace}% DELETED
\renewcommand*{\linesfmt}[1]{}% NEW
\renewcommand*{\pageandline}[2]{##1.##2}% ##1 page, ##2 line.
\renewcommand*{\repeatref}[1]{##1}% E.g., ...
\renewcommand*{\repeatref}[1]{\textnormal{/}}% ... instead.
% \renewcommand{\lemmafmt}[1]{##1\thinspace]\enskip}% DELETED
\renewcommand{\lemmafmt}[1]
{\stepcounter{footnote}\textsuperscript{##1}\addtocounter{footnote}{-1}}% NEW
\renewcommand{\lemmaellipsis}{\textsymmdots}%
\renewcommand{\notefmt}[1]{##1}%
}
\newcommand*{\Bfootnote}[1]{%
\addtocounter{footnote}{-1}%
\Bnote{\footnotemark}{#1}%
}
\begin{document}
\null\vfill% just for the example
Some text \Anote{a}{An apparatus A note.}.
Some text.\Bfootnote{An apparatus B note that behaves like a normal footnote.}
Some text.\Bfootnote{And another one.}
\end{document}
```
 | Following up on Uwe's suggestion, here is another approach that produces the same output as lockstep's (though without the automatic counters):
```
\documentclass{article}
\usepackage{ednotes}
\linenumbers
\newfootnote{Z}
\newcommand\footnoteZ[2]{\Footnotemark{#1}\FootnotetextZ{}{#2}}
\begin{document}
\null\vfill% just for the example
Some text \Anote{a}{An apparatus A note.}.
Some text.\footnoteZ{1}{An apparatus B note that behaves like a normal footnote.}
Some text.\footnoteZ{2}{And another one.}
\end{document}
```
The `\newfootnote{}` command is part of the `manyfoot` package loaded by `ednote`. |
69,395 | In the context of the scholarly apparatus package [`ednotes`](http://www.ctan.org/pkg/ednotes) I would like to create a customized `\Bnote` which behaves like a normal LaTeX footnote; i.e., I would like to enter into the body of the text something like
```
blah blah.\Bnote{a}{This is the footnote text.} Blah blah blah...
```
And the footnote would appear below the `\Anote` layer and would look something like
>
> a This is the footnote text.
>
>
>
Within the `ednotes.sty` file there are a number of commands that can be modified to customize `\Bnote`, but I haven't been able to see how to get this behavior. Why, you ask, do I not just use the standard footnote utility? Because it comes out ABOVE the `\Anote` layer. Just to be clear, the default behavior in ednote that I am trying to override is using the line number as the footnote reference.
I am using LuaLaTeX and TeXShop. | 2012/08/30 | [
"https://tex.stackexchange.com/questions/69395",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/17054/"
]
| In the meantime I (`ednotes`'s author) have told by mail: `ednotes` uses `manyfoot` as "footnote engine". `ednotes`'s setup of footnote layers uses `manyfoot`'s setup to create layers of footnotes without footnote marks. To get the footnote marks "back", I think one should not try from within `ednotes`, better use `manyfoot` directly.
In the previous solution, I see the redefinition of `\linesfmt`. That is very right, some seconds before I had looked at the code and discovered it myself. Paul had discovered `\lemmafmt` before. That above solution really looks like that it should work; but `manyfoot` already offers a counter that should better be used directly. | Following up on Uwe's suggestion, here is another approach that produces the same output as lockstep's (though without the automatic counters):
```
\documentclass{article}
\usepackage{ednotes}
\linenumbers
\newfootnote{Z}
\newcommand\footnoteZ[2]{\Footnotemark{#1}\FootnotetextZ{}{#2}}
\begin{document}
\null\vfill% just for the example
Some text \Anote{a}{An apparatus A note.}.
Some text.\footnoteZ{1}{An apparatus B note that behaves like a normal footnote.}
Some text.\footnoteZ{2}{And another one.}
\end{document}
```
The `\newfootnote{}` command is part of the `manyfoot` package loaded by `ednote`. |
22,487,520 | Tested with TRAC v 1.0
I stumbled with users can see projects, they don't have access to. I did not wanted them to see only "no permission" on these projects, I simply wanted to hide it completely, when a user don't have the permission to see the project.
Here's a q'n'd "solution", by just moving two lines of code to another place.
If some of you need it, just change it as shown below.
Replace:
```
for project_name in sorted(projects.keys()):
has_access = True
can_show = True
if (project_name == "--None Project--"):
div_project = '<br><div id="project"><fieldset><legend><h2>Unbenanntes Projekt</h2></legend>'
else:
project_info = self.__SmpModel.get_project_info(project_name)
if project_info:
if hide_closed and project_info[4] > 0: # column 4 of table smp_project tells if project is closed
can_show = False
if self.__SmpModel.is_not_in_restricted_users(req.authname, project_info):
has_access = False
div_project = '<br><div id="project"><fieldset><legend><b>Projekt </b> <em style="font-size: 12pt; color: black;">%s</em></legend>' % project_name
if can_show and has_access and project_info and show_proj_descr:
div_project = div_project + '<div class="description" xml:space="preserve">'
if project_info[2]:
div_project = div_project + '%s<br/><br/>' % project_info[2]
div_project = div_project + '%s</div>' % wiki_to_html(project_info[3], self.env, req)
div_milestone = ''
if can_show and len(projects[project_name]) > 0:
if has_access:
for milestone in projects[project_name]:
mi = '<em>%s</em>' % milestone
for i in range(len(div_milestones_array)):
if(div_milestones_array[i].find(mi)>0):
div_milestone = div_milestone + div_milestones_array[i]
else:
div_milestone = '<em style="color: red;">no permission</em>'
div_project = div_project + to_unicode(div_milestone) + '</fieldset></div>'
div_projects_milestones = to_unicode(div_projects_milestones + div_project)
stream_div_projects_milestones = HTML(div_projects_milestones)
return stream_div_projects_milestones
```
with:
```
for project_name in sorted(projects.keys()):
has_access = True
can_show = True
project_info = self.__SmpModel.get_project_info(project_name)
if self.__SmpModel.is_not_in_restricted_users(req.authname, project_info):
has_access = False
if has_access:
if (project_name == "--None Project--"):
div_project = '<br><div id="project"><fieldset><legend><h2>Unbenanntes Projekt</h2></legend>'
else:
if project_info:
if hide_closed and project_info[4] > 0: # column 4 of table smp_project tells if project is closed
can_show = False
div_project = '<br><div id="project"><fieldset><legend><b>Projekt </b> <em style="font-size: 12pt; color: black;">%s</em></legend>' % project_name
if can_show and has_access and project_info and show_proj_descr:
div_project = div_project + '<div class="description" xml:space="preserve">'
if project_info[2]:
div_project = div_project + '%s<br/><br/>' % project_info[2]
div_project = div_project + '%s</div>' % wiki_to_html(project_info[3], self.env, req)
div_milestone = ''
if can_show and len(projects[project_name]) > 0:
if has_access:
for milestone in projects[project_name]:
mi = '<em>%s</em>' % milestone
for i in range(len(div_milestones_array)):
if(div_milestones_array[i].find(mi)>0):
div_milestone = div_milestone + div_milestones_array[i]
else:
div_milestone = '<em style="color: red;">no permission</em>'
div_project = div_project + to_unicode(div_milestone) + '</fieldset></div>'
div_projects_milestones = to_unicode(div_projects_milestones + div_project)
stream_div_projects_milestones = HTML(div_projects_milestones)
return stream_div_projects_milestones
```
in **simplemultiproject/roadmap.py**
Restart your apache web server and you will see only projects you have acess to. | 2014/03/18 | [
"https://Stackoverflow.com/questions/22487520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1478230/"
]
| Well, after a while messing around with this "solution" i ran into a few problems when setting different filters. After looking again into the script, I saw that there just 2 lines needed to be changed.
This is my new and better solution:
Just replace the code above with this one.
```
for project_name in sorted(projects.keys()):
has_access = True
can_show = True
if (project_name == "--None Project--"):
div_project = '<br><div id="project"><fieldset><legend><h2>Unbenanntes Projekt</h2></legend>'
else:
project_info = self.__SmpModel.get_project_info(project_name)
if project_info:
if hide_closed and project_info[4] > 0: # column 4 of table smp_project tells if project is closed
can_show = False
if self.__SmpModel.is_not_in_restricted_users(req.authname, project_info):
has_access = False
div_project = '<br><div id="project"><fieldset><legend><b>Projekt </b> <em style="font-size: 12pt; color: black;">%s</em></legend>' % project_name
if can_show and has_access and project_info and show_proj_descr:
div_project = div_project + '<div class="description" xml:space="preserve">'
if project_info[2]:
div_project = div_project + '%s<br/><br/>' % project_info[2]
div_project = div_project + '%s</div>' % wiki_to_html(project_info[3], self.env, req)
div_milestone = ''
if has_access:
if can_show and len(projects[project_name]) > 0:
for milestone in projects[project_name]:
mi = '<em>%s</em>' % milestone
for i in range(len(div_milestones_array)):
if(div_milestones_array[i].find(mi)>0):
div_milestone = div_milestone + div_milestones_array[i]
else:
div_milestone = '<em style="color: red;">no permission</em>'
div_project = div_project + to_unicode(div_milestone) + '</fieldset></div>'
div_projects_milestones = to_unicode(div_projects_milestones + div_project)
stream_div_projects_milestones = HTML(div_projects_milestones)
return stream_div_projects_milestones
```
The according diff is:
```
Index: simplemultiprojectplugin/trunk/simplemultiproject/roadmap.py
===================================================================
--- simplemultiprojectplugin/trunk/simplemultiproject/roadmap.py (revision 13785)
+++ simplemultiprojectplugin/trunk/simplemultiproject/roadmap.py (working copy)
@@ -157,8 +157,9 @@
div_milestone = ''
- if can_show and len(projects[project_name]) > 0:
- if has_access:
+ if has_access:
+ if can_show and len(projects[project_name]) > 0:
+
for milestone in projects[project_name]:
mi = '<em>%s</em>' % milestone
for i in range(len(div_milestones_array)):
``` | Meanwhile this question is completely outdated and obsolete since the code has completely changed over the years. Please close your question or accept this as answer. |
46,666,293 | I want to list the VPC id's which have a particular tag (Name=MyVPC).
I am aware that I can use `--filter` and run:
```
aws ec2 describe-vpcs --filters Name=tag:Name,Values=MyVPC --query 'Vpcs[].VpcId'
```
This works completely fine.
Is there a way I can achieve this without using `--filter` and only use JMESPath? | 2017/10/10 | [
"https://Stackoverflow.com/questions/46666293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6775514/"
]
| ```
aws ec2 describe-vpcs --query 'Vpcs[?Tags[?Key==`Name`]|[?Value==`MyVPC`]].VpcId' --output text
``` | Try this command:
```
aws ec2 describe-vpcs --query 'Vpcs[?contains(Tags[?Key==`Name`].Value[], `MyVPC`) == `true`].[VpcId]' --output text
``` |
333,165 | I'm trying to use find & rsync to back up specific files from a remote machine, and getting nowhere.
Here's the setup: I want to use rsync to back up all files containing `*state*` or `*srm` on the remote machine into a local directory. I specifically want to run this from my local machine, rather than running it with find on the remote machine (a RetroPie, if you're curious), because I don't want to set up login credentials from the remote machine. I already have ssh keys set up properly. I'm aiming to backup into ~/retropie-backup locally.
The find command that I'm using works properly on the remote machine (truncated to one result for clarity):
```
$ find -iname "*state*" -o -iname "*srm"
./RetroPie/roms/snes/EarthBound (USA).srm
```
So far so good. I also know that I need to add -s to rsync so it doesn't panic over spaces in the file names. My attempt at combining the two, however, doesn't work:
```
$ rsync -v -s pi@retropie:'`find -iname "*state*" -o -iname "*srm"`' retropie-backup/
rsync: link_stat "/home/pi/`find -iname "*state*" -o -iname "*srm"`" failed: No such file or directory (2)
```
I can tell that I'm missing something basic, but I'm just not seeing it. Any suggestions? | 2016/12/28 | [
"https://unix.stackexchange.com/questions/333165",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/207451/"
]
| There are a couple of ways of skinning this cat
You can use another `ssh` invocation to generate the list of files, and pipe that into your `rsync`. This version requires the GNU extension `find -print0` to handle filenames that might contain whitespace, newlines, or other non-printing characters.
```
ssh -nq pi find -type f \( -iname "*state*" -o -iname "*srm" \) -print0 |
rsync --dry-run -aiv --from0 --files-from - pi@retropie: retropie-backup/
```
Another approach is to have `rsync` directly include only these files. Here you need to include all directories so that `rsync` will descend into them, include the files of consideration, and then exclude everything else. Finally you need to tell `rsync` to skip directories that would end up with no content.
```
rsync --dry-run -aiv --include '*/' --include '*state*' --include '*srm' --exclude '*' --prune-empty-dirs pi@retropie: retropie-backup/
```
In both cases remove `--dry-run` to perform the action once you're happy it's selected the correct set of files. | The `find` has to run on the remote machine, which looks like what you are trying to do except your syntax isn't right. Backticks can only run commands on the local machine. You must `ssh` into the remote machine to run `find`.
```
ssh pi@retropie find ... >./filelist
rsync -v -files-from ./filelist pi@retropie: retropie-backup/
``` |
27,277,713 | I have this query:
```
Select
DescFornecedor, DescUsuario, Classificacao,
Sum(Tempo) as Tempo,
Case Classificacao
When 'Agendamento' Then 2
When 'Aguardando cadastro' Then 3
When 'Descarte' Then 8
When 'Desistรชncia' Then 7
When 'Em Pausa' Then 4
When 'Em Volta' Then 10
When 'Entrevista' Then 1
When 'Filtro' Then 5
When 'Outros' Then 9
When 'Recusa' Then 6
When 'Sem Atividade' Then 11
End as Ordem
from
vwProducaoGeralTempoLogadoSemAtividade t1 With(NoLock)
Where
Not Exists (Select 0
from vwProducaoGeralTempoLogadoSemAtividade t2 With(NoLock)
Where T1.CodUsuario = t2.CodUsuario
Group by CodUsuario
Having Sum(tempo) <> MAx(tempoLogado))
Group By
DescFornecedor, DescUsuario, Classificacao
```
When we use it, it returns the results in 30~1min.
Now I've made some adjustments:
```
Select DescFornecedor,DescUsuario,Classificacao,Sum(t1.Tempo) as Tempo,
Case Classificacao
When 'Agendamento' Then 2
When 'Aguardando cadastro' Then 3
When 'Descarte' Then 8
When 'Desistรชncia' Then 7
When 'Em Pausa' Then 4
When 'Em Volta' Then 10
When 'Entrevista' Then 1
When 'Filtro' Then 5
When 'Outros' Then 9
When 'Recusa' Then 6
When 'Sem Atividade' Then 11
End as Ordem
from vwProducaoGeralTempoLogadoSemAtividade t1 With(NoLock)
inner join (
select CodUsuario, SUM(tempo) as Tempo, MAX(tempologado) as TempoLogado
from vwProducaoGeralTempoLogadoSemAtividade with(nolock)
group by CodUsuario
) t2
on t1.CodUsuario = t2.CodUsuario and
t2.Tempo = t2.TempoLogado
Group By DescFornecedor,DescUsuario,Classificacao
```
But i's stil slow ! lasting 10~20secs.
How can i improve this query?
i'm out of ideas.
don't know what to do with the time comparison.
Thank you very much.
( Indexes and stats are ok, not even the trace can help me now ) | 2014/12/03 | [
"https://Stackoverflow.com/questions/27277713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4210181/"
]
| add height to `<td rowspan="2" height="100px">`
<http://jsfiddle.net/p55czapy/24/> | ```
<table>
<tr>
<td><input type="button" class="button" value="1"></td>
<td><input type="button" class="button" value="2"></td>
<td><input type="button" class="button" value="3"></td>
<td rowspan="2" style="height: 100%;"><input type="button" class="button" value="-" style="height:100%;"></td>
<td rowspan="2" style="height: 100%;">
<input type="button" class="button" value="=" style="height:100%;">
</td>
</tr>
<tr>
<td colspan="3">
<input type="button" class="button" value="0" style="width:100%;"></td>
<td><input type="button" class="button" value="+"></td>
</tr>
</table>
```
Please try this hope it will help |
19,121,105 | I have long running code, that gets battered with requests, it causes higher resource usage and unneeded concurrency problems. My solution is to have like a waiting area, where each thread waits for some predefined time. If there is no new request while the thread is waiting, it goes ahead with the operation. Any new request will reset the clock again and we release the previous thread.
I have used Semaphores and countdown latches before, but neither of them work for this particular scenario. Before I hand code this, I wanted to see if there is a standard way of doing it. | 2013/10/01 | [
"https://Stackoverflow.com/questions/19121105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577334/"
]
| >
> I have long running code, that gets battered with requests, it causes higher resource usage and unneeded concurrency problems.
>
>
>
Sounds to me that you should be using a throttled `ExecutorService`. You should have a fixed number of threads and *not* let new threads be created whenever a new request comes in. Then you can maximize you throughput by tuning the number of threads in the pool.
```
// only allow 10 concurrent requests
ExecutorService threadPool = Executors.newFixedThreadPool(10);
...
while (requestsComeIn) {
threadPool.submit(yourRunnableRequest);
}
// you need to shut the pool down once no more requests come in
threadPool.shutdown();
```
To throttle the requests, you should use a `RejectedExecutionHandler`. Something like the following code should work which blocks after 100 elements are in the queue:
```
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
ThreadPoolExecutor threadPool =
new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, queue);
// we need our RejectedExecutionHandler to block if the queue is full
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// this will block the producer until there's room in the queue
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(
"Unexpected InterruptedException", e);
}
}
});
```
>
> My solution is to have like a waiting area, where each thread waits for some predefined time.
>
>
>
You get this for free with the `ThreadPoolExecutor`. For example, you could allocate 1 core threads and 10 max threads and then specify (for example) `5L, TimeUnit.MINUTES` so if one of the 5 extra threads is dormant for 5 minutes it will get shutdown. It is important to note that, unfortunately, the `ThreadPoolExecutor` will not start more than the core threads *unless* the queue is full. So only after 100 things are in the queue does the 2nd thread get allocated. For that reason I usually make the core and max thread params to be the same value. | The tidiest way of keeping control is to use a queue. The modern `BlockingQueue` classes do an excellent job. You can then throttle by varying the length of the queue.
Instead of actually doing the work yourself you post a `Job` into the queue and have one or more threads sitting at the other end of the queue doing all of the work.
There is actually a structure ready-made for implementing this exact architecture, It is called an `ExecutorService`. There are many examples of use elsewhere.
See [ExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html) for details. |
37,666,573 | I have the HTML below:
```
<div id="div_2_1_3" class="Button CoachView CoachView_show"
data-type="com.ibm.bpm.coach.Snapshot_5b0cf92e_d5be_41c3_b0d3_f101b717826c.Button"
data-binding="" data-bindingtype="" data-config="config3"
data-viewid="Button3" data-eventid="boundaryEvent_4">
<button type="button" class="BPMButton BPMButtonBorder"
```
and I have to click in button that class is BPMButton BPMButtonBorder.
I am trying this code, but is returning the error: Run-time error: '438': Object doesn't support this property or method.
How can I click on BPMButton BPMButtonBorder?
```
sub html
Set divs = ie.getElementBytagname("div")
For Each divi In divs
If divi.id = "div_2_1_3" Then Set botoes = ie.Document.getElementsByTagName("BUTTON")
For Each bt In botoes
If bt.ClassName = "BPMButton BPMButtonBorder" Then
bt.Click
Exit For
End If
Next bt
Next divi
end sub
``` | 2016/06/06 | [
"https://Stackoverflow.com/questions/37666573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5150025/"
]
| Try something like this:
```
Sub html
Dim div, botoes, bt
'edit - added missing .document
Set div = ie.document.getElementById("div_2_1_3")
Set botoes = div.getElementsByTagName("BUTTON")
For Each bt In botoes
Debug.Print bt.ClassName
If bt.ClassName = "BPMButton BPMButtonBorder" Then
bt.Click
Exit For
End If
Next bt
end sub
``` | Tim, I believe that was missing **document** after **ie.**.
It works with this code:
```
Set botoes = ie.Document.getElementsByTagName("button")
For Each bt In botoes
Debug.Print bt.innertext
If bt.innertext = "Run Now" Then
bt.Click
Exit For
End If
Next bt
``` |
23,860,945 | I have an `AJAX` script updating a database via `PHP`.
I am then trying to return two variables back to the `AJAX` success function.
Currently, when alerting the data returned they are showing `UNDEFINED`.
When I return the `JSON` without stating the part of the array I require, the array displays in full. But only when I state specifically which value from the array I wish to use, I seem to get undefined on both values.
`How should I manage these values returned from the PHP?`
**The AJAX**
```
success: function(data) {
$('#'+data.toUpdate).html(data.quant);
$('#'+data.toUpdate).addClass('updated_grn');
alert('quant:' + data.quant + '\nid:' + data.toUpdate);
}
```
**The PHP**
```
if ($query) {
echo json_encode(array("toUpdate" => $toUpdate, "quant" => $quant));
}
```
**The Result**

When I `alert(data)` this is returned:

**The full php**
```
$itemid = ($_POST['itemid']);
$quant = ($_POST['quant']);
$toUpdate = ($_POST['toUpdate']);
$sql = "UPDATE items_list
SET `stock_level` = '$quant'
WHERE item_id = '$itemid'";
$query = mysql_query($sql);
if ($query) {
echo json_encode(array("toUpdate" => $toUpdate, "quant" => $quant));
}
```
**The full AJAX**
```
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: {
itemid: itemid,
quant: quant,
toUpdate: toUpdate
},
beforeSend: function() {
$('#'+id+'_num')
.html("<img src='xxxxxxx.com/home/secure/images/gif/ajax-loader.gif'></img>");
},
success: function(data) {
alert(data);
// $('#'+data.toUpdate).html(data.quant);
// $('#'+data.toUpdate).addClass('updated_grn');
// alert('quant:' + data.quant + '\nid:' + data.toUpdate);
}
});
``` | 2014/05/25 | [
"https://Stackoverflow.com/questions/23860945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459692/"
]
| Just change `dataType: 'html'` to `dataType: 'json'` :) | Make sure that `$query` is true. I would also do `die()` so nothing else is in output:
```
if ($query) {
die(json_encode(array("toUpdate" => $toUpdate, "quant" => $quant)));
}
```
You can always check what you get from **PHP**:
```
success: function(data) {
alert(data);
$('#'+data.toUpdate).html(data.quant);
$('#'+data.toUpdate).addClass('updated_grn');
alert('quant:'+data.quant+'\nid:'+data.toUpdate);
}
``` |
23,860,945 | I have an `AJAX` script updating a database via `PHP`.
I am then trying to return two variables back to the `AJAX` success function.
Currently, when alerting the data returned they are showing `UNDEFINED`.
When I return the `JSON` without stating the part of the array I require, the array displays in full. But only when I state specifically which value from the array I wish to use, I seem to get undefined on both values.
`How should I manage these values returned from the PHP?`
**The AJAX**
```
success: function(data) {
$('#'+data.toUpdate).html(data.quant);
$('#'+data.toUpdate).addClass('updated_grn');
alert('quant:' + data.quant + '\nid:' + data.toUpdate);
}
```
**The PHP**
```
if ($query) {
echo json_encode(array("toUpdate" => $toUpdate, "quant" => $quant));
}
```
**The Result**

When I `alert(data)` this is returned:

**The full php**
```
$itemid = ($_POST['itemid']);
$quant = ($_POST['quant']);
$toUpdate = ($_POST['toUpdate']);
$sql = "UPDATE items_list
SET `stock_level` = '$quant'
WHERE item_id = '$itemid'";
$query = mysql_query($sql);
if ($query) {
echo json_encode(array("toUpdate" => $toUpdate, "quant" => $quant));
}
```
**The full AJAX**
```
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: {
itemid: itemid,
quant: quant,
toUpdate: toUpdate
},
beforeSend: function() {
$('#'+id+'_num')
.html("<img src='xxxxxxx.com/home/secure/images/gif/ajax-loader.gif'></img>");
},
success: function(data) {
alert(data);
// $('#'+data.toUpdate).html(data.quant);
// $('#'+data.toUpdate).addClass('updated_grn');
// alert('quant:' + data.quant + '\nid:' + data.toUpdate);
}
});
``` | 2014/05/25 | [
"https://Stackoverflow.com/questions/23860945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459692/"
]
| Just change `dataType: 'html'` to `dataType: 'json'` :) | FYI.
I found this problem when using WordPress (4.3.1) and tried to load json data to D3.json function inside WordPress. json\_encode(some\_array) did not work but returned undefined. It returned a single integer value but not any array. UTF-8 check or anything else did not help.
Then incidently I closed the php ajax function by wp\_die() command, it was missing there. And voila!, this suddenly works, json\_encode returns array fine.
Hopefully this helps someone. |
39,836,839 | I have an array of objects with three properties each (year, total, per\_capita).
Example:
```
0: Object
per_capita: "125.8"
total: "1007.2"
year: "2009"
```
Those properties are strings and I want to create a loop that goes through the array and converts them to int.
I tried the following loop:
```
for (i=0; i<data.length; i++){
parseInt(data[i].year, 10)
parseInt(data[i].total, 10)
parseInt(data[i].per_capita, 10)
}
```
However when I do typeof(data[0].total) it says its a string.
I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type.
Anyone have an idea where the problem is? | 2016/10/03 | [
"https://Stackoverflow.com/questions/39836839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4876564/"
]
| [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) does not mutate objects but parses a string and returns a integer. You have to re-assign the parsed values back to the object properties.
```
for (i=0; i<data.length; i++){
data[i].year = parseInt(data[i].year, 10)
data[i].total = parseInt(data[i].total, 10)
data[i].per_capita = parseInt(data[i].per_capita, 10)
}
``` | All you did was the conversion, but you missed the assignment:
```
for (i=0; i<data.length; i++){
data[i].year = parseInt(data[i].year, 10)
data[i].total = parseInt(data[i].total, 10)
data[i].per_capita = parseInt(data[i].per_capita, 10)
}
```
The `parseInt` function returns the int value, it doesn't change the input variable.
Another thing - if you need the total number to be float you should use the `parseFloat` function and not the `parseInt`. |
39,836,839 | I have an array of objects with three properties each (year, total, per\_capita).
Example:
```
0: Object
per_capita: "125.8"
total: "1007.2"
year: "2009"
```
Those properties are strings and I want to create a loop that goes through the array and converts them to int.
I tried the following loop:
```
for (i=0; i<data.length; i++){
parseInt(data[i].year, 10)
parseInt(data[i].total, 10)
parseInt(data[i].per_capita, 10)
}
```
However when I do typeof(data[0].total) it says its a string.
I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type.
Anyone have an idea where the problem is? | 2016/10/03 | [
"https://Stackoverflow.com/questions/39836839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4876564/"
]
| [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) does not mutate objects but parses a string and returns a integer. You have to re-assign the parsed values back to the object properties.
```
for (i=0; i<data.length; i++){
data[i].year = parseInt(data[i].year, 10)
data[i].total = parseInt(data[i].total, 10)
data[i].per_capita = parseInt(data[i].per_capita, 10)
}
``` | You could iterate the array and the object amd assign the integer value of the properties, you want.
```
data.forEach(function (a) {
['year', 'total', 'per_capita'].forEach(function (k) {
a[k] = Math.floor(+a[k]);
});
});
``` |
39,836,839 | I have an array of objects with three properties each (year, total, per\_capita).
Example:
```
0: Object
per_capita: "125.8"
total: "1007.2"
year: "2009"
```
Those properties are strings and I want to create a loop that goes through the array and converts them to int.
I tried the following loop:
```
for (i=0; i<data.length; i++){
parseInt(data[i].year, 10)
parseInt(data[i].total, 10)
parseInt(data[i].per_capita, 10)
}
```
However when I do typeof(data[0].total) it says its a string.
I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type.
Anyone have an idea where the problem is? | 2016/10/03 | [
"https://Stackoverflow.com/questions/39836839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4876564/"
]
| This should help!
```js
var a = {
per_capita: "125.8",
total: "1007.2",
year: "2009",
}
Object.keys(a).forEach(function(el){
a[el] = parseInt(a[el])
})
console.log(a)
console.log(typeof a.total)
``` | All you did was the conversion, but you missed the assignment:
```
for (i=0; i<data.length; i++){
data[i].year = parseInt(data[i].year, 10)
data[i].total = parseInt(data[i].total, 10)
data[i].per_capita = parseInt(data[i].per_capita, 10)
}
```
The `parseInt` function returns the int value, it doesn't change the input variable.
Another thing - if you need the total number to be float you should use the `parseFloat` function and not the `parseInt`. |
39,836,839 | I have an array of objects with three properties each (year, total, per\_capita).
Example:
```
0: Object
per_capita: "125.8"
total: "1007.2"
year: "2009"
```
Those properties are strings and I want to create a loop that goes through the array and converts them to int.
I tried the following loop:
```
for (i=0; i<data.length; i++){
parseInt(data[i].year, 10)
parseInt(data[i].total, 10)
parseInt(data[i].per_capita, 10)
}
```
However when I do typeof(data[0].total) it says its a string.
I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type.
Anyone have an idea where the problem is? | 2016/10/03 | [
"https://Stackoverflow.com/questions/39836839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4876564/"
]
| This should help!
```js
var a = {
per_capita: "125.8",
total: "1007.2",
year: "2009",
}
Object.keys(a).forEach(function(el){
a[el] = parseInt(a[el])
})
console.log(a)
console.log(typeof a.total)
``` | You could iterate the array and the object amd assign the integer value of the properties, you want.
```
data.forEach(function (a) {
['year', 'total', 'per_capita'].forEach(function (k) {
a[k] = Math.floor(+a[k]);
});
});
``` |
56,094,484 | I am using MathJax and I have the following scenario:
>
> I want to run some code when the page contains some Math that MathJax will process and render properly
>
>
>
Consider this example:
```html
<p>
This is a page containing an equation: $b^2 - 4ac$.
</p>
```
Here the function, or whatever it is I can use, would return `true`. But if the page contains no chunk of TeX code to process (or any code according to how MathJax was configured to trigger), then this API would return `false`.
### A bit more details
This is not about modifying the rendering pipeline. MathJax will eventually do its job and I am fine with it. I just need a reliable way (hopefully provided by the library's API) to detect that the page has some math that will need processing.
Does MathJax has a functionality that I can use to get this info? Also, for completeness, I am adding the way I am configuring MathJax (inline):
```
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/CommonHTML"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"CommonHTML": { linebreaks: { automatic: true } }
});
</script>
<script src="//mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML"></script>
```
### Alternatively...
If what I am asking is not actually feasible, then how about this:
>
> Can I attach to an event in the rendering pipeline so I get to execute a callback function when MathJax is done rendering the math?
>
>
>
I saw the [MathJax startup sequence](http://docs.mathjax.org/en/latest/advanced/startup.html) and there lies my answer probably. However I see the trigger is run also when there is no math on the page.
---
### Troubleshoot
I have tried to detect the presence of classes like `MathJax_Preview` or `mjx-chtml` which are added to the elements that are generated. But this code is not reliable as it needs to trigger after the rendering process. And this adds time to the computation.
I cound not find the API I am looking for for querying the presence of math to render, but it seems strange there is not such a thing exposed by MathJax. | 2019/05/11 | [
"https://Stackoverflow.com/questions/56094484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519836/"
]
| A possible workaround is to create your own class, then test if this class is present in the DOM, then embed mathjax dynamically if needed
Snippet with math :
```js
var test = document.querySelectorAll('.math2Process');
if(test.length>0){
var mathJax_config = document.createElement('script');
mathJax_config.setAttribute('type','text/x-mathjax-config');
mathJax_config.text = `MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/CommonHTML"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"CommonHTML": { linebreaks: { automatic: true } }
});`
var mathJax_script = document.createElement('script');
mathJax_script.setAttribute('src','//mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML');
document.head.appendChild(mathJax_config);
document.head.appendChild(mathJax_script);
}
```
```html
<p class="math2Process">
This is a page containing an equation: $b^2 - 4ac$.
</p>
```
the same but no math :
```js
var test = document.querySelectorAll('.math2Process');
if(test.length>0){
var mathJax_config = document.createElement('script');
mathJax_config.setAttribute('type','text/x-mathjax-config');
mathJax_config.text = `MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/CommonHTML"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"CommonHTML": { linebreaks: { automatic: true } }
});`
var mathJax_script = document.createElement('script');
mathJax_script.setAttribute('src','//mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML');
document.head.appendChild(mathJax_config);
document.head.appendChild(mathJax_script);
}
```
```html
<p>
This is a page containing an equation: $b^2 - 4ac$.
</p>
``` | The following code will check if the current page requires MathJax, and only load in the script if it is needed:
```html
<script>
document.addEventListener('DOMContentLoaded', () => {
const skipHtmlTags = ['script', 'noscript', 'style', 'textarea', 'pre', 'code', 'annotation', 'annotation-xml'].map((v) => `:not(${v})`).join('')
const ignoreHtmlClasses = ['mathjax_ignore'].map((v) => `:not(.${v})`).join('')
const requiresMathjax = Array.from(document.body.querySelectorAll('*' + skipHtmlTags + ignoreHtmlClasses))
.some((el) => el.textContent.match(/\\\(|\$\$|\\\[/))
if (requiresMathjax) {
const sc = document.createElement('script')
sc.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.min.js')
sc.setAttribute('integrity', 'sha512-9DkJEmXbL/Tdj8b1SxJ4H2p3RCAXKsu8RqbznEjhFYw0cFIWlII+PnGDU2FX3keyE9Ev6eFaDPyEAyAL2cEX0Q==')
sc.setAttribute('crossorigin', 'anonymous')
sc.setAttribute('referrerpolicy', 'no-referrer')
document.head.appendChild(sc)
}
})
</script>
```
minified:
```
document.addEventListener("DOMContentLoaded",()=>{var t=["script","noscript","style","textarea","pre","code","annotation","annotation-xml"].map(t=>`:not(${t})`).join(""),e=["mathjax_ignore"].map(t=>`:not(.${t})`).join("");if(Array.from(document.body.querySelectorAll("*"+t+e)).some(t=>t.textContent.match(/\\\(|\$\$|\\\[/))){const n=document.createElement("script");n.setAttribute("src","https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.min.js"),n.setAttribute("integrity","sha512-9DkJEmXbL/Tdj8b1SxJ4H2p3RCAXKsu8RqbznEjhFYw0cFIWlII+PnGDU2FX3keyE9Ev6eFaDPyEAyAL2cEX0Q=="),n.setAttribute("crossorigin","anonymous"),n.setAttribute("referrerpolicy","no-referrer"),document.head.appendChild(n)}});
```
You have `inlineMath: [ ['$','$'], ["\\(","\\)"] ],`, but you probably will want to stop using just a single dollar sign--you'll get too many false-positives. If you want to keep using a single dollar sign, you can update the regex in the script.
If you'd like a different script, update the `src` and `integrity` attributes using the URLs at <https://cdnjs.com/libraries/mathjax> (or your preferred CDN) |
17,292,630 | I have a mysql query.
The idea is to select the records between a date range. The dates are stored as unix timestamps. With the query below, I end up with far more records than I should (out of the date range).
I have picked my brain and I cant see where the query is going wrong. The other fields look correct, its just that I am out of the desired date range.
```
SELECT
mdl_user_info_data.data,
mdl_user.firstname,
mdl_user.lastname,
mdl_grade_grades.itemid,
mdl_grade_items.itemname,
mdl_quiz.fcpd,
mdl_user_info_data.id,
mdl_grade_grades.timecreated AS DATE
FROM mdl_grade_grades
INNER JOIN mdl_user ON mdl_grade_grades.userid = mdl_user.id
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.id
INNER JOIN mdl_quiz ON mdl_grade_items.courseid = mdl_quiz.course
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
WHERE mdl_grade_grades.timecreated BETWEEN (FROM_UNIXTIME(1371704400) AND FROM_UNIXTIME(1371790800))
AND mdl_user_info_data.fieldid = 1
AND mdl_grade_items.itemname IS NOT NULL
AND mdl_course.category = 27
OR mdl_grade_items.itemname LIKE '%asa%'
GROUP BY mdl_user.firstname, mdl_user.lastname, mdl_grade_grades.timecreated
``` | 2013/06/25 | [
"https://Stackoverflow.com/questions/17292630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1882752/"
]
| AFAIK, the svc is useless if you are not working with IIS. Outside of IIS, the so called self hosted approach, needs you to write a something like this, where HelloWorldWcfServiceMessage is your type implementing the service contract. Additionaly, don't forget to configure an endpoint for the server and to make sure you are allowed to open a service on the configured port. The following code you can use in windows service or in a console program (better for testing and debugging). Hope that helps and I got your question right.
```
...
this.serviceHost = new ServiceHost(typeof(HelloWorldWcfServiceMessage));
this.serviceHost.Open();
...
public class HelloWorldWcfServiceMessage : IHelloWorldWcfServiceMessage
{
}
[ServiceContract(Namespace = "http://HelloWorldServiceNamespace", Name = "PublicHelloWorldWCFService")]
public interface IHelloWorldWcfServiceMessage
{
[OperationContract]
string HelloWorldMessage(string name);
}
``` | I think there is some confusion with the names.
In the SVC you wrote:
CodeBehind="Service1.svc.cs"
But you say your file name is Service.svc.cs (without the 1). |
17,292,630 | I have a mysql query.
The idea is to select the records between a date range. The dates are stored as unix timestamps. With the query below, I end up with far more records than I should (out of the date range).
I have picked my brain and I cant see where the query is going wrong. The other fields look correct, its just that I am out of the desired date range.
```
SELECT
mdl_user_info_data.data,
mdl_user.firstname,
mdl_user.lastname,
mdl_grade_grades.itemid,
mdl_grade_items.itemname,
mdl_quiz.fcpd,
mdl_user_info_data.id,
mdl_grade_grades.timecreated AS DATE
FROM mdl_grade_grades
INNER JOIN mdl_user ON mdl_grade_grades.userid = mdl_user.id
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.id
INNER JOIN mdl_quiz ON mdl_grade_items.courseid = mdl_quiz.course
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
WHERE mdl_grade_grades.timecreated BETWEEN (FROM_UNIXTIME(1371704400) AND FROM_UNIXTIME(1371790800))
AND mdl_user_info_data.fieldid = 1
AND mdl_grade_items.itemname IS NOT NULL
AND mdl_course.category = 27
OR mdl_grade_items.itemname LIKE '%asa%'
GROUP BY mdl_user.firstname, mdl_user.lastname, mdl_grade_grades.timecreated
``` | 2013/06/25 | [
"https://Stackoverflow.com/questions/17292630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1882752/"
]
| AFAIK, the svc is useless if you are not working with IIS. Outside of IIS, the so called self hosted approach, needs you to write a something like this, where HelloWorldWcfServiceMessage is your type implementing the service contract. Additionaly, don't forget to configure an endpoint for the server and to make sure you are allowed to open a service on the configured port. The following code you can use in windows service or in a console program (better for testing and debugging). Hope that helps and I got your question right.
```
...
this.serviceHost = new ServiceHost(typeof(HelloWorldWcfServiceMessage));
this.serviceHost.Open();
...
public class HelloWorldWcfServiceMessage : IHelloWorldWcfServiceMessage
{
}
[ServiceContract(Namespace = "http://HelloWorldServiceNamespace", Name = "PublicHelloWorldWCFService")]
public interface IHelloWorldWcfServiceMessage
{
[OperationContract]
string HelloWorldMessage(string name);
}
``` | **Solved this**
This is all about Publishing a WCF service on IIS 8
All the credits goes to Gyรถrgy Balรกssy
WCF services donโt run on IIS 8 with the default conแguration, because the webserver doesnโt know, how to handle incoming requests targeting .svc แles. You can teach it in two steps:
Please check the same answer here.
<https://stackoverflow.com/a/45979587/3059688> |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| You can also use [Regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) with `i` modifier to perform case-insensitive matching and the method [RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
* It is very convenient when you want to evaluate multiple object properties like:
```js
new RegExp(searchString, 'i').test(
person.email || person.firstName || person.lastName
)
```
Code:
```js
const people = [{ firstName: 'Bob', lastName: 'Smith', status: 'single' }, { firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' }, { firstName: 'Jim', lastName: 'Johnson', status: 'complicated' }, { firstName: 'Sally', lastName: 'Fields', status: 'relationship' }, { firstName: 'Robert', lastName: 'Bobler', status: 'single' }, { firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' }, { firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship', rogueBonusKey: 'bob likes salmon' }]
const searchString = 'Bob'
const found = people.filter(({ firstName }) =>
new RegExp(searchString, 'i').test(firstName))
console.log(found)
``` | Array.prototype.filter() also works as well:
```
const includesQuery = (value) => {
return value['SOME_KEY'].toLowerCase().includes(query.toLowerCase());
}
const filtered = this.myArray.filter(includesQuery);
console.log(filtered);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| If we assume that all properties are strings, then you might do in the following way
```
const people = [
// ...
]
const searchString = 'Bob'
const filterBy = (term) => {
const termLowerCase = term.toLowerCase()
return (person) =>
Object.keys(person)
.some(prop => person[prop].toLowerCase().indexOf(termLowerCase) !== -1)
}
const found = people.filter(filterBy(searchString))
console.log(found)
```
Update: alternative solution with RegExp and more old-school :) but 2x faster
```
const people = [
// ...
]
const searchString = 'Bob'
const escapeRegExp = (str) => // or better use 'escape-string-regexp' package
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const filterBy = (term) => {
const re = new RegExp(escapeRegExp(term), 'i')
return person => {
for (let prop in person) {
if (!person.hasOwnProperty(prop)) {
continue;
}
if (re.test(person[prop])) {
return true;
}
}
return false;
}
}
const found = people.filter(filterBy(searchString))
``` | You should give fusejs a shot. <http://fusejs.io/>
It has some interesting settings such as threshold, which allow some typo error (0.0 = perfect, 1.0 = match anything) and `keys` to specify any keys you want to search in.
```
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship'
rogueBonusKey: 'bob likes salmon' },
]
const fuseOptions = {
caseSensitive: false,
shouldSort: true,
threshold: 0.2,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"firstName",
"lastName",
"rogueBonusKey",
]
};
const search = (txt) => {
const fuse = new Fuse(people, fuseOptions);
const result = fuse.search(txt);
return result;
}
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| You should give fusejs a shot. <http://fusejs.io/>
It has some interesting settings such as threshold, which allow some typo error (0.0 = perfect, 1.0 = match anything) and `keys` to specify any keys you want to search in.
```
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship'
rogueBonusKey: 'bob likes salmon' },
]
const fuseOptions = {
caseSensitive: false,
shouldSort: true,
threshold: 0.2,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"firstName",
"lastName",
"rogueBonusKey",
]
};
const search = (txt) => {
const fuse = new Fuse(people, fuseOptions);
const result = fuse.search(txt);
return result;
}
``` | Array.prototype.filter() also works as well:
```
const includesQuery = (value) => {
return value['SOME_KEY'].toLowerCase().includes(query.toLowerCase());
}
const filtered = this.myArray.filter(includesQuery);
console.log(filtered);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| If we assume that all properties are strings, then you might do in the following way
```
const people = [
// ...
]
const searchString = 'Bob'
const filterBy = (term) => {
const termLowerCase = term.toLowerCase()
return (person) =>
Object.keys(person)
.some(prop => person[prop].toLowerCase().indexOf(termLowerCase) !== -1)
}
const found = people.filter(filterBy(searchString))
console.log(found)
```
Update: alternative solution with RegExp and more old-school :) but 2x faster
```
const people = [
// ...
]
const searchString = 'Bob'
const escapeRegExp = (str) => // or better use 'escape-string-regexp' package
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const filterBy = (term) => {
const re = new RegExp(escapeRegExp(term), 'i')
return person => {
for (let prop in person) {
if (!person.hasOwnProperty(prop)) {
continue;
}
if (re.test(person[prop])) {
return true;
}
}
return false;
}
}
const found = people.filter(filterBy(searchString))
``` | You can use [`Array.prototype.find()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
```js
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship',
'rogueBonusKey': 'bob likes salmon' },
]
const searchString = 'Bob';
const person = people.find(({ firstName }) => firstName.toLowerCase() === searchString.toLowerCase());
console.log(person);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| you need to filter the array, then filter each key in the objects to match a regular expression. This example breaks down the problem into single responsibility funcitons and connects them with functional concepts eg.
Performance tests are included, in chrome this is consistently faster than Dmitry's example. I have not tested any other browsers. This may be because of optimisations that chrome takes to allow the jit to process the script faster when the code is expressed as small single responsibility functions that only take one type of data as an input and one type of data as an output.
Due to the tests this takes around 4 seconds to load.
```js
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship', rogueBonusKey: 'bob likes salmon' },
]
// run a predicate function over each key of an object
// const hasValue = f => o =>
// Object.keys(o).some(x => f(o[x]))
const hasValue = f => o => {
let key
for (key in o) {
if (f(o[key])) return true
}
return false
}
// convert string to regular expression
const toReg = str =>
new RegExp(str.replace(/\//g, '//'), 'gi')
// test a string with a regular expression
const match = reg => x =>
reg.test(x)
// filter an array by a predicate
// const filter = f => a => a.filter(a)
const filter = f => a => {
const ret = []
let ii = 0
let ll = a.length
for (;ii < ll; ii++) {
if (f(a[ii])) ret.push(a[ii])
}
return ret
}
// **magic**
const filterArrByValue = value => {
// create a regular expression based on your search value
// cache it for all filter iterations
const reg = toReg(value)
// filter your array of people
return filter(
// only return the results that match the regex
hasValue(match(reg))
)
}
// create a function to filter by the value 'bob'
const filterBob = filterArrByValue('Bob')
// ########################## UNIT TESTS ########################## //
console.assert('hasValue finds a matching value', !!hasValue(x => x === 'one')({ one: 'one' }))
console.assert('toReg is a regular expression', toReg('reg') instanceof RegExp)
console.assert('match finds a regular expression in a string', !!match(/test/)('this is a test'))
console.assert('filter filters an array', filter(x => x === true)([true, false]).length === 1)
// ########################## RESULTS ########################## //
console.log(
// run your function passing in your people array
'find bob',
filterBob(people)
)
console.log(
// or you could call both of them at the same time
'find salmon',
filterArrByValue('salmon')(people)
)
// ########################## BENCHMARKS ########################## //
// dmitry's first function
const filterBy = (term) => {
const termLowerCase = term.toLowerCase()
return (person) =>
Object.keys(person)
.some(prop => person[prop].toLowerCase().indexOf(termLowerCase) !== -1)
}
// dmitry's updated function
const escapeRegExp = (str) => // or better use 'escape-string-regexp' package
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const filterBy2 = (term) => {
const re = new RegExp(escapeRegExp(term), 'i')
return person => {
for (let prop in person) {
if (!person.hasOwnProperty(prop)) {
continue;
}
if (re.test(person[prop])) {
return true;
}
}
return false;
}
}
// test stringify - incredibly slow
const fuzzyMatch = (collection, searchTerm) =>
collection.filter((obj) => JSON.stringify(obj)
.toLowerCase()
.indexOf(searchTerm.toLowerCase()) !== -1
)
new Benchmark({ iterations: 1000000 })
// test my function - fastest
.add('synthet1c', function() {
filterBob(people)
})
.add('dmitry', function() {
people.filter(filterBy('Bob'))
})
.add('dmitry2', function() {
people.filter(filterBy2('Bob'))
})
.add('guest', function() {
fuzzyMatch(people, 'Bob')
})
.run()
```
```html
<link rel="stylesheet" type="text/css" href="https://codepen.io/synthet1c/pen/WrQapG.css">
<script src="https://codepen.io/synthet1c/pen/WrQapG.js"></script>
``` | If the entire matched object is expected result you can use `for..of` loop, `Object.values()`, `Array.prototype.find()`
```
consy searchString = "Bob";
const re = new RegExp(searchString, "i");
let res = [];
for (const props of Object.values(people))
Object.values(props).find(prop => re.test(prop)) && res.push(props);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| If we assume that all properties are strings, then you might do in the following way
```
const people = [
// ...
]
const searchString = 'Bob'
const filterBy = (term) => {
const termLowerCase = term.toLowerCase()
return (person) =>
Object.keys(person)
.some(prop => person[prop].toLowerCase().indexOf(termLowerCase) !== -1)
}
const found = people.filter(filterBy(searchString))
console.log(found)
```
Update: alternative solution with RegExp and more old-school :) but 2x faster
```
const people = [
// ...
]
const searchString = 'Bob'
const escapeRegExp = (str) => // or better use 'escape-string-regexp' package
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const filterBy = (term) => {
const re = new RegExp(escapeRegExp(term), 'i')
return person => {
for (let prop in person) {
if (!person.hasOwnProperty(prop)) {
continue;
}
if (re.test(person[prop])) {
return true;
}
}
return false;
}
}
const found = people.filter(filterBy(searchString))
``` | If the entire matched object is expected result you can use `for..of` loop, `Object.values()`, `Array.prototype.find()`
```
consy searchString = "Bob";
const re = new RegExp(searchString, "i");
let res = [];
for (const props of Object.values(people))
Object.values(props).find(prop => re.test(prop)) && res.push(props);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| You should give fusejs a shot. <http://fusejs.io/>
It has some interesting settings such as threshold, which allow some typo error (0.0 = perfect, 1.0 = match anything) and `keys` to specify any keys you want to search in.
```
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship'
rogueBonusKey: 'bob likes salmon' },
]
const fuseOptions = {
caseSensitive: false,
shouldSort: true,
threshold: 0.2,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"firstName",
"lastName",
"rogueBonusKey",
]
};
const search = (txt) => {
const fuse = new Fuse(people, fuseOptions);
const result = fuse.search(txt);
return result;
}
``` | You can use [`Array.prototype.find()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
```js
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship',
'rogueBonusKey': 'bob likes salmon' },
]
const searchString = 'Bob';
const person = people.find(({ firstName }) => firstName.toLowerCase() === searchString.toLowerCase());
console.log(person);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| you need to filter the array, then filter each key in the objects to match a regular expression. This example breaks down the problem into single responsibility funcitons and connects them with functional concepts eg.
Performance tests are included, in chrome this is consistently faster than Dmitry's example. I have not tested any other browsers. This may be because of optimisations that chrome takes to allow the jit to process the script faster when the code is expressed as small single responsibility functions that only take one type of data as an input and one type of data as an output.
Due to the tests this takes around 4 seconds to load.
```js
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship', rogueBonusKey: 'bob likes salmon' },
]
// run a predicate function over each key of an object
// const hasValue = f => o =>
// Object.keys(o).some(x => f(o[x]))
const hasValue = f => o => {
let key
for (key in o) {
if (f(o[key])) return true
}
return false
}
// convert string to regular expression
const toReg = str =>
new RegExp(str.replace(/\//g, '//'), 'gi')
// test a string with a regular expression
const match = reg => x =>
reg.test(x)
// filter an array by a predicate
// const filter = f => a => a.filter(a)
const filter = f => a => {
const ret = []
let ii = 0
let ll = a.length
for (;ii < ll; ii++) {
if (f(a[ii])) ret.push(a[ii])
}
return ret
}
// **magic**
const filterArrByValue = value => {
// create a regular expression based on your search value
// cache it for all filter iterations
const reg = toReg(value)
// filter your array of people
return filter(
// only return the results that match the regex
hasValue(match(reg))
)
}
// create a function to filter by the value 'bob'
const filterBob = filterArrByValue('Bob')
// ########################## UNIT TESTS ########################## //
console.assert('hasValue finds a matching value', !!hasValue(x => x === 'one')({ one: 'one' }))
console.assert('toReg is a regular expression', toReg('reg') instanceof RegExp)
console.assert('match finds a regular expression in a string', !!match(/test/)('this is a test'))
console.assert('filter filters an array', filter(x => x === true)([true, false]).length === 1)
// ########################## RESULTS ########################## //
console.log(
// run your function passing in your people array
'find bob',
filterBob(people)
)
console.log(
// or you could call both of them at the same time
'find salmon',
filterArrByValue('salmon')(people)
)
// ########################## BENCHMARKS ########################## //
// dmitry's first function
const filterBy = (term) => {
const termLowerCase = term.toLowerCase()
return (person) =>
Object.keys(person)
.some(prop => person[prop].toLowerCase().indexOf(termLowerCase) !== -1)
}
// dmitry's updated function
const escapeRegExp = (str) => // or better use 'escape-string-regexp' package
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const filterBy2 = (term) => {
const re = new RegExp(escapeRegExp(term), 'i')
return person => {
for (let prop in person) {
if (!person.hasOwnProperty(prop)) {
continue;
}
if (re.test(person[prop])) {
return true;
}
}
return false;
}
}
// test stringify - incredibly slow
const fuzzyMatch = (collection, searchTerm) =>
collection.filter((obj) => JSON.stringify(obj)
.toLowerCase()
.indexOf(searchTerm.toLowerCase()) !== -1
)
new Benchmark({ iterations: 1000000 })
// test my function - fastest
.add('synthet1c', function() {
filterBob(people)
})
.add('dmitry', function() {
people.filter(filterBy('Bob'))
})
.add('dmitry2', function() {
people.filter(filterBy2('Bob'))
})
.add('guest', function() {
fuzzyMatch(people, 'Bob')
})
.run()
```
```html
<link rel="stylesheet" type="text/css" href="https://codepen.io/synthet1c/pen/WrQapG.css">
<script src="https://codepen.io/synthet1c/pen/WrQapG.js"></script>
``` | You can use [`Array.prototype.find()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
```js
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship',
'rogueBonusKey': 'bob likes salmon' },
]
const searchString = 'Bob';
const person = people.find(({ firstName }) => firstName.toLowerCase() === searchString.toLowerCase());
console.log(person);
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| If we assume that all properties are strings, then you might do in the following way
```
const people = [
// ...
]
const searchString = 'Bob'
const filterBy = (term) => {
const termLowerCase = term.toLowerCase()
return (person) =>
Object.keys(person)
.some(prop => person[prop].toLowerCase().indexOf(termLowerCase) !== -1)
}
const found = people.filter(filterBy(searchString))
console.log(found)
```
Update: alternative solution with RegExp and more old-school :) but 2x faster
```
const people = [
// ...
]
const searchString = 'Bob'
const escapeRegExp = (str) => // or better use 'escape-string-regexp' package
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const filterBy = (term) => {
const re = new RegExp(escapeRegExp(term), 'i')
return person => {
for (let prop in person) {
if (!person.hasOwnProperty(prop)) {
continue;
}
if (re.test(person[prop])) {
return true;
}
}
return false;
}
}
const found = people.filter(filterBy(searchString))
``` | You can also use [Regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) with `i` modifier to perform case-insensitive matching and the method [RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
* It is very convenient when you want to evaluate multiple object properties like:
```js
new RegExp(searchString, 'i').test(
person.email || person.firstName || person.lastName
)
```
Code:
```js
const people = [{ firstName: 'Bob', lastName: 'Smith', status: 'single' }, { firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' }, { firstName: 'Jim', lastName: 'Johnson', status: 'complicated' }, { firstName: 'Sally', lastName: 'Fields', status: 'relationship' }, { firstName: 'Robert', lastName: 'Bobler', status: 'single' }, { firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' }, { firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship', rogueBonusKey: 'bob likes salmon' }]
const searchString = 'Bob'
const found = people.filter(({ firstName }) =>
new RegExp(searchString, 'i').test(firstName))
console.log(found)
``` |
47,117,924 | So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
```
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
```
thr problem im having is with the
```
x=y; y=z; z=x+y;
```
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up. | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8887805/"
]
| You can use [`Array.prototype.find()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
```js
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'Johnson', status: 'complicated' },
{ firstName: 'Sally', lastName: 'Fields', status: 'relationship' },
{ firstName: 'Robert', lastName: 'Bobler', status: 'single' },
{ firstName: 'Johnny', lastName: 'Johannson', status: 'complicated' },
{ firstName: 'Whaley', lastName: 'McWhalerson', status: 'relationship',
'rogueBonusKey': 'bob likes salmon' },
]
const searchString = 'Bob';
const person = people.find(({ firstName }) => firstName.toLowerCase() === searchString.toLowerCase());
console.log(person);
``` | Array.prototype.filter() also works as well:
```
const includesQuery = (value) => {
return value['SOME_KEY'].toLowerCase().includes(query.toLowerCase());
}
const filtered = this.myArray.filter(includesQuery);
console.log(filtered);
``` |
173,176 | What is a Journaling file system?
Even wikipedia doesn't give much information. Apart from NTFS which other file systems(on Windows / Linux) support journaling and how does it give a performance boost? | 2010/08/22 | [
"https://serverfault.com/questions/173176",
"https://serverfault.com",
"https://serverfault.com/users/23923/"
]
| A journaling filesystem records changes to the filesystem before it actually performs them. In this way it is able to recover after a failure (e.g. power fail) with minimal loss of data.
The [Features](http://en.wikipedia.org/wiki/Comparison_of_file_systems#Features) section of Wikipedia's comparison of filesystems gives which are journaled.
Journaling does not give a performance boost. In fact, the journaling operationn reduces the speed slightly, in exchange for the above reliability. | The wikipedia article on [Journaling file system](http://en.wikipedia.org/wiki/Journaling_file_system) contains a lot more details on what it is, how it works, and why. |
173,176 | What is a Journaling file system?
Even wikipedia doesn't give much information. Apart from NTFS which other file systems(on Windows / Linux) support journaling and how does it give a performance boost? | 2010/08/22 | [
"https://serverfault.com/questions/173176",
"https://serverfault.com",
"https://serverfault.com/users/23923/"
]
| A journaling filesystem records changes to the filesystem before it actually performs them. In this way it is able to recover after a failure (e.g. power fail) with minimal loss of data.
The [Features](http://en.wikipedia.org/wiki/Comparison_of_file_systems#Features) section of Wikipedia's comparison of filesystems gives which are journaled.
Journaling does not give a performance boost. In fact, the journaling operationn reduces the speed slightly, in exchange for the above reliability. | In essence, what a journaling file system does is add an extra level of abstraction between the hard drive and the operating system. Rather than perform operations directly on the disk, it keeps track of what it's trying to do first, then whether or not it succeeds.
For example, if you wanted to move a file from one drive to another, the procedure would look something like the following:
* Physically copy old file to new location
* Update directory entry on new drive
* Remove directory entry from old drive
* Free space on old drive
Exact process is filesystem dependent, but you get the idea. This would normally work fine, but in the off chance of a system crash, things could be interrupted halfway through. You may end up with the file physically copied, but no directory entry pointing to it. You may end up with the directory reference removed on the old drive, but the space not freed. In some cases, you may end up with a corrupted filesystem which won't even work anymore because a directory entry is only partially written.
In other words, a lot can go wrong.
A journalled file system would use the same basic procedure, with a few additional steps. Something like:
* Journal entry: Moving file from A to B
+ Physically copy old file to new location
+ Update directory entry on new drive
+ Remove directory entry from old drive
+ Free space on old drive
* Journal entry: Done moving file from A to B
If this process gets interrupted for any reason, such as a system crash, the filesystem now knows what was in progress, and whether it completed or not. It can then recover quickly and gracefully, either by trying to complete the transaction from the beginning, or by putting the filesystem back to the state it was in before. All this without needing to resort to a block-by-block check of the filesystem to find errors, which can be painfully time-consuming given the size of modern hard drives.
This can significantly improve the robustness of the filesystem, and speed up recovery time in the case of failure. Different levels of reliability can be gained by changing the granularity of the journal entries -- this again is filesystem dependent.
Since journalling inevitably involves more steps than the alternative, there would not be any performance boost unless you feel like crashing a lot. However, the difference in performance is often negligible compared to the advantages. |
173,176 | What is a Journaling file system?
Even wikipedia doesn't give much information. Apart from NTFS which other file systems(on Windows / Linux) support journaling and how does it give a performance boost? | 2010/08/22 | [
"https://serverfault.com/questions/173176",
"https://serverfault.com",
"https://serverfault.com/users/23923/"
]
| A journaling filesystem records changes to the filesystem before it actually performs them. In this way it is able to recover after a failure (e.g. power fail) with minimal loss of data.
The [Features](http://en.wikipedia.org/wiki/Comparison_of_file_systems#Features) section of Wikipedia's comparison of filesystems gives which are journaled.
Journaling does not give a performance boost. In fact, the journaling operationn reduces the speed slightly, in exchange for the above reliability. | A journaling filesystem is a term being misused widely for filesystems that are not, after all, journaling.
What "journaling" means in the context of filesystems is that the filesystem is capable of recovering from crashes and power losses to a consistent state. It does not mean a performance boost, it doesn't mean that the filesystem recovers to a complete snapshot some time before the crash, it doesn't even mean that there wouldn't be a "filesystem check" style operation to recover after a crash. |
173,176 | What is a Journaling file system?
Even wikipedia doesn't give much information. Apart from NTFS which other file systems(on Windows / Linux) support journaling and how does it give a performance boost? | 2010/08/22 | [
"https://serverfault.com/questions/173176",
"https://serverfault.com",
"https://serverfault.com/users/23923/"
]
| In essence, what a journaling file system does is add an extra level of abstraction between the hard drive and the operating system. Rather than perform operations directly on the disk, it keeps track of what it's trying to do first, then whether or not it succeeds.
For example, if you wanted to move a file from one drive to another, the procedure would look something like the following:
* Physically copy old file to new location
* Update directory entry on new drive
* Remove directory entry from old drive
* Free space on old drive
Exact process is filesystem dependent, but you get the idea. This would normally work fine, but in the off chance of a system crash, things could be interrupted halfway through. You may end up with the file physically copied, but no directory entry pointing to it. You may end up with the directory reference removed on the old drive, but the space not freed. In some cases, you may end up with a corrupted filesystem which won't even work anymore because a directory entry is only partially written.
In other words, a lot can go wrong.
A journalled file system would use the same basic procedure, with a few additional steps. Something like:
* Journal entry: Moving file from A to B
+ Physically copy old file to new location
+ Update directory entry on new drive
+ Remove directory entry from old drive
+ Free space on old drive
* Journal entry: Done moving file from A to B
If this process gets interrupted for any reason, such as a system crash, the filesystem now knows what was in progress, and whether it completed or not. It can then recover quickly and gracefully, either by trying to complete the transaction from the beginning, or by putting the filesystem back to the state it was in before. All this without needing to resort to a block-by-block check of the filesystem to find errors, which can be painfully time-consuming given the size of modern hard drives.
This can significantly improve the robustness of the filesystem, and speed up recovery time in the case of failure. Different levels of reliability can be gained by changing the granularity of the journal entries -- this again is filesystem dependent.
Since journalling inevitably involves more steps than the alternative, there would not be any performance boost unless you feel like crashing a lot. However, the difference in performance is often negligible compared to the advantages. | The wikipedia article on [Journaling file system](http://en.wikipedia.org/wiki/Journaling_file_system) contains a lot more details on what it is, how it works, and why. |
173,176 | What is a Journaling file system?
Even wikipedia doesn't give much information. Apart from NTFS which other file systems(on Windows / Linux) support journaling and how does it give a performance boost? | 2010/08/22 | [
"https://serverfault.com/questions/173176",
"https://serverfault.com",
"https://serverfault.com/users/23923/"
]
| In essence, what a journaling file system does is add an extra level of abstraction between the hard drive and the operating system. Rather than perform operations directly on the disk, it keeps track of what it's trying to do first, then whether or not it succeeds.
For example, if you wanted to move a file from one drive to another, the procedure would look something like the following:
* Physically copy old file to new location
* Update directory entry on new drive
* Remove directory entry from old drive
* Free space on old drive
Exact process is filesystem dependent, but you get the idea. This would normally work fine, but in the off chance of a system crash, things could be interrupted halfway through. You may end up with the file physically copied, but no directory entry pointing to it. You may end up with the directory reference removed on the old drive, but the space not freed. In some cases, you may end up with a corrupted filesystem which won't even work anymore because a directory entry is only partially written.
In other words, a lot can go wrong.
A journalled file system would use the same basic procedure, with a few additional steps. Something like:
* Journal entry: Moving file from A to B
+ Physically copy old file to new location
+ Update directory entry on new drive
+ Remove directory entry from old drive
+ Free space on old drive
* Journal entry: Done moving file from A to B
If this process gets interrupted for any reason, such as a system crash, the filesystem now knows what was in progress, and whether it completed or not. It can then recover quickly and gracefully, either by trying to complete the transaction from the beginning, or by putting the filesystem back to the state it was in before. All this without needing to resort to a block-by-block check of the filesystem to find errors, which can be painfully time-consuming given the size of modern hard drives.
This can significantly improve the robustness of the filesystem, and speed up recovery time in the case of failure. Different levels of reliability can be gained by changing the granularity of the journal entries -- this again is filesystem dependent.
Since journalling inevitably involves more steps than the alternative, there would not be any performance boost unless you feel like crashing a lot. However, the difference in performance is often negligible compared to the advantages. | A journaling filesystem is a term being misused widely for filesystems that are not, after all, journaling.
What "journaling" means in the context of filesystems is that the filesystem is capable of recovering from crashes and power losses to a consistent state. It does not mean a performance boost, it doesn't mean that the filesystem recovers to a complete snapshot some time before the crash, it doesn't even mean that there wouldn't be a "filesystem check" style operation to recover after a crash. |
12,020,855 | Is it dangerous to cast "(NSInteger)self"?
I need to distinguish two views, not using tag value.
If It is dangerous, any ideas? | 2012/08/18 | [
"https://Stackoverflow.com/questions/12020855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1410800/"
]
| You mean you have two `UIView` pointers and you want to know if they are pointing to the same object? Just use `==`. No need to cast them. If you mean something else, you'll need to provide more details on what you mean by "distinguishing two views". | Ignoring what convulsions ARC may go through, it's not dangerous to cast `self` (or any other pointer) to `integer`. It is exceedingly dangerous, however, to cast the other direction.
And Objective-C has enough odd corners and dark hallways that it's difficult to say with great confidence that `self` cast to an integer will be reproducible in a useful way. |
12,020,855 | Is it dangerous to cast "(NSInteger)self"?
I need to distinguish two views, not using tag value.
If It is dangerous, any ideas? | 2012/08/18 | [
"https://Stackoverflow.com/questions/12020855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1410800/"
]
| Ignoring what convulsions ARC may go through, it's not dangerous to cast `self` (or any other pointer) to `integer`. It is exceedingly dangerous, however, to cast the other direction.
And Objective-C has enough odd corners and dark hallways that it's difficult to say with great confidence that `self` cast to an integer will be reproducible in a useful way. | The `NSObject` protocol declares an [`isEqual:`](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/doc/uid/20000052-BBCCECDG) method for comparing objects. A class can override this to define its instances as equal if their contents are equal; otherwise two instances will compare as unequal.
This is what you should really use to distinguish objects from each other, rather than comparing their pointer values directly. That is, however, safe to do. |
12,020,855 | Is it dangerous to cast "(NSInteger)self"?
I need to distinguish two views, not using tag value.
If It is dangerous, any ideas? | 2012/08/18 | [
"https://Stackoverflow.com/questions/12020855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1410800/"
]
| You mean you have two `UIView` pointers and you want to know if they are pointing to the same object? Just use `==`. No need to cast them. If you mean something else, you'll need to provide more details on what you mean by "distinguishing two views". | The `NSObject` protocol declares an [`isEqual:`](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/doc/uid/20000052-BBCCECDG) method for comparing objects. A class can override this to define its instances as equal if their contents are equal; otherwise two instances will compare as unequal.
This is what you should really use to distinguish objects from each other, rather than comparing their pointer values directly. That is, however, safe to do. |
38,830,828 | I have pushed to heroku but the application will not run. I see that it is due to the dotenv gem. Is there a way around this? I need the dot-env gem in order to encrypt the basic auth user name and password. I'd prefer not to use devise or anything of that complexity as this is a simple application.
Below is my heroku terminal output, only issue is I dont really know how to spot errors/read the output.
```
/app/config/application.rb:4:in `require': cannot load such file -- dotenv (LoadError)
from /app/config/application.rb:4:in `<top (required)>'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:141:in `require'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:141:in `require_application_and_environment!'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:67:in `console'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `<top (required)>'
from /app/bin/rails:9:in `require'
from /app/bin/rails:9:in `<main>'
gem 'rails', '4.2.5'
gem 'pg'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'will_paginate', '~> 3.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem "font-awesome-rails"
gem 'dotenv-rails', :groups => [:development, :test]
gem 'will_paginate-bootstrap'
gem "paperclip", "~> 5.0.0"
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# gem 'dotenv-heroku'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
``` | 2016/08/08 | [
"https://Stackoverflow.com/questions/38830828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2026178/"
]
| You configured the `dotenv` gem to be enabled only for the `development` and `test` environments:
```
gem 'dotenv-rails', :groups => [:development, :test]
```
However, the application is started in `production` environment in Heroku. Therefore, the Rails application will crash because it tries to load the gem but it's not available.
You likely manually included the `dotenv` loading code somewhere in your application:
```
Dotenv::Railtie.load
```
You need to remove it (as dotenv will inject itself in the load process, when the gem is loaded), or wrap the code within a conditional block that executes it only if `Dotenv` is defined
```
if defined? Dotenv
# ..
end
```
Unless you really need to manually load the library (and generally you don't), then simply remove the explicit statement, [explained in the documentation](http://www.rubydoc.info/gems/dotenv-rails/2.1.1).
>
> dotenv is initialized in your Rails app during the before\_configuration callback, which is fired when the Application constant is defined in config/application.rb with class Application < Rails::Application. **If you need** it to be initialized sooner, you can manually call Dotenv::Railtie.load.
>
>
> | `dotenv` gem is used for load environment variables from .env into ENV in `development`.
and heroku used `production` environment. So, you need to just put this on `Gemfile`
```
gem 'dotenv-rails', :groups => [:development, :test]
```
Hope, this will helps you. |
38,830,828 | I have pushed to heroku but the application will not run. I see that it is due to the dotenv gem. Is there a way around this? I need the dot-env gem in order to encrypt the basic auth user name and password. I'd prefer not to use devise or anything of that complexity as this is a simple application.
Below is my heroku terminal output, only issue is I dont really know how to spot errors/read the output.
```
/app/config/application.rb:4:in `require': cannot load such file -- dotenv (LoadError)
from /app/config/application.rb:4:in `<top (required)>'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:141:in `require'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:141:in `require_application_and_environment!'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:67:in `console'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `<top (required)>'
from /app/bin/rails:9:in `require'
from /app/bin/rails:9:in `<main>'
gem 'rails', '4.2.5'
gem 'pg'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'will_paginate', '~> 3.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem "font-awesome-rails"
gem 'dotenv-rails', :groups => [:development, :test]
gem 'will_paginate-bootstrap'
gem "paperclip", "~> 5.0.0"
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# gem 'dotenv-heroku'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
``` | 2016/08/08 | [
"https://Stackoverflow.com/questions/38830828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2026178/"
]
| You configured the `dotenv` gem to be enabled only for the `development` and `test` environments:
```
gem 'dotenv-rails', :groups => [:development, :test]
```
However, the application is started in `production` environment in Heroku. Therefore, the Rails application will crash because it tries to load the gem but it's not available.
You likely manually included the `dotenv` loading code somewhere in your application:
```
Dotenv::Railtie.load
```
You need to remove it (as dotenv will inject itself in the load process, when the gem is loaded), or wrap the code within a conditional block that executes it only if `Dotenv` is defined
```
if defined? Dotenv
# ..
end
```
Unless you really need to manually load the library (and generally you don't), then simply remove the explicit statement, [explained in the documentation](http://www.rubydoc.info/gems/dotenv-rails/2.1.1).
>
> dotenv is initialized in your Rails app during the before\_configuration callback, which is fired when the Application constant is defined in config/application.rb with class Application < Rails::Application. **If you need** it to be initialized sooner, you can manually call Dotenv::Railtie.load.
>
>
> | dotenv is for managing your environment variables in your development environment. YOu need to manually create these variables on heroku. |
3,683,445 | My statement:
```
string sqlCommandText = "SELECT * FROM ForumThread WHERE";
```
How can I read `*` from it?
I'm trying like this but its doesnt work:
```
if (reader["*"] != DBNull.Value)
{
result.TextContent = Convert.ToString(reader["*"]);
}
``` | 2010/09/10 | [
"https://Stackoverflow.com/questions/3683445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291120/"
]
| `*` is not a column, it's a instruction to `SELECT` to just grab every column it can find.
The columns will appear individually though, so you need to iterate through the columns one by one and grab their contents.
To get the column contents, you can do this:
```
StringBuilder sb = new StringBuilder();
for (int index = 0; index < reader.FieldCount; index++)
{
object value = reader[index];
if (value != DBNull.Value)
sb.Append(value.ToString());
}
result.TextContent = sb.ToString();
```
However, this will result in everything being mashed together.
For instance, if your result set look like this:
```
A B C D
10 20 30 Some name here
```
Then your resulting string will look like this:
102030Some name here
Is this what you want?
Perhaps you told us what you want to accomplish, we can think of a better answer? | Additionally, you can use this method to retrieve the associated field name:
```
reader.GetName( /* index of the column */);
``` |
3,683,445 | My statement:
```
string sqlCommandText = "SELECT * FROM ForumThread WHERE";
```
How can I read `*` from it?
I'm trying like this but its doesnt work:
```
if (reader["*"] != DBNull.Value)
{
result.TextContent = Convert.ToString(reader["*"]);
}
``` | 2010/09/10 | [
"https://Stackoverflow.com/questions/3683445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291120/"
]
| `*` is not a column, it's a instruction to `SELECT` to just grab every column it can find.
The columns will appear individually though, so you need to iterate through the columns one by one and grab their contents.
To get the column contents, you can do this:
```
StringBuilder sb = new StringBuilder();
for (int index = 0; index < reader.FieldCount; index++)
{
object value = reader[index];
if (value != DBNull.Value)
sb.Append(value.ToString());
}
result.TextContent = sb.ToString();
```
However, this will result in everything being mashed together.
For instance, if your result set look like this:
```
A B C D
10 20 30 Some name here
```
Then your resulting string will look like this:
102030Some name here
Is this what you want?
Perhaps you told us what you want to accomplish, we can think of a better answer? | Suppose your **ForumThread** table contains the **ThreadResponse** column, and you actually want to read the **ThreadResponse** column, you can use the next code:
```
//calculates the column ordinal based on column name
int ThreadResponseColumnIdx = reader.GetOrdinal("ThreadResponse");
//If there is a line in the result
if (reader.Read())
{
//read from the current line the ThreadResponse column
result.TextContent = reader.GetString(ThreadResponseColumnIdx);
}
``` |
3,683,445 | My statement:
```
string sqlCommandText = "SELECT * FROM ForumThread WHERE";
```
How can I read `*` from it?
I'm trying like this but its doesnt work:
```
if (reader["*"] != DBNull.Value)
{
result.TextContent = Convert.ToString(reader["*"]);
}
``` | 2010/09/10 | [
"https://Stackoverflow.com/questions/3683445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291120/"
]
| Additionally, you can use this method to retrieve the associated field name:
```
reader.GetName( /* index of the column */);
``` | Suppose your **ForumThread** table contains the **ThreadResponse** column, and you actually want to read the **ThreadResponse** column, you can use the next code:
```
//calculates the column ordinal based on column name
int ThreadResponseColumnIdx = reader.GetOrdinal("ThreadResponse");
//If there is a line in the result
if (reader.Read())
{
//read from the current line the ThreadResponse column
result.TextContent = reader.GetString(ThreadResponseColumnIdx);
}
``` |
65,255,620 | So i prepared a keras model including USE4 using the below link :
<https://tfhub.dev/google/universal-sentence-encoder-large/4>
Using tensorflow 2.3, i added it to my model and saved the model
```
tf.saved_model.save(
model,
export_dir= '/directory/model/1',
)
```
Once served in docker, I'm able to get the metadata but predict request is not working. Here is the request :
```
{"inputs":{"text":["Hello"]}}
```
Response :
```
{ "error": "[_Derived_]{{function_node __inference_pruned_16231}} {{function_node __inference_pruned_16231}} Table not initialized.\n\t [[{{node text_preprocessor_1/hash_table_Lookup/hash_table_Lookup/LookupTableFindV2}}]]\n\t [[StatefulPartitionedCall/StatefulPartitionedCall/sequential/keras_layer/StatefulPartitionedCall/StatefulPartitionedCall/StatefulPartitionedCall]]" }
```
I read here <https://github.com/awslabs/amazon-sagemaker-examples/issues/773#issuecomment-509433290> that this issue can be resolved in older tf versions by using the command tf.tables\_initializer() in the old tf.saved\_model.simple\_save() function. But in 2.3.0 what's the alternative? | 2020/12/11 | [
"https://Stackoverflow.com/questions/65255620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11278414/"
]
| I'd change the functions to accept a single argument as an object, which gets destructured, so that all functions can be called with the same argument:
```
mainFunction() {
let name = something;
let address = something;
let date = something;
....
let height = something;
const paramsObj = { name, address, date, height };
for (const fn of Functs) {
fn(paramsObj);
// do whatever you need to do with the return value or loop logic
}
```
and
```
f1 = function({ name, address, date }) {};
f2 = function({ name, age }) {};
f3 = function({ height });
```
If you need these parameters be modified while being passed along as well, you can destructure on the first line instead, allowing you to mutate the params object, eg:
```
f1 = function(params) {
const { name, address, date } = params;
if (someCondition) {
params.height += 2;
}
};
```
and then subsequent calls will see the changed parameter. | After a lot of testing and benchmarking, the fastest method we've come up with is this (using @certainPerformance 's solution as a starting point):
1. Store functions in an array of objects. This allows a user to insert new custom functions anywhere in the list (insert before 'taskA', etc.) and is *much* faster than an object of objects or Map.
2. Call the tasks using `array.some()`. Somewhat faster than `for of` or `for in`, and even seemed slightly faster than `array.map`.
3. Use `function.call()` to call the functions. This allows use of the `this` variable if you need to access other class features, for example. If you do this, you should also pass in `this` to `array.some()`, which preserves the `this` context without needing `bind(this)` which seemed quite slow.
4. For parameters used by only a few functions, use an object `params` which gives a common function signature while allowing custom functions access to any relevant variables. For parameters common to all functions, pass in directly (for speed, especially if modifying that value).
```
//=== List of Pipeline Steps ===//
this.pipelineTasks = [
{ name: 'taskA', func: this.taskA },
{ name: 'taskB', func: this.taskB },
{ name: 'taskC', func: this.taskC }
];
// TaskA
TaskA(src, params) {
return src + params.title;
}
// TaskB
TaskB(src, params) {
return params.name ? params.name : params.name + "chicken";
}
// TaskC
TaskC(src, params) {
params.age = params.age + params.shoeSize;
return params.age > params.shoeSize ? params.age : params.shoeSize;
}
//=== Execute the processing pipeline ===//
processPipeline(src, name, age, shoeSize, title) {
const myParams = {
name : name,
age : 10,
shoeSize : 20,
title : title
};
while (myParams.age < 100) {
this.pipelineTasks.some(function(fn) {
return result = fn.func.call(this, src, myParams);
}, this));
//Alternatively, with arrow functions
// (slightly slower in Chrome, significantly slower in Node with hundreds
// of function calls, but doesn't require 'this' in array.some )
// this.pipelineTasks.some((fn) => result = fn.func.call(this, src, myParams));
}
}
``` |
65,255,620 | So i prepared a keras model including USE4 using the below link :
<https://tfhub.dev/google/universal-sentence-encoder-large/4>
Using tensorflow 2.3, i added it to my model and saved the model
```
tf.saved_model.save(
model,
export_dir= '/directory/model/1',
)
```
Once served in docker, I'm able to get the metadata but predict request is not working. Here is the request :
```
{"inputs":{"text":["Hello"]}}
```
Response :
```
{ "error": "[_Derived_]{{function_node __inference_pruned_16231}} {{function_node __inference_pruned_16231}} Table not initialized.\n\t [[{{node text_preprocessor_1/hash_table_Lookup/hash_table_Lookup/LookupTableFindV2}}]]\n\t [[StatefulPartitionedCall/StatefulPartitionedCall/sequential/keras_layer/StatefulPartitionedCall/StatefulPartitionedCall/StatefulPartitionedCall]]" }
```
I read here <https://github.com/awslabs/amazon-sagemaker-examples/issues/773#issuecomment-509433290> that this issue can be resolved in older tf versions by using the command tf.tables\_initializer() in the old tf.saved\_model.simple\_save() function. But in 2.3.0 what's the alternative? | 2020/12/11 | [
"https://Stackoverflow.com/questions/65255620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11278414/"
]
| ```js
const if_then = (if_fn, then_fn) => (params_object) =>
if_fn(params_object) ? then_fn(params_object) : null;
const apply_params = (fn, arg_keys, write_to_key = false) => (params_object) => {
const result = fn(...arg_keys.map((v) => params_object[v]));
if(write_to_key)
params_object[write_to_key] = result;
return result;
};
const name_and_age = (name, age) => name + ' is ' + age + ' and a half years old';
const volume = (height, width, depth) => height * width * depth;
const double_height = (height) => height * 2;
const double_width = (width) => width * 2;
const count_loop = (params_object) => Object.assign(params_object, { loop_count: (params_object.loop_count ?? 0) + 1 })
let functs = [
count_loop,
apply_params(double_height, ['height'], 'height'),
if_then(
(p) => !p.name_and_age,
apply_params(name_and_age, ['name', 'age'], 'name_and_age'),
),
];
const bob = true;
if(bob)
functs.push(
if_then(
(p) => p.loop_count > 2,
apply_params(double_width, ['width'], 'width'),
)
);
functs = functs.concat([
apply_params(volume, ['height', 'width', 'depth'], 'volume'),
console.log
]);
let params = {
name : 'Orbold the Grim',
age : 145,
height: 2,
width: 0.3,
depth: 0.2,
};
const should_exit_loop = (params_object) =>
(params_object.loop_count || 0) > 10 || params_object.height > 8;
while(!should_exit_loop(params)) {
functs.forEach(
(f) => f(params)
);
};
``` | After a lot of testing and benchmarking, the fastest method we've come up with is this (using @certainPerformance 's solution as a starting point):
1. Store functions in an array of objects. This allows a user to insert new custom functions anywhere in the list (insert before 'taskA', etc.) and is *much* faster than an object of objects or Map.
2. Call the tasks using `array.some()`. Somewhat faster than `for of` or `for in`, and even seemed slightly faster than `array.map`.
3. Use `function.call()` to call the functions. This allows use of the `this` variable if you need to access other class features, for example. If you do this, you should also pass in `this` to `array.some()`, which preserves the `this` context without needing `bind(this)` which seemed quite slow.
4. For parameters used by only a few functions, use an object `params` which gives a common function signature while allowing custom functions access to any relevant variables. For parameters common to all functions, pass in directly (for speed, especially if modifying that value).
```
//=== List of Pipeline Steps ===//
this.pipelineTasks = [
{ name: 'taskA', func: this.taskA },
{ name: 'taskB', func: this.taskB },
{ name: 'taskC', func: this.taskC }
];
// TaskA
TaskA(src, params) {
return src + params.title;
}
// TaskB
TaskB(src, params) {
return params.name ? params.name : params.name + "chicken";
}
// TaskC
TaskC(src, params) {
params.age = params.age + params.shoeSize;
return params.age > params.shoeSize ? params.age : params.shoeSize;
}
//=== Execute the processing pipeline ===//
processPipeline(src, name, age, shoeSize, title) {
const myParams = {
name : name,
age : 10,
shoeSize : 20,
title : title
};
while (myParams.age < 100) {
this.pipelineTasks.some(function(fn) {
return result = fn.func.call(this, src, myParams);
}, this));
//Alternatively, with arrow functions
// (slightly slower in Chrome, significantly slower in Node with hundreds
// of function calls, but doesn't require 'this' in array.some )
// this.pipelineTasks.some((fn) => result = fn.func.call(this, src, myParams));
}
}
``` |
15,861,808 | Hi im developping an ssis package that imports excel files (.xlsx) from an ftp server to a local folder then they are imported to a sql server table . I'm using a `foreach` mapping to the name of files. The import from the ftp server to local work fine, but the import from the local folder to the sql table failed.
It seems that I have a problem in excel source. These are the errors:
```
Start SSIS package "Package.dtsx."
Information: 0x1 at Script Task, C # My Message: System.Collections.ArrayList
Information: 0x4004300A at Data Flow Task, SSIS.Pipeline: Validation phase begins.
Error: 0xC0202009 at Data Flow Task, Excel Source [1]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E37.
Error: 0xC02020E8 to Flow Task data, Excel Source [1]: Failed to open a rowset for "Sheet1 $". Verify that the object exists in the database.
Error: 0xC004706B to Flow Task data SSIS.Pipeline: validation failed "component" Excel Source "(1)". Returned validation status "VS_ISBROKEN."
Error: 0xC004700C to Flow Task data SSIS.Pipeline: Failed to validate one or more components.
Error: 0xC0024107 at Data Flow Task: There were errors during task validation.
Warning: 0x80019002 at Foreach Loop Container: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors (6) reached the maximum allowed (1); leading to a failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the value of MaximumErrorCount or fix the errors.
SSIS package "Package.dtsx" finished: Success.
The program '[5504] Package.dtsx: DTS' has exited with code 0 (0x0).
```
As configuration I have:
For the excel manager connexion, I made an expression for connectionString = `@[User::variable1] + @[User::DOWNLOAD_DIRECTORY_LOCAL] + @[User::FTP_FILE_URL] + @[User::variable2]`
`variable 1 =Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`
`variable 2 = ;Extended Properties="EXCEL 12.0;HDR=YES";`
I made also the delay validation property to true for data flow task, ftp task, foreach task and excel connection. | 2013/04/07 | [
"https://Stackoverflow.com/questions/15861808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2254347/"
]
| I don't have any experience with **vmware**, but assuming you can use any VM, here's a solution for [VirtualBox](https://www.virtualbox.org/):
* Setup a network interface on your VM, that's visible to the host
system only ([reference](http://www.virtualbox.org/manual/ch06.html#network_hostonly)):
>
> Host-only networking is another networking mode that was added with
> version 2.2 of VirtualBox. It can be thought of as a hybrid between
> the bridged and internal networking modes: as with bridged networking,
> the virtual machines can talk to each other and the host as if they
> were connected through a physical ethernet switch. Similarly, as with
> internal networking however, a physical networking interface need not
> be present, and the virtual machines cannot talk to the world outside
> the host since they are not connected to a physical networking
> interface.
>
>
>
* Configure **port forwarding** on system B ([external\_port] -> [host\_over\_vpn]:[service\_port])
Connect to [system\_B\_ip\_over\_provided\_interface]:[external\_port] as if you were connecting to the database directly. | yes it is possible. Just give correct IPs. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| Try something like this:
```
<html class="nojs">
<head>
<script type="text/javascript">
document.getElementByTagName("html")[0].className="";
</script>
<style>
html#nojs {
/* do something */
}
</style>
```
This removes a class while loading the page. If javascript is not activated the class won't be removed. | You can get around this by having those classes in your default stylesheet and have JavaScript get rid of them when the page loads. This will only work if JavaScript is enabled otherwise it would load the desired styles. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| `<noscript>` tags are "body" tags and `<style>` tags are "head" tags. Therefor you get an error.
You should make non-javascript style default and then use js to change your style. See here for more details:
<https://stackoverflow.com/a/218917/1068167> | Try something like this:
```
<html class="nojs">
<head>
<script type="text/javascript">
document.getElementByTagName("html")[0].className="";
</script>
<style>
html#nojs {
/* do something */
}
</style>
```
This removes a class while loading the page. If javascript is not activated the class won't be removed. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| Try something like this:
```
<html class="nojs">
<head>
<script type="text/javascript">
document.getElementByTagName("html")[0].className="";
</script>
<style>
html#nojs {
/* do something */
}
</style>
```
This removes a class while loading the page. If javascript is not activated the class won't be removed. | You could for example do it the other way around and disable some css file via javascript which doesn' t happen if it's not activated. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| `<noscript>` tags are "body" tags and `<style>` tags are "head" tags. Therefor you get an error.
You should make non-javascript style default and then use js to change your style. See here for more details:
<https://stackoverflow.com/a/218917/1068167> | You can get around this by having those classes in your default stylesheet and have JavaScript get rid of them when the page loads. This will only work if JavaScript is enabled otherwise it would load the desired styles. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| Seems very similar to this [question](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> "To clear up the validation issue: noscript is only allowed in the
> body element, style only allowed in the head. Therefore, the latter is
> not allowed within the former."
>
>
>
It might matter where your `<noscript>` tag is located. | You can get around this by having those classes in your default stylesheet and have JavaScript get rid of them when the page loads. This will only work if JavaScript is enabled otherwise it would load the desired styles. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| `<noscript>` tags are "body" tags and `<style>` tags are "head" tags. Therefor you get an error.
You should make non-javascript style default and then use js to change your style. See here for more details:
<https://stackoverflow.com/a/218917/1068167> | Seems very similar to this [question](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> "To clear up the validation issue: noscript is only allowed in the
> body element, style only allowed in the head. Therefore, the latter is
> not allowed within the former."
>
>
>
It might matter where your `<noscript>` tag is located. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| `<noscript>` tags are "body" tags and `<style>` tags are "head" tags. Therefor you get an error.
You should make non-javascript style default and then use js to change your style. See here for more details:
<https://stackoverflow.com/a/218917/1068167> | You could for example do it the other way around and disable some css file via javascript which doesn' t happen if it's not activated. |
13,961,840 | >
> **Possible Duplicate:**
>
> [Embedding extra styles with noscript](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> [Define css if javascript is not enabled](https://stackoverflow.com/questions/4665748/define-css-if-javascript-is-not-enabled)
>
>
>
I am trying to define specific CSS styles only if Javascript is turned off. I am using:
```
<noscript>
<style type="text/css">
.needjs {display:none !important;}
.mwnojs { margin-top: 40px !important; }
</style>
</noscript>
```
When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".
So, how would I go about doing this while keeping my markup valid? | 2012/12/19 | [
"https://Stackoverflow.com/questions/13961840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279133/"
]
| Seems very similar to this [question](https://stackoverflow.com/questions/218162/embedding-extra-styles-with-noscript)
>
> "To clear up the validation issue: noscript is only allowed in the
> body element, style only allowed in the head. Therefore, the latter is
> not allowed within the former."
>
>
>
It might matter where your `<noscript>` tag is located. | You could for example do it the other way around and disable some css file via javascript which doesn' t happen if it's not activated. |
869,154 | I really wonder if an IP Address with all its bits off can be used or not. Please do answer if you know where its used or it can not be used. | 2015/01/25 | [
"https://superuser.com/questions/869154",
"https://superuser.com",
"https://superuser.com/users/411506/"
]
| **Reference** [IP Addresses With Special Meanings](http://www.tcpipguide.com/free/t_IPAddressesWithSpecialMeanings-2.htm) :
>
> **0.0.0.0**
>
>
> โMeโ: (Alternately, โthis hostโ, or โthe current/default hostโ). Used by a device to refer to itself when it doesn't know its
> own IP address. **The most common use is when a device attempts to
> determine its address using a host-configuration protocol like DHCP**.
> May also be used to indicate that any address of a multihomed host may
> be used.
>
>
>
**Reference** [What is the meaning of the IP address 0.0.0.0](http://www.linuxquestions.org/questions/linux-networking-3/what-is-the-meaning-of-the-ip-address-0-0-0-0-a-716643/):
>
> "0.0.0.0" is a valid address syntax. So it should parse as valid
> wherever an IP address in traditional dotted-decimal notation is
> expected. Once parsed, and converted to workable numeric form, then
> its value determines what happens next.
>
>
> **The all-zero value does have a special meaning.** So it is "valid", but
> has a meaning that may not be appropriate (and thus treated as not
> valid) for particular circumstances. **It is basically the "no
> particular address" placeholder.** For things like address binding of
> network connections, the result can be to assign an appropriate
> interface address to the connection. If you are using it to configure
> an interface, it can remove an address from the interface, instead. **It
> depends on the context of use to determine what "no particular
> address" really does.**
>
>
> **In the context of a route entry, it usually means the default route**.
> That happens as a result more of the address mask, which selects the
> bits to compare. A mask of "0.0.0.0" selects no bits, so the compare
> will always succeed. So when such a route is configured, there is
> always somewhere for packets to go (if configured with a valid
> destination).
>
>
> In some cases, merely "0" will also work and have the same effect. But
> this is not guaranteed. The "0.0.0.0" form is the standard way to say
> "no particular address" (in IPv6 that is "::0" or just "::").
>
>
>
**Reference** [0.0.0.0](http://en.wikipedia.org/wiki/0.0.0.0):
>
> In the Internet Protocol version 4 the address 0.0.0.0 is a
> non-routable meta-address used to designate an invalid, unknown or non
> applicable target. To give a special meaning to an otherwise invalid
> piece of data is an application of in-band signaling.
>
>
> Uses include:
>
>
> * The address a host claims as its own when it has not yet been assigned an address. Such as when sending the initial DHCPDISCOVER
>
> packet when using DHCP.
> * The address a host assigns to itself when address request via DHCP has failed, provided the host's IP stack supports this. This usage has been replaced with the APIPA mechanism in modern operating
>
> systems.
> * A way to specify "any IPv4-host at all". It is used in this way when specifying a default route.
> * A way to explicitly specify that the target is unavailable.[1](https://i.stack.imgur.com/UORYD.png)
> * A way to specify "any IPv4 address at all". It is used in this way when configuring servers (i.e. when binding listening sockets).
> This is known to TCP programmers as INADDR\_ANY. (bind(2) binds to
>
> addresses, not interfaces.)
>
>
> In IPv6, the all-zeros-address is written as "::".
>
>
>
**DHCP Discovery/Request:**
Reference [Understanding and Troubleshooting DHCP in Catalyst Switch or Enterprise Networks](http://www.cisco.com/c/en/us/support/docs/ip/dynamic-address-allocation-resolution/27470-100.html)
>
> When a client boots up for the first time, it is said to be in the
> Initializing state, and transmits a DHCPDISCOVER message on its local
> physical subnet over User Datagram Protocol (UDP) port 67 (BootP
> server). **Since the client has no way of knowing the subnet to which it
> belongs, the DHCPDISCOVER is an all subnets broadcast (destination IP
> address of 255.255.255.255), with a source IP address of 0.0.0.0. The
> source IP address is 0.0.0.0, since the client does not have a
> configured IP address.** If a DHCP server exists on this local subnet
> and is configured and operating correctly, the DHCP server will hear
> the broadcast and respond with a DHCPOFFER message. If a DHCP server
> does not exist on the local subnet, there must be a DHCP/BootP Relay
> Agent on this local subnet to forward the DHCPDISCOVER message to a
> subnet that contains a DHCP server.
>
>
> This relay agent can either be a dedicated host (for example,
> Microsoft Windows Server), or router (for example, a Cisco router
> configured with interface level IP helper statements).
>
>
>
...
>
> After the client receives a DHCPOFFER, it responds with a DHCPREQUEST message, indicating its intent to accept the parameters in the DHCPOFFER, and moves into the Requesting state. The client may receive multiple DHCPOFFER messages, one from each DHCP server that received the original DHCPDISCOVER message. The client chooses one DHCPOFFER and responds to that DHCP server only, implicitly declining all other DHCPOFFER messages. The client identifies the selected server by populating the Server Identifier option field with the DHCP server's IP address. The DHCPREQUEST is also a broadcast, so all DHCP servers that sent a DHCPOFFER will see the DHCPREQUEST, and each will know whether its DHCPOFFER was accepted or declined. Any additional configuration options that the client requires will be included in the options field of the DHCPREQUEST message. **Even though the client has been offered an IP address, it will send the DHCPREQUEST message with a source IP address of 0.0.0.0. At this time, the client has not yet received verification that it is clear to use the IP address.**
>
>
>
...
>
> Client-Server Conversation for Client Obtaining DHCP Address Where Client and DHCP Server Reside on Same Subnet
>
>
> 
>
>
>
**Default Route:**
Reference [Configuring a Gateway of Last Resort Using IP Commands](http://www.cisco.com/c/en/us/support/docs/ip/routing-information-protocol-rip/16448-default.html)
>
> This document explains how to configure a default route, or gateway of
> last resort. These IP commands are used:
>
>
> * ip default-gateway
> * ip default-network
> * and ip route 0.0.0.0 0.0.0.0
>
>
> **ip route 0.0.0.0 0.0.0.0**
>
>
> Creating a static route to network 0.0.0.0 0.0.0.0 is another way to
> set the gateway of last resort on a router. As with the ip
> default-network command, using the static route to 0.0.0.0 is not
> dependent on any routing protocols. However, ip routing must be
> enabled on the router.
>
>
> Note: IGRP does not understand a route to 0.0.0.0. Therefore, it
> cannot propagate default routes created using the ip route 0.0.0.0
> 0.0.0.0 command. Use the ip default-network command to have IGRP propagate a default route.
>
>
> | Thanks for looking into it but i found the answer.
For your knowledge and mine as well, i would like to tell that 0.0.0.0 IP address is used when a new network is formed and the DHCP server is on in that network, so as it a new network none of the workstations is having its own IP , so to configure and get the IP computer generates the packet with Source IP 0.0.0.0 and this packet is automatically received to DHCP server as per configuration. |
33,087,071 | Every time I try to run the create.sql file I have, it says there is a syntax error near "buy\_price". The rest of the tables work fine, though.
```
create table Item (itemID string PRIMARY KEY,
name string,
currently string,
buy_price string,
first_bid string,
started string,
ends string,
userID string references User,
description string,
constraint ch_buy_price check buy_price >= first_bid,
constraint );
```
Any help would be appreciated. | 2015/10/12 | [
"https://Stackoverflow.com/questions/33087071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2852231/"
]
| The check constraint needs to be enclosed in parentheses:
```
create table item
(
itemid string primary key,
name string,
currently_ string,
buy_price string,
first_bid string,
started string,
ends string,
userid string references user,
description string,
constraint chk_buy_price check (buy_price >= first_bid) --<< here
);
```
You also have an additional `constraint` at the end which needs to be removed. | You are getting the error because you can not refer first\_bid(table column) in check constraint(**Column check constraint cannot reference other column**).If you want to have a check for this use triggers. |
2,697,152 | I'm looking for a decent WPF or Winform time range selector, much like a home central heating system, where a time range is selectable.
<http://lhill.com.au/l%20hill%20web%20page%20pictures/time%20clock%202.jpg>
Is there any GUI libraries or examples available to fulfill this need? | 2010/04/23 | [
"https://Stackoverflow.com/questions/2697152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271200/"
]
| You are mixing up variables, references and objects.
Doing `delete y;` removes the variable y. As the variable no longer exists, it will naturally no longer have a value. Thus the reference that the variable contained is gone.
Removing the variable will however not in itself remove the object that it was referencing. The array still contains a reference to the object, and neither of those depend on the existance of the variable.
There is actually no way of removing the object directly. You remove objects by destroying all references to it, not the other way around. You want the object to remove it's references, which is simply not how it works. | That's not how `delete` works. It will delete the object reference you pass to it - not any other references to the same object. You're looking for something like a "weak reference" here and I'm not aware of any ways of implementing those in JavaScript. |
2,697,152 | I'm looking for a decent WPF or Winform time range selector, much like a home central heating system, where a time range is selectable.
<http://lhill.com.au/l%20hill%20web%20page%20pictures/time%20clock%202.jpg>
Is there any GUI libraries or examples available to fulfill this need? | 2010/04/23 | [
"https://Stackoverflow.com/questions/2697152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271200/"
]
| You are mixing up variables, references and objects.
Doing `delete y;` removes the variable y. As the variable no longer exists, it will naturally no longer have a value. Thus the reference that the variable contained is gone.
Removing the variable will however not in itself remove the object that it was referencing. The array still contains a reference to the object, and neither of those depend on the existance of the variable.
There is actually no way of removing the object directly. You remove objects by destroying all references to it, not the other way around. You want the object to remove it's references, which is simply not how it works. | Would this help?
`Var x=[{}];
var y=x[0];`
Edit:
Sorry, I was a bit brief in my first attempt at answering. What I'd start asking is: why does y need to "exist" outside of the array in the first place? Can't you just create an array of objects and use delete or array.splice() to remove the object when you need to?
Second, if y needs to exist outside of the array, what you need to do is either to create a property that refers to the array index, or a utility function that can scan through the array to find the correct object reference to remove. In other words, something like
```
var x=[]; var y={}; y.arrayIndex=(x.push(y)-1);
// later on, you want to get rid of y
delete x[y.arrayIndex]; delete y;
``` |
2,697,152 | I'm looking for a decent WPF or Winform time range selector, much like a home central heating system, where a time range is selectable.
<http://lhill.com.au/l%20hill%20web%20page%20pictures/time%20clock%202.jpg>
Is there any GUI libraries or examples available to fulfill this need? | 2010/04/23 | [
"https://Stackoverflow.com/questions/2697152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271200/"
]
| You are mixing up variables, references and objects.
Doing `delete y;` removes the variable y. As the variable no longer exists, it will naturally no longer have a value. Thus the reference that the variable contained is gone.
Removing the variable will however not in itself remove the object that it was referencing. The array still contains a reference to the object, and neither of those depend on the existance of the variable.
There is actually no way of removing the object directly. You remove objects by destroying all references to it, not the other way around. You want the object to remove it's references, which is simply not how it works. | >
> This doesnt work:
>
> ```
> x.push(y);
> ```
>
>
>
>
Of course it does, it will work exactly as intended - pushing the value of y to the array you created.
The [`delete`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator) operator is specifically for deleting properties on objects, if the expression following the operator does not resolve to a property then nothing happens at all.
```
var y = {"someprop":true};
delete y;
alert(y.someprop); // alerts "true"
```
Try it in your browser window, paste the following into your address bar and hit enter:
```
javascript:var y = {"someprop":true}; delete y; alert(y.someprop);
``` |
6,125,353 | I have three tabs (div- enabled on click) in my view, In tab3 I have a delete functionality. When I click "Ok" in the confirmation box, the record is deleted and redirected to my view, which is tab1 enable.
My controller:
```
public ActionResult DeleteAccount(int? id)
{
if(id.HasValue)
{ this.UserAccountTasks.DeleteUserProfile(id.Value); }
return this.RedirectToAction("ManageCompanies");
}
```
How can I redirect to the same tab3 after deletion? | 2011/05/25 | [
"https://Stackoverflow.com/questions/6125353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760845/"
]
| Start with this:
```
return RedirectToAction("ManageCompanies", new { showThirdTab = true });
```
And in your ManageCompanies Action, take in a bool parameter called showThirdTab. Pass that to your view and if it's true, set a class or some value to tell your javascript to switch to that tab.
Off topic a bit, but might I suggest a different approach? Just return the data/html for your three tabs asynchronously after the delete and load it into the other divs with jQuery. | I have listed below ways, there might be more!
1.All the operations in tabs should be done with ajax call.
2.With Html and model data manipulation.
**Steps:**
a). Create a property in the model, "ActiveTab" type integer
b). In the view,
```
@{
//We can also use the array
string activeTabCss1 =Model.ActiveTab == 1? "active-tab":String.Empty ;
string activeTabCss2 = Model.ActiveTab == 2? "active-tab":String.Empty ;
string activeTabCss3 = Model.ActiveTab == 3? "active-tab":String.Empty ;
}
<div class="tab @activeTabCss1"></div>
<div class="tab @activeTabCss2"></div>
<div class="tab @activeTabCss3"></div>
```
3.Use jquery for manipulating DOM elements.
**Steps:**
a). Follow step 2.a
b). In the view, create a hidden for ActiveTab.
```
@Html.HiddenFor(m=>m.ActiveTab)
```
c). Write a below javascript function.
```
$(document).ready(function(){
var activeTab = $("#ActiveTab").val();
$(".tab:nth-child("+activeTab +")").addClass('active-tab');
});
``` |
138,562 | **Warning:** Massive spoilers ahead for those who haven't read *A Dance With Dragons*. Don't proceed if you do not wish to be spoiled.
---
In *A Dance With Dragons* Epilogue, we see the following conversation between Kevan Lannister and Varys:
>
> "Aegon?" For a moment he did not understand. Then he remembered. A
> babe swaddled in a crimson cloak, the cloth stained with his blood and
> brains.
>
>
> "Dead. He's dead."
>
>
> "No." The eunuch's voice seemed deeper. "He is here."
>
>
>
Before that, Aegon explains to Tyrion how he escaped King's Landing:
>
> โA true friend, our Lord Connington. He must be, to remain so fiercely
> loyal to the grandson of the king who took his lands and titles and
> sent him into exile. A pity about that. Elsewise Prince Rhaegarโs
> friend might have been on hand when my father sacked Kingโs Landing,
> to save Prince Rhaegarโs precious little son from getting his royal
> brains dashed out against a wall.โ
>
>
> The lad flushed. โThat was not me. I told you. **That was some
> tannerโs son from Pisswater Bend whose mother died birthing him. His
> father sold him to Lord Varys for a jug of Arbor gold**. He had other
> sons but had never tasted Arbor gold. Varys gave the Pisswater boy to
> my lady mother and carried me away.โ
>
>
> โAye.โ Tyrion moved his elephants. โAnd when the pisswater prince was
> safely dead, **the eunuch smuggled you across the narrow sea to his
> fat friend the cheesemonger, who hid you on a poleboat and found an
> exile lord willing to call himself your father**. It does make for a
> splendid story, and the singers will make much of your escape once you
> take the Iron Throne โฆ assuming that our fair Daenerys takes you for
> her consort.โ
>
>
>
Of course it makes a splendid story but then the question arises, Why couldn't Varys save Rhaenys as well?
Rhaenys was important because:
1. She was Aegon's heir if any mishap was to befall their uncle Viserys (Targaryens prefer male succession in aftermath of Dance of Dragons. See succession of King Viserys II despite claims of sisters of King Baelor).
2. She was potential bride for Aegon.
But yet, she was left to her fate, apparently while her younger brother was saved.
Finding a silver-haired babe is no small deed. Sure there are bound to be silver-haired bastards sired by Lyseni Sailors on Whores of King's Landing (Yet this boy was supposedly sold by his father, not mother) but Rhaenys had common hair and looks and would have been easier to be replaced with a body double as compared to the typical Targaryen Princeling Aegon. Yet there was no effort at all.
Princess Elia was with "fake" Aegon when Gregor Clegane broke into her room. So if Varys' story is correct, She must have been taken into confidence by the eunuch. How on earth did Varys manage to make a mother agree to leaving her one child to beasts like Amory Lorch while saving the other? It is clear nevertheless, Varys never made any substantial effort to save the princess as well, if he made any efforts at all.
How does Varys explain that? Does he ever?1 Because I don't remember anything like Varys talking about Princess Rhaenys except the little speech he gave to Eddard Stark regarding her murder and her kitten. Then of course there are other indicators, suggesting that [Varys may have been lying altogether (Linked post contains similar level of spoilers)](https://scifi.stackexchange.com/a/131317/54887).
It is just very disconcerting that no one, be it Tyrion, Jon Connington or Aegon himself raises this question that why couldn't Rhaenys be saved as well?
---
1. If he doesn't, *We Do not Know yet* is a perfectly valid answer until we do. | 2016/08/22 | [
"https://scifi.stackexchange.com/questions/138562",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/54887/"
]
| There's a plethora of reasons that Varys could have said to convince people that Rhaenys wasn't able to be saved. I don't think there is canon evidence for the reasoning he may have given, but we can speculate:
* **She wasn't as important**
As you said in the question, male heirs are preferred over their female counterparts. Whilst ensuring that Aegon would have had a relative to wed to keep the bloodline pure, that probably wasn't a priority when the possibility of having their entire family wiped out was upon them.
This means that he may have just expended more effort in rescuing Aegon than Rhaenys, and she was collateral damage in order to make the deception more believable. Having the corpse of one child would make everyone else more likely to believe that the other is also who they were supposed to be, and people wouldn't look as closely at the baby to make sure it was the right child.
* **He tried, but couldn't save her**
Ned was captured and Sansa was taken hostage in aGoT, yet Arya managed to escape. Similarly, Varys may have had a plan to rescue them both firmly in place, along with replicas, yet when the time came he wasn't able to get to Rhaenys and decided to not risk Aegon's life in order to look for her.
* **He couldn't find a replacement**
He says he bought a baby from a man in exchange for wine, as the guy had other sons, but how many people would give up their (8 year old?) child for such a fee, or for anything? If they raised her for that long, it's unlikely that they would give her up to an unknown fate.
It would have been much more difficult to find a replacement child for her than for a baby, particularly one who looks convincingly enough like her to hold up to scrutiny. She would have been at court for years, so many lords would know her face, as opposed to a newborn that most people wouldn't recognize.
* **It was harder to conceal a child than a baby**
Carrying around a baby, as long as it doesn't cry, can be hidden quite easily under a large cloak (a disguise Varys makes use of on several occasions). It would be trivial to get Aegon out of the city without anyone paying attention to Varys, and also smuggling the replacement in.
However, it would be much more difficult to smuggle out a young girl, particularly if his deception was revealed and people were looking for the escapees. In addition, he would have had to have found a way to get a young girl into the castle without arousing suspicion before taking a different one out without anybody asking questions. If there was any hint of such things happening and he was caught, they would all have been killed. | Why doesn't he explain why he didn't save her?
----------------------------------------------
No-one asks. Why doesn't anyone ask? Well, the story about saving Aegon on it's own is already audacious and daring enough. As Tyrion said in your quote:
>
> It does make for a splendid story, and the singers will make much of your escape
>
>
>
It's already potentially the stuff of legend. It's just not very common to react to the revelation that someone did something audacious and stunning by demanding to know why they didn't do another even more audacious and stunning thing *at the same time*.
This isn't a cheesy superhero movie where the expectation is that if someone has to choose between saving one of two people against formidable odds, they'll somehow contrive to save both while delivering a pithy one-liner. This is a world where heroes struggling to choose who to save against formidable odds typically fail to save either and die a tragic failure.
Why did he *actually* not save her?
-----------------------------------
If the plan was real, adding Rhaenys would have more than doubled the risk of failure (since she's more difficult to swap and to smuggle), *without* more than doubling the dynastic "rewards": the law of diminishing returns applies to heirs as much as it does economics, and while two heirs are better than one, they're not more than twice as good. Diminishing returns doesn't apply to the intrinsic value of human lives - but hey, this is Varys we're talking about, that's never been his concern.
Big problems with substituting her:
* Children are more recognisable than babies. What if the person who charged into that bedroom wasn't a murderous brute, but was someone capable of saying "Hang on, why does the princess have another girl's face?". Or, more likely, a diligent solider who takes the princess captive and brings her somewhere someone who would recognise the princess sees her, e.g. a high ranking lord or someone at court who defects like Pycelle, Barristand and Jaime (and Varys!) did.
* Then there's the period after the substitution while the war is still ongoing. How do you prevent anyone who knows the princess from seeing the princess's face, or hearing her voice, for an unknown period of time? Very few people can be in on the deception, since some will defect and could use this secret to save their necks.
* The baby's silver hair isn't that big an issue. There are heaps of examples of characters successfully disguising (non-baby) hair with dye or shaving.
* Smuggling a recognisable child princess out of a city without being recognised is also much, much harder than smuggling a baby. Shave the kid if you're worried about the silver hair, but you can't change a princess's face or make a frightened, confused young child princess convincingly impersonate a commoner overnight. What do you do if she throws a Royal Tantrum when served a bowl of brown on a dirty, smelly ship, instead of nutmeg-roasted lamb? Substituting babies is so easy, we see people do it for real with Gilly's and Mance's kids, and get away with it.
Varys isn't in the habit of taking big risks to save someone out of kindness when the risk/benefit analysis is unfavourable, as he made clear while telling Ned that he could rescue him, but wouldn't. Gilly and Val agreed (reluctantly) to a baby swap to save a baby, so it's not something people wouldn't consider.
That's if the plan was real...
Were either of them rescued at all?
-----------------------------------
Personally, I'm of the view that there are many little holes and out-of-character oddities in Varys's account, and the simplest explanation is that the whole thing is a convenient cover story and good PR for (probably) a conveniently located orphaned Blackfyre (or maybe a Dayne). But that's a whole other question... there are heaps of theories as you well know!
One thing that goes for all of them, however, is that Varys being unsure if Westerosi lords would buy his story gives us an explanation for what otherwise appears to be an uncharacteristic "Bond villain" moment with Kevan, where he needlessly takes a risk by telling an adversary his plan before killing them.
If the whole thing is a lie, this is actually a smart move: testing if it's a good enough lie to take in an intelligent, level-headed lord like Kevan. If he sees through the lie, meh, he's dead anyway, and you learned that you need to raise your game.
But we're getting speculative now, so let's stop... |
49,363,411 | I have strings similar to the following:
```
4123499-TESCO45-123
every99999994_54
```
And I want to extract the largest numeric sequence in each string, respectively:
```
4123499
99999994
```
I have previously tried regex (I am using VB6)
```
Set rx = New RegExp
rx.Pattern = "[^\d]"
rx.Global = True
StringText = rx.Replace(StringText, "")
```
Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:
```
412349945123
```
Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help! | 2018/03/19 | [
"https://Stackoverflow.com/questions/49363411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3326321/"
]
| You cannot get the result by just a regex. You will have to extract all numeric chunks and get the longest one using other programming means.
Here is an example:
```
Dim strPattern As String: strPattern = "\d+"
Dim str As String: str = "4123499-TESCO45-123"
Dim regEx As New RegExp
Dim matches As MatchCollection
Dim match As Match
Dim result As String
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
Set matches = regEx.Execute(str)
For Each m In matches
If result < Len(m.Value) Then result = m.Value
Next
Debug.Print result
```
The `\d+` with `RegExp.Global=True` will find all digit chunks and then only the longest will be printed after all matches are processed in a loop. | That's not solvable with an RE on its own.
Instead you can simply walk along the string tracking the longest consecutive digit group:
```
For i = 1 To Len(StringText)
If IsNumeric(Mid$(StringText, i, 1)) Then
a = a & Mid$(StringText, i, 1)
Else
a = ""
End If
If Len(a) > Len(longest) Then longest = a
Next
MsgBox longest
```
(first result wins a tie) |
49,363,411 | I have strings similar to the following:
```
4123499-TESCO45-123
every99999994_54
```
And I want to extract the largest numeric sequence in each string, respectively:
```
4123499
99999994
```
I have previously tried regex (I am using VB6)
```
Set rx = New RegExp
rx.Pattern = "[^\d]"
rx.Global = True
StringText = rx.Replace(StringText, "")
```
Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:
```
412349945123
```
Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help! | 2018/03/19 | [
"https://Stackoverflow.com/questions/49363411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3326321/"
]
| You cannot get the result by just a regex. You will have to extract all numeric chunks and get the longest one using other programming means.
Here is an example:
```
Dim strPattern As String: strPattern = "\d+"
Dim str As String: str = "4123499-TESCO45-123"
Dim regEx As New RegExp
Dim matches As MatchCollection
Dim match As Match
Dim result As String
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
Set matches = regEx.Execute(str)
For Each m In matches
If result < Len(m.Value) Then result = m.Value
Next
Debug.Print result
```
The `\d+` with `RegExp.Global=True` will find all digit chunks and then only the longest will be printed after all matches are processed in a loop. | If the two examples you gave, are of a standard where:
1. `<long_number>-<some_other_data>-<short_number>`
2. `<text><long_number>_<short_number>`
Are the two formats that the strings come in, there are some solutions.
However, if you are searching any string in any format for the longest number, these will not work.
### Solution 1
```
([0-9]+)[_-].*
```
See the [demo](https://regex101.com/r/r6LDxq/2)
In the first capture group, you should have the longest number for those 2 formats.
**Note**: This assumes that the longest number will be the first number it encounters with an underscore or a hyphen next to it, matching those two examples given.
### Solution 2
```
\d{6,}
```
See the [demo](https://regex101.com/r/r6LDxq/3)
**Note**: This assumes that the shortest number will never exceed 5 characters in length, and the longest number will never be shorter than 6 characters in length |
49,363,411 | I have strings similar to the following:
```
4123499-TESCO45-123
every99999994_54
```
And I want to extract the largest numeric sequence in each string, respectively:
```
4123499
99999994
```
I have previously tried regex (I am using VB6)
```
Set rx = New RegExp
rx.Pattern = "[^\d]"
rx.Global = True
StringText = rx.Replace(StringText, "")
```
Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:
```
412349945123
```
Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help! | 2018/03/19 | [
"https://Stackoverflow.com/questions/49363411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3326321/"
]
| You cannot get the result by just a regex. You will have to extract all numeric chunks and get the longest one using other programming means.
Here is an example:
```
Dim strPattern As String: strPattern = "\d+"
Dim str As String: str = "4123499-TESCO45-123"
Dim regEx As New RegExp
Dim matches As MatchCollection
Dim match As Match
Dim result As String
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
Set matches = regEx.Execute(str)
For Each m In matches
If result < Len(m.Value) Then result = m.Value
Next
Debug.Print result
```
The `\d+` with `RegExp.Global=True` will find all digit chunks and then only the longest will be printed after all matches are processed in a loop. | Please, try.
Pure VB. **No external libs or objects.**
No brain-breaking regexp's patterns.
No string manipulations, so - speed. **Superspeed. ~30 times faster** than [regexp](https://stackoverflow.com/a/49363651/6698332) :)
Easy transform on variouse needs.
For example, concatenate all digits from the source string to a single string.
Moreover, if target string is only intermediate step,
so it's possible to manipulate with numbers only.
```
Public Sub sb_BigNmb()
Dim sSrc$, sTgt$
Dim taSrc() As Byte, taTgt() As Byte, tLB As Byte, tUB As Byte
Dim s As Byte, t As Byte, tLenMin As Byte
tLenMin = 4
sSrc = "every99999994_54"
sTgt = vbNullString
taSrc = StrConv(sSrc, vbFromUnicode)
tLB = LBound(taSrc)
tUB = UBound(taSrc)
ReDim taTgt(tLB To tUB)
t = 0
For s = tLB To tUB
Select Case taSrc(s)
Case 48 To 57
taTgt(t) = taSrc(s)
t = t + 1
Case Else
If CBool(t) Then Exit For ' *** EXIT FOR ***
End Select
Next
If (t > tLenMin) Then
ReDim Preserve taTgt(tLB To (t - 1))
sTgt = StrConv(taTgt, vbUnicode)
End If
Debug.Print "'" & sTgt & "'"
Stop
End Sub
```
How to handle `sSrc = "ev_1_ery99999994_54"`, please, make by yourself :)
. |
49,363,411 | I have strings similar to the following:
```
4123499-TESCO45-123
every99999994_54
```
And I want to extract the largest numeric sequence in each string, respectively:
```
4123499
99999994
```
I have previously tried regex (I am using VB6)
```
Set rx = New RegExp
rx.Pattern = "[^\d]"
rx.Global = True
StringText = rx.Replace(StringText, "")
```
Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:
```
412349945123
```
Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help! | 2018/03/19 | [
"https://Stackoverflow.com/questions/49363411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3326321/"
]
| That's not solvable with an RE on its own.
Instead you can simply walk along the string tracking the longest consecutive digit group:
```
For i = 1 To Len(StringText)
If IsNumeric(Mid$(StringText, i, 1)) Then
a = a & Mid$(StringText, i, 1)
Else
a = ""
End If
If Len(a) > Len(longest) Then longest = a
Next
MsgBox longest
```
(first result wins a tie) | If the two examples you gave, are of a standard where:
1. `<long_number>-<some_other_data>-<short_number>`
2. `<text><long_number>_<short_number>`
Are the two formats that the strings come in, there are some solutions.
However, if you are searching any string in any format for the longest number, these will not work.
### Solution 1
```
([0-9]+)[_-].*
```
See the [demo](https://regex101.com/r/r6LDxq/2)
In the first capture group, you should have the longest number for those 2 formats.
**Note**: This assumes that the longest number will be the first number it encounters with an underscore or a hyphen next to it, matching those two examples given.
### Solution 2
```
\d{6,}
```
See the [demo](https://regex101.com/r/r6LDxq/3)
**Note**: This assumes that the shortest number will never exceed 5 characters in length, and the longest number will never be shorter than 6 characters in length |
49,363,411 | I have strings similar to the following:
```
4123499-TESCO45-123
every99999994_54
```
And I want to extract the largest numeric sequence in each string, respectively:
```
4123499
99999994
```
I have previously tried regex (I am using VB6)
```
Set rx = New RegExp
rx.Pattern = "[^\d]"
rx.Global = True
StringText = rx.Replace(StringText, "")
```
Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:
```
412349945123
```
Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help! | 2018/03/19 | [
"https://Stackoverflow.com/questions/49363411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3326321/"
]
| That's not solvable with an RE on its own.
Instead you can simply walk along the string tracking the longest consecutive digit group:
```
For i = 1 To Len(StringText)
If IsNumeric(Mid$(StringText, i, 1)) Then
a = a & Mid$(StringText, i, 1)
Else
a = ""
End If
If Len(a) > Len(longest) Then longest = a
Next
MsgBox longest
```
(first result wins a tie) | Please, try.
Pure VB. **No external libs or objects.**
No brain-breaking regexp's patterns.
No string manipulations, so - speed. **Superspeed. ~30 times faster** than [regexp](https://stackoverflow.com/a/49363651/6698332) :)
Easy transform on variouse needs.
For example, concatenate all digits from the source string to a single string.
Moreover, if target string is only intermediate step,
so it's possible to manipulate with numbers only.
```
Public Sub sb_BigNmb()
Dim sSrc$, sTgt$
Dim taSrc() As Byte, taTgt() As Byte, tLB As Byte, tUB As Byte
Dim s As Byte, t As Byte, tLenMin As Byte
tLenMin = 4
sSrc = "every99999994_54"
sTgt = vbNullString
taSrc = StrConv(sSrc, vbFromUnicode)
tLB = LBound(taSrc)
tUB = UBound(taSrc)
ReDim taTgt(tLB To tUB)
t = 0
For s = tLB To tUB
Select Case taSrc(s)
Case 48 To 57
taTgt(t) = taSrc(s)
t = t + 1
Case Else
If CBool(t) Then Exit For ' *** EXIT FOR ***
End Select
Next
If (t > tLenMin) Then
ReDim Preserve taTgt(tLB To (t - 1))
sTgt = StrConv(taTgt, vbUnicode)
End If
Debug.Print "'" & sTgt & "'"
Stop
End Sub
```
How to handle `sSrc = "ev_1_ery99999994_54"`, please, make by yourself :)
. |
50,042,755 | I want to execute two keywords in a test-case out of which, one keyword has to be executed only once and the other has to be executed multiple times. Please find the code below to understand the logic of the execution:
```
*** Settings ***
Test Setup OPEN CHROME BROWSER
Test Teardown CLOSE CHROME BROWSER
Test Template KEYWORD1
Force Tags Smoke
*** Test Cases *** userid userpass content
VALID CREDENTIAL [email protected] mypass CONTENT A
CONTENT B
CONTENT C
*** Keywords ***
--------------------------------------------------------------------------
KEYWORD 1
[Arguments] ${userid} {userpass}
GO TO LOGIN PAGE
ENTER USERID
ENTER PASSWORD
CLICK ON LOGIN BUTTON
-----needs to run once and then KEYWORD 2 should run thrice---------------
KEYWORD 2
[Arguments] ${content}
CLICK ON CONTENT TILE ${content}
DO SOME ACTION
GO TO HOME
```
I want 'keyword 1' to be executed only once and 'keyword 2' to be repeated 3 times as per the content list. Please guide me how to handle this.
Current issue:
While continuing with second test it asks userid and userpass to be passed again.
What I want to achieve:
Login once into the web-portal(KEYWORD1). RUN KEYWORD 2 with CONTENT A as arguement, then with CONTENT B as arguement and finally with CONTENT C. I should not login for each time the content needs to be changed. | 2018/04/26 | [
"https://Stackoverflow.com/questions/50042755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9044468/"
]
| ```
*** Settings ***
Test Setup KEYWORD1 ${reg_userid} ${reg_userpass}
Test Teardown CLOSE CHROME BROWSER
Test Template KEYWORD2 ${content}
Force Tags Smoke
*** Test Cases *** content
VALID CREDENTIAL CONTENT A
CONTENT B
CONTENT C
*** Keywords ***
#------------------------KEYWORD 1 runs once--------------------------------
KEYWORD 1
[Arguments] ${userid} {userpass}
OPEN CHROME BROWSER
GO TO LOGIN PAGE
ENTER USERID
ENTER PASSWORD
CLICK ON LOGIN BUTTON
#------------------------KEYWORD 2 runs thrice-----------------------------
KEYWORD 2
[Arguments] ${content}
CLICK ON CONTENT TILE ${content}
DO SOME ACTION
GO TO HOME
***Variables***
${reg_userid} [email protected]
${reg_userpass} password
``` | You can create another keyword like below
```
Execute Keyword Multiple Times
[Arguments] ${keyword_name} @{params}
FOR ${i} IN @{params}
Run Keyword ${keyword_name} ${i}
END
```
and you can call it
```
Execute Keyword Multiple Times KEYWORD 2 CONTENT A CONTENT B ...
```
If You need to give more than one param you can use dict.
I suggest you another way: give to KEYWORD 2 n args and put a loop into it. The code will be more understandable. |
50,042,755 | I want to execute two keywords in a test-case out of which, one keyword has to be executed only once and the other has to be executed multiple times. Please find the code below to understand the logic of the execution:
```
*** Settings ***
Test Setup OPEN CHROME BROWSER
Test Teardown CLOSE CHROME BROWSER
Test Template KEYWORD1
Force Tags Smoke
*** Test Cases *** userid userpass content
VALID CREDENTIAL [email protected] mypass CONTENT A
CONTENT B
CONTENT C
*** Keywords ***
--------------------------------------------------------------------------
KEYWORD 1
[Arguments] ${userid} {userpass}
GO TO LOGIN PAGE
ENTER USERID
ENTER PASSWORD
CLICK ON LOGIN BUTTON
-----needs to run once and then KEYWORD 2 should run thrice---------------
KEYWORD 2
[Arguments] ${content}
CLICK ON CONTENT TILE ${content}
DO SOME ACTION
GO TO HOME
```
I want 'keyword 1' to be executed only once and 'keyword 2' to be repeated 3 times as per the content list. Please guide me how to handle this.
Current issue:
While continuing with second test it asks userid and userpass to be passed again.
What I want to achieve:
Login once into the web-portal(KEYWORD1). RUN KEYWORD 2 with CONTENT A as arguement, then with CONTENT B as arguement and finally with CONTENT C. I should not login for each time the content needs to be changed. | 2018/04/26 | [
"https://Stackoverflow.com/questions/50042755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9044468/"
]
| What you need is the [Repeat Keyword](http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Repeat%20Keyword) from the [BuildIn](http://robotframework.org/robotframework/latest/libraries/BuiltIn.html) library.
>
> Examples:
>
>
>
> ```robot
> Repeat Keyword 5 times Go Back
> Repeat Keyword ${var} Some Keyword arg1 arg2
> Repeat Keyword 2 minutes Some Keyword arg1 arg2
>
> ```
>
> | You can create another keyword like below
```
Execute Keyword Multiple Times
[Arguments] ${keyword_name} @{params}
FOR ${i} IN @{params}
Run Keyword ${keyword_name} ${i}
END
```
and you can call it
```
Execute Keyword Multiple Times KEYWORD 2 CONTENT A CONTENT B ...
```
If You need to give more than one param you can use dict.
I suggest you another way: give to KEYWORD 2 n args and put a loop into it. The code will be more understandable. |
44,516,613 | I had just been having problems with creating new records as posted here [Can't create new record via form in Rails 5 app](https://stackoverflow.com/questions/44505042/cant-create-new-record-via-form-in-rails-5-app), so not sure if this could be related.
The issue is that when I edit an existing record, the changes are captured fine, but it creates a duplicate and amends the URL with what looks like a hash: <https://www.gourmetcoffee.london/coffeeshops/caravan-exmouth-market-2f9f6d3c-7ca3-4542-ac40-207104f835fa>. I'm using friendly\_ids gem to dynamically take the `:name` field and use that as the unique url.
I have other tables in the db which I can edit ok.
I saw a [related question](https://stackoverflow.com/questions/18946479/ror-nested-attributes-produces-duplicates-when-edit) and his solution was to add the `:id` to the permited\_params, I've ensured that `:slug` and `:id` are permitted, but this is not solved it so far.
*my controller*
```
class CoffeeshopsController < ApplicationController
http_basic_authenticate_with name: "****", password: "****", except: [:index, :show, :favorite, :bookmarked]
def index
if params[:tag]
@coffeeshops = Coffeeshop.tagged_with(params[:tag])
else
@coffeeshops = Coffeeshop.all
end
@coffeeshops = @coffeeshops.order("created_at ASC").page params[:page]
end
def show
@coffeeshop = Coffeeshop.find(params[:id])
@last3_coffeeshops = Coffeeshop.last(3)
@commentable = @coffeeshop
@comments = @commentable.comments
@comment = Comment.new
@locale_cafe = Coffeeshop.where(locale: @coffeeshop.locale)
@fave_count = @coffeeshop.favorited_by
@user = User.all
@currentuser = current_user
end
def new
end
def edit
@coffeeshop = Coffeeshop.friendly.find(params[:id])
end
def create
@coffeeshop = Coffeeshop.new(coffeeshop_params)
if @coffeeshop.save
redirect_to @coffeeshop
else
render 'new'
end
end
def update
@coffeeshop = Coffeeshop.friendly.find(params[:id])
if @coffeeshop.update(coffeeshop_params)
redirect_to @coffeeshop
else
render 'edit'
end
end
def destroy
@coffeeshop = Coffeeshop.find(params[:id])
@coffeeshop.destroy
redirect_to coffeeshops_path
end
def favorite
@coffeeshop = Coffeeshop.find(params[:id])
type = params[:type]
if type == "favorite"
current_user.favorites << @coffeeshop
redirect_to :back, notice: "You favorited #{@coffeeshop.name}"
elsif type == "unfavorite"
current_user.favorites.delete(@coffeeshop)
redirect_to :back, notice: "Unfavorited #{@coffeeshop.name}"
else
# Type missing, nothing happens
redirect_to :back, notice: "Nothing happened."
end
end
def bookmarked
@coffeeshop = Coffeeshop.find(params[:id])
type = params[:type]
if type == "bookmarked"
current_user.bookmarks << @coffeeshop
redirect_to :back, notice: "You bookmarked #{@coffeeshop.name}"
elsif type == "unbookmark"
current_user.bookmarks.delete(@coffeeshop)
redirect_to :back, notice: "You removed #{@coffeeshop.name} bookmark"
else
# Type missing, nothing happens
redirect_to :back, notice: "Nothing happened."
end
end
private
def coffeeshop_params
params.require(:coffeeshop).permit(:name, :desc, :area, :url, :email, :address, :postcode, :locale, :phone, :image_path, :image_thumb_path, :snippet, :beans, :long_black, :tag_list, :slug, :id)
end
end
```
*model*
```
class Coffeeshop < ApplicationRecord
paginates_per 5
include PgSearch
pg_search_scope :search_by_full_name, against: [:name]
require 'acts-as-taggable-on'
acts_as_taggable
#acts_as_taggable_on :tag_list
has_many :comments, as: :commentable
belongs_to :roaster
belongs_to :user
has_many :favorite_coffeeshops# just the 'relationships'
has_many :favorited_by, through: :favorite_coffeeshops, source: :user
has_many :bookmarked_coffeeshops# just the 'relationships'
has_many :bookmarked_by, through: :bookmarked_coffeeshops, source: :user
validates :name, :snippet, :area, :image_thumb_path, :image_path, :presence => true
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
private
def should_generate_new_friendly_id?
slug.nil? || name_changed?
end
end
```
*routes*
```
Simons-MBP:gourmet_coffee Simon$ rails routes
Prefix Verb URI Pattern Controller#Action
roasters GET /roasters(.:format) roasters#index
POST /roasters(.:format) roasters#create
new_roaster GET /roasters/new(.:format) roasters#new
edit_roaster GET /roasters/:id/edit(.:format) roasters#edit
roaster GET /roasters/:id(.:format) roasters#show
PATCH /roasters/:id(.:format) roasters#update
PUT /roasters/:id(.:format) roasters#update
DELETE /roasters/:id(.:format) roasters#destroy
home_index GET /home/index(.:format) home#index
root GET / home#index
new_user_session GET /auth/sign_in(.:format) users/sessions#new
user_session POST /auth/sign_in(.:format) users/sessions#create
destroy_user_session DELETE /auth/sign_out(.:format) users/sessions#destroy
user_facebook_omniauth_authorize GET|POST /auth/auth/facebook(.:format) users/omniauth_callbacks#passthru
user_facebook_omniauth_callback GET|POST /auth/auth/facebook/callback(.:format) users/omniauth_callbacks#facebook
new_user_password GET /auth/password/new(.:format) devise/passwords#new
edit_user_password GET /auth/password/edit(.:format) devise/passwords#edit
user_password PATCH /auth/password(.:format) devise/passwords#update
PUT /auth/password(.:format) devise/passwords#update
POST /auth/password(.:format) devise/passwords#create
cancel_user_registration GET /auth/cancel(.:format) users/registrations#cancel
new_user_registration GET /auth/sign_up(.:format) users/registrations#new
edit_user_registration GET /auth/edit(.:format) users/registrations#edit
user_registration PATCH /auth(.:format) users/registrations#update
PUT /auth(.:format) users/registrations#update
DELETE /auth(.:format) users/registrations#destroy
POST /auth(.:format) users/registrations#create
destroy_fb_user_session DELETE /sign_out(.:format) devise/sessions#destroy
new_message GET /contact-me(.:format) messages#new
create_message POST /contact-me(.:format) messages#create
title GET /article(.:format) articles#show
longblack GET /longblack(.:format) longblack#index
prices GET /prices(.:format) prices#new
POST /prices(.:format) prices#create
about GET /about(.:format) pages#about
cookiepolicy GET /cookiepolicy(.:format) pages#cookiepolicy
map GET /map(.:format) pages#map
tag GET /articles/tags/:tag(.:format) articles#index
coffeeshops_tag GET /coffeeshops/tags/:tag(.:format) coffeeshops#index
roasters_tag GET /roasters/tags/:tag(.:format) roasters#index
roaster_comments GET /roasters/:roaster_id/comments(.:format) comments#index
POST /roasters/:roaster_id/comments(.:format) comments#create
new_roaster_comment GET /roasters/:roaster_id/comments/new(.:format) comments#new
edit_roaster_comment GET /roasters/:roaster_id/comments/:id/edit(.:format) comments#edit
roaster_comment GET /roasters/:roaster_id/comments/:id(.:format) comments#show
PATCH /roasters/:roaster_id/comments/:id(.:format) comments#update
PUT /roasters/:roaster_id/comments/:id(.:format) comments#update
DELETE /roasters/:roaster_id/comments/:id(.:format) comments#destroy
GET /roasters(.:format) roasters#index
POST /roasters(.:format) roasters#create
GET /roasters/new(.:format) roasters#new
GET /roasters/:id/edit(.:format) roasters#edit
GET /roasters/:id(.:format) roasters#show
PATCH /roasters/:id(.:format) roasters#update
PUT /roasters/:id(.:format) roasters#update
DELETE /roasters/:id(.:format) roasters#destroy
article_comments GET /articles/:article_id/comments(.:format) comments#index
POST /articles/:article_id/comments(.:format) comments#create
new_article_comment GET /articles/:article_id/comments/new(.:format) comments#new
edit_article_comment GET /articles/:article_id/comments/:id/edit(.:format) comments#edit
article_comment GET /articles/:article_id/comments/:id(.:format) comments#show
PATCH /articles/:article_id/comments/:id(.:format) comments#update
PUT /articles/:article_id/comments/:id(.:format) comments#update
DELETE /articles/:article_id/comments/:id(.:format) comments#destroy
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
coffeeshop_comments GET /coffeeshops/:coffeeshop_id/comments(.:format) comments#index
POST /coffeeshops/:coffeeshop_id/comments(.:format) comments#create
new_coffeeshop_comment GET /coffeeshops/:coffeeshop_id/comments/new(.:format) comments#new
edit_coffeeshop_comment GET /coffeeshops/:coffeeshop_id/comments/:id/edit(.:format) comments#edit
coffeeshop_comment GET /coffeeshops/:coffeeshop_id/comments/:id(.:format) comments#show
PATCH /coffeeshops/:coffeeshop_id/comments/:id(.:format) comments#update
PUT /coffeeshops/:coffeeshop_id/comments/:id(.:format) comments#update
DELETE /coffeeshops/:coffeeshop_id/comments/:id(.:format) comments#destroy
coffeeshops GET /coffeeshops(.:format) coffeeshops#index
POST /coffeeshops(.:format) coffeeshops#create
new_coffeeshop GET /coffeeshops/new(.:format) coffeeshops#new
edit_coffeeshop GET /coffeeshops/:id/edit(.:format) coffeeshops#edit
coffeeshop GET /coffeeshops/:id(.:format) coffeeshops#show
PATCH /coffeeshops/:id(.:format) coffeeshops#update
PUT /coffeeshops/:id(.:format) coffeeshops#update
DELETE /coffeeshops/:id(.:format) coffeeshops#destroy
favorite_coffeeshop PUT /coffeeshops/:id/favorite(.:format) coffeeshops#favorite
GET /coffeeshops(.:format) coffeeshops#index
POST /coffeeshops(.:format) coffeeshops#create
GET /coffeeshops/new(.:format) coffeeshops#new
GET /coffeeshops/:id/edit(.:format) coffeeshops#edit
GET /coffeeshops/:id(.:format) coffeeshops#show
PATCH /coffeeshops/:id(.:format) coffeeshops#update
PUT /coffeeshops/:id(.:format) coffeeshops#update
DELETE /coffeeshops/:id(.:format) coffeeshops#destroy
bookmarked_coffeeshop PUT /coffeeshops/:id/bookmarked(.:format) coffeeshops#bookmarked
GET /coffeeshops(.:format) coffeeshops#index
POST /coffeeshops(.:format) coffeeshops#create
GET /coffeeshops/new(.:format) coffeeshops#new
GET /coffeeshops/:id/edit(.:format) coffeeshops#edit
GET /coffeeshops/:id(.:format) coffeeshops#show
PATCH /coffeeshops/:id(.:format) coffeeshops#update
PUT /coffeeshops/:id(.:format) coffeeshops#update
DELETE /coffeeshops/:id(.:format) coffeeshops#destroy
GET /coffeeshops(.:format) coffeeshops#index
GET / coffeeshops#index
coffeeshops_new GET /coffeeshops/new(.:format) coffeeshops#new
coffeeshopseast GET /coffeeshopseast(.:format) coffeeshopseast#index
coffeeshopscentral GET /coffeeshopscentral(.:format) coffeeshopscentral#index
profile GET /profile(.:format) profile#show
page GET /pages/*id high_voltage/pages#show
```
*form*
```
<%= form_for :coffeeshop, url: coffeeshops_path do |f| %>
<form>
<div class="form-group">
<p>
<%= f.label :Name %><br>
<%= f.text_field :name, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Snippet %><br>
<%= f.text_area :snippet, class: "form-control", rows: "2" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Desciption %><br>
<%= f.text_area :desc, class: "form-control", rows: "8" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Area %><br>
<%= f.text_area :area, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Locale %><br>
<%= f.text_area :locale, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :URL %><br>
<%= f.text_area :url, class: "form-control" %>
</p>
<div class="form-group">
<p>
<%= f.label :email %><br>
<%= f.text_area :email, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Address %><br>
<%= f.text_area :address, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Postcode %><br>
<%= f.text_area :postcode, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Phone %><br>
<%= f.text_area :phone, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Thumbnail %><br>
<%= f.text_area :image_thumb_path, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Image %><br>
<%= f.text_area :image_path, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Beans %><br>
<%= f.text_area :beans, class: "form-control" %>
</p>
</div>
<div class="form-group">
<p>
<%= f.label :Price_of_long_black %><br>
<%= f.text_area :long_black, class: "form-control" %>
</p>
</div>
<p class="uk-text-right">
<%= link_to 'Cancel', coffeeshops_path(@coffeeshops), class: "btn btn-warning" %>
<%= f.submit "Add", class: "btn btn-primary" %>
</p>
<% end %>
```
**Solution**
For clarity, I'll add the set-up:
Using the same form via a partial for new and update:
`<%= form_for @coffeeshop do |f| %>`
Found I was trying to use the friendly URL to update causing the duplication on id. Using the below solved it:
```
def update
@coffeeshop = Coffeeshop.find(params[:id]) #<was Coffeeshop.friendly.find(params[:id])
if @coffeeshop.update(coffeeshop_params)
redirect_to @coffeeshop
else
render 'edit'
end
end
``` | 2017/06/13 | [
"https://Stackoverflow.com/questions/44516613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240241/"
]
| You need to be more precise when defining the regex. `.*` is too greedy and matches across commas and other stuff.
I suggest using
```
var latencyPattern = regexp.MustCompile(`(round-trip|rtt)\s+\S+\s*=\s*([0-9.]+)/([0-9.]+)/([0-9.]+)/([0-9.]+)\s*ms`)
```
See the [regex demo](https://regex101.com/r/B2ESZj/1).
[Go lang demo](https://play.golang.org/p/drI2b8poLK):
```
package main
import (
"fmt"
"regexp"
"strings"
"strconv"
)
func main() {
strOutput := `1->5 packets transmitted, 5 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.067/0.078/0.087/0.007 ms
2->5 packets transmitted, 5 received, 0% packet loss, time 801ms
rtt min/avg/max/stddev = 0.019/0.034/0.044/0.010 ms, ipg/ewma 200.318/0.038 ms`
latencyPattern := regexp.MustCompile(`(round-trip|rtt)\s+\S+\s*=\s*([0-9.]+)/([0-9.]+)/([0-9.]+)/([0-9.]+)\s*ms`)
matches := latencyPattern.FindAllStringSubmatch(strOutput, -1)
for _, item := range matches {
latency, _ := strconv.ParseFloat(strings.TrimSpace(item[3]), 64)
jitter, _ := strconv.ParseFloat(strings.TrimSpace(item[5]), 64)
fmt.Printf("AVG = %.3f, STDDEV = %.3f\n", latency, jitter)
}
}
```
Result:
```
AVG = 0.078, STDDEV = 0.007
AVG = 0.034, STDDEV = 0.010
```
**Pattern details**:
* `(round-trip|rtt)` - `round-trip` or `rtt` substrings
* `\s+` - 1+ whitespaces
* `\S+` - 1+ non-whitespace symbols
* `\s*=\s*` - a `=` enclosed with 0+ whitespaces
* `([0-9.]+)` - Group 1: the first number
* `/` - a `/`
* `([0-9.]+)` - Group 2: the second number
* `/` - a `/`
* `([0-9.]+)` - Group 3: the third number
* `/` - a `/`
* `([0-9.]+)` - Group 4: the fourth number
* `\s*` - 0+ whitespaces
* `ms` - a substring `ms` | Personally, I would simplify this as much as possible, especially since you aren't trying to pull out all the data, just a couple parts - which are conveniently in the same format in both versions! Essentially, in that string, you only care about `min/avg/max/stddev = 0.019/0.034/0.044/0.010`:
```
re := regexp.MustCompile("min/avg/max/stddev = ([0-9./]+)")
sub := re.FindStringSubmatch(input)
parts := strings.Split(sub[1], "/")
fmt.Printf("Avg: %s, StdDev: %s\n", parts[1], parts[3])
```
[Example on playground](https://play.golang.org/p/k_hWMfOovo). |
2,698,662 | Here's an interesting problem, and result, that I wish to share with the math community here at Math SE. I think I've found a proof without words...
[](https://i.stack.imgur.com/rcIcf.jpg)
I came across this problem sometime back, and here's a possible proof without words that I'll post as a picture -
[](https://i.stack.imgur.com/KSbLS.jpg)
*I claim* that one can, for any inscribed quadrilateral EFGH, make necessary constructions (several parallelograms) as in the figure, and hence show that at least one of the diagonals is parallel to a side of the quadrilateral ABCD.
Is there anything I'm missing, or is the proof complete? Let me know!
Also, please post other proofs in the answers section! (So we can all solve the problem together and discuss several methods for the same - it'll be of use to everyone to know all possible methods of approaching this problem)
I was thinking about a possible solution using complex numbers, assuming one of the side pair to be parallel to the real axis in Argand's plane, for simplicity. A similar solution, not involving too much calculation can be done using vectors!
I'm not sure about coordinate geometry, as it tends to get quite cumbersome in such situations, however if anyone does manage to prove it neatly, please post the solution.
**Share your ideas!** | 2018/03/19 | [
"https://math.stackexchange.com/questions/2698662",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/425395/"
]
| **This is a hint, not a solution.**
Hint: Let's call your set $X$, just to give it a name.
1. Can you show that $\Bbb Q$ is disconnected by exhibiting nonempty open sets $U$ and $V$ with $\Bbb Q = U \cup V$ and $U \cap V = \emptyset$?
2. If you can, then $U\_1 = U \times \Bbb R$ and $V\_1 = V \times \Bbb R$ are both open. (Why?)
3. $U' = U\_1 \cap X$, and $V' = V\_1 \cap X$ are both open subsets of $X$ in the subspace topology. (Why?)
4. $U'$ and $V'$ are nonempty.
You take it from here. | Looking over the comments to John Hughes' answer, I see that you were advised to study how the definitions and properties of connected\subspace\product play out together.
With that as the background, the problem can be tackled by finding a nonempty and proper subset of $D = \mathbb{Q}ร[0,1]$ that is both open and closed.
So we want to find an open set $U$ of $\mathbb{R^2}$ and a closed set of $C$ of $\mathbb{R^2}$ such that
$\tag 1 \emptyset \ne U \cap D = C \cap D \ne D$
There are two candidates that practically 'jump out' for inspection:
$\quad U = (\sqrt2, +\infty) \times \mathbb R$
and
$\quad C = [\sqrt2, +\infty) \times \mathbb R\;$ (recall that the product of two closed sets is closed)
We leave it to the OP to wrap up any loose ends. |
1,188,407 | Relevant questions are:
[Where Linux places the messages of boot?](https://superuser.com/questions/176165/where-linux-places-the-messages-of-boot)
[Name of log file where boot process is logged](https://superuser.com/questions/132496/name-of-log-file-where-boot-process-is-logged?rq=1)
However, these do not answer this question. This question is concerned with how **all** the boot messages can be viewed.
This is for Gentoo, OpenRC, modern kernels, 4.9.6 if you want to get specific. A generic solution that works for all distributions would however be preferable.
The problem is that sometimes an error or warning will scroll by so quickly that it cannot be seen. Nor is it always possible to simply scroll up for two reasons (even with --noclear in inittab): when switching to the framebuffer scrolling up to the point before the switch too place is no longer possible, and second, that after X starts, switching to console and trying to scroll up doesn't allow scrolling at all until new text is added to the buffer. Sometimes, certain messages are simply not found in dmesg nor /var/log/messages.
How can I view all the messages?
I see someone here <https://www.linuxquestions.org/questions/linux-newbie-8/please-how-to-pause-scrolling-messages-at-boot-323772/> suggesting that pressing scroll lock might pause it. However, this is a not very elegant solution at best -- some messages will scroll by too quickly, systems can suddenly churn out a lot of text these days when booting.
This is what I ideally want:
* A dmesg | less type solution, if possible, or some other way of single stepping through the boot process.
* A way to ensure that everything printed on the screen also gets logged.
Is there a straightforward way to achieve either of these?
I know of one solution:
CONFIG\_BOOT\_PRINTK\_DELAY: Delay each boot printk message by N milliseconds
Strangely I don't seem allowed to even select BOOT\_PRINTK\_DELAY in my menuconfig, I can find it when searching for it, but under Kernel hacking -> printk and dmesg options ->, I only have "Show timing information on printks" and "Default message log level". Where is the printk delay option? Do I need to enable something else first to make it visible? What? It would be nice to have this as part of an answer, if anyone knows.
But anyway this requires a kernel recompilation which makes this an ugly and invasive hack for a seemingly trivial task. A proper way of doing this would be very much welcome. | 2017/03/14 | [
"https://superuser.com/questions/1188407",
"https://superuser.com",
"https://superuser.com/users/280044/"
]
| So your console has two types of messages:
* generated by the kernel (via printk);
* generated by userspace (usually your init system).
Kernel messages are always stored in the kmsg buffer, visible via `dmesg`. They're also often copied to your syslog. (This also applies to userspace messages written to `/dev/kmsg`, but those are fairly rare.)
Meanwhile, when userspace writes its fancy boot status text to `/dev/console` or `/dev/tty1`, it's not stored anywhere at all. It just goes to the screen and that's it. So I think pretty much *any* solution โ except for Rowan's serial console suggestion โ will end up being either very distro-specific (due to each init system performing logging differently) or an "invasive hack" that involves strace or kernel hacking or such.
In the best case, your init system will *itself* log all important events to the syslog (/var/log/messages or such). For example:
```
systemd[1]: Starting BIRD routing daemon...
bird[478296]: /etc/bird.conf, line 2: syntax error
systemd[1]: bird.service: Control process exited, code=exited status=1
systemd[1]: Failed to start BIRD routing daemon.
```
(systemd and upstart also log the services' stdout/stderr as well; many other init systems just redirect it to the console or nowhere.) | Grawity's answer is must better described than I would have been able to accomplish for that stage in the boot.
On the physical redirection method, your BIOS has to support it. Server geared boards usually do. The Intel, IBM, and SuperMicro systems typically have a Console Redirection option under the main heading of the BIOS. It cannot be used if your motherboard does not have a physical serial port, e.g. only USB. You may need to attach a physical port to pins on the motherboard if it has it.
Console Redirection can cause wackiness when you get to the point where the operating system is trying to use the serial port for something else. I would say it's primarily used for debugging in a particular case rather than constant use.
To use, you would need to set matching port settings on your receiver com port which could be usb based, then you need to link the two devices with a null modem cable which exchanges the transmit and receive pins between the devices.
The receiving device needs to be fully powered on and watching for the communication during the boot of the source system. The receiving system will get all text based output.
If during boot your OS starts displaying text via a grapical construct rather than as text, the receiving system will get gibberish. |
1,188,407 | Relevant questions are:
[Where Linux places the messages of boot?](https://superuser.com/questions/176165/where-linux-places-the-messages-of-boot)
[Name of log file where boot process is logged](https://superuser.com/questions/132496/name-of-log-file-where-boot-process-is-logged?rq=1)
However, these do not answer this question. This question is concerned with how **all** the boot messages can be viewed.
This is for Gentoo, OpenRC, modern kernels, 4.9.6 if you want to get specific. A generic solution that works for all distributions would however be preferable.
The problem is that sometimes an error or warning will scroll by so quickly that it cannot be seen. Nor is it always possible to simply scroll up for two reasons (even with --noclear in inittab): when switching to the framebuffer scrolling up to the point before the switch too place is no longer possible, and second, that after X starts, switching to console and trying to scroll up doesn't allow scrolling at all until new text is added to the buffer. Sometimes, certain messages are simply not found in dmesg nor /var/log/messages.
How can I view all the messages?
I see someone here <https://www.linuxquestions.org/questions/linux-newbie-8/please-how-to-pause-scrolling-messages-at-boot-323772/> suggesting that pressing scroll lock might pause it. However, this is a not very elegant solution at best -- some messages will scroll by too quickly, systems can suddenly churn out a lot of text these days when booting.
This is what I ideally want:
* A dmesg | less type solution, if possible, or some other way of single stepping through the boot process.
* A way to ensure that everything printed on the screen also gets logged.
Is there a straightforward way to achieve either of these?
I know of one solution:
CONFIG\_BOOT\_PRINTK\_DELAY: Delay each boot printk message by N milliseconds
Strangely I don't seem allowed to even select BOOT\_PRINTK\_DELAY in my menuconfig, I can find it when searching for it, but under Kernel hacking -> printk and dmesg options ->, I only have "Show timing information on printks" and "Default message log level". Where is the printk delay option? Do I need to enable something else first to make it visible? What? It would be nice to have this as part of an answer, if anyone knows.
But anyway this requires a kernel recompilation which makes this an ugly and invasive hack for a seemingly trivial task. A proper way of doing this would be very much welcome. | 2017/03/14 | [
"https://superuser.com/questions/1188407",
"https://superuser.com",
"https://superuser.com/users/280044/"
]
| So your console has two types of messages:
* generated by the kernel (via printk);
* generated by userspace (usually your init system).
Kernel messages are always stored in the kmsg buffer, visible via `dmesg`. They're also often copied to your syslog. (This also applies to userspace messages written to `/dev/kmsg`, but those are fairly rare.)
Meanwhile, when userspace writes its fancy boot status text to `/dev/console` or `/dev/tty1`, it's not stored anywhere at all. It just goes to the screen and that's it. So I think pretty much *any* solution โ except for Rowan's serial console suggestion โ will end up being either very distro-specific (due to each init system performing logging differently) or an "invasive hack" that involves strace or kernel hacking or such.
In the best case, your init system will *itself* log all important events to the syslog (/var/log/messages or such). For example:
```
systemd[1]: Starting BIRD routing daemon...
bird[478296]: /etc/bird.conf, line 2: syntax error
systemd[1]: bird.service: Control process exited, code=exited status=1
systemd[1]: Failed to start BIRD routing daemon.
```
(systemd and upstart also log the services' stdout/stderr as well; many other init systems just redirect it to the console or nowhere.) | One suggestion is to have another laptop film the boot screen with high resolution and frame rates then slow play the resulting (**MOV - MP4 - AVI**) - maybe not the best solution but simply to deploy and its for debugging anyway right ? Just an Idea ... |
1,188,407 | Relevant questions are:
[Where Linux places the messages of boot?](https://superuser.com/questions/176165/where-linux-places-the-messages-of-boot)
[Name of log file where boot process is logged](https://superuser.com/questions/132496/name-of-log-file-where-boot-process-is-logged?rq=1)
However, these do not answer this question. This question is concerned with how **all** the boot messages can be viewed.
This is for Gentoo, OpenRC, modern kernels, 4.9.6 if you want to get specific. A generic solution that works for all distributions would however be preferable.
The problem is that sometimes an error or warning will scroll by so quickly that it cannot be seen. Nor is it always possible to simply scroll up for two reasons (even with --noclear in inittab): when switching to the framebuffer scrolling up to the point before the switch too place is no longer possible, and second, that after X starts, switching to console and trying to scroll up doesn't allow scrolling at all until new text is added to the buffer. Sometimes, certain messages are simply not found in dmesg nor /var/log/messages.
How can I view all the messages?
I see someone here <https://www.linuxquestions.org/questions/linux-newbie-8/please-how-to-pause-scrolling-messages-at-boot-323772/> suggesting that pressing scroll lock might pause it. However, this is a not very elegant solution at best -- some messages will scroll by too quickly, systems can suddenly churn out a lot of text these days when booting.
This is what I ideally want:
* A dmesg | less type solution, if possible, or some other way of single stepping through the boot process.
* A way to ensure that everything printed on the screen also gets logged.
Is there a straightforward way to achieve either of these?
I know of one solution:
CONFIG\_BOOT\_PRINTK\_DELAY: Delay each boot printk message by N milliseconds
Strangely I don't seem allowed to even select BOOT\_PRINTK\_DELAY in my menuconfig, I can find it when searching for it, but under Kernel hacking -> printk and dmesg options ->, I only have "Show timing information on printks" and "Default message log level". Where is the printk delay option? Do I need to enable something else first to make it visible? What? It would be nice to have this as part of an answer, if anyone knows.
But anyway this requires a kernel recompilation which makes this an ugly and invasive hack for a seemingly trivial task. A proper way of doing this would be very much welcome. | 2017/03/14 | [
"https://superuser.com/questions/1188407",
"https://superuser.com",
"https://superuser.com/users/280044/"
]
| So your console has two types of messages:
* generated by the kernel (via printk);
* generated by userspace (usually your init system).
Kernel messages are always stored in the kmsg buffer, visible via `dmesg`. They're also often copied to your syslog. (This also applies to userspace messages written to `/dev/kmsg`, but those are fairly rare.)
Meanwhile, when userspace writes its fancy boot status text to `/dev/console` or `/dev/tty1`, it's not stored anywhere at all. It just goes to the screen and that's it. So I think pretty much *any* solution โ except for Rowan's serial console suggestion โ will end up being either very distro-specific (due to each init system performing logging differently) or an "invasive hack" that involves strace or kernel hacking or such.
In the best case, your init system will *itself* log all important events to the syslog (/var/log/messages or such). For example:
```
systemd[1]: Starting BIRD routing daemon...
bird[478296]: /etc/bird.conf, line 2: syntax error
systemd[1]: bird.service: Control process exited, code=exited status=1
systemd[1]: Failed to start BIRD routing daemon.
```
(systemd and upstart also log the services' stdout/stderr as well; many other init systems just redirect it to the console or nowhere.) | OpenRC Logging
"OpenRC doesn't log anything by default. To log OpenRC's output during boot, uncomment and set the `rc_logger` option in `/etc/rc.conf`. The log will be saved at `/var/log/rc.log` by default."
```
rc_logger="Yes"
```
then
```
cat /var/log/rc.log # After reboot
```
Gentoo Wiki
OpenRC
Chapter 3 Configuration 3.2 Logging
<https://wiki.gentoo.org/wiki/OpenRC> |
1,188,407 | Relevant questions are:
[Where Linux places the messages of boot?](https://superuser.com/questions/176165/where-linux-places-the-messages-of-boot)
[Name of log file where boot process is logged](https://superuser.com/questions/132496/name-of-log-file-where-boot-process-is-logged?rq=1)
However, these do not answer this question. This question is concerned with how **all** the boot messages can be viewed.
This is for Gentoo, OpenRC, modern kernels, 4.9.6 if you want to get specific. A generic solution that works for all distributions would however be preferable.
The problem is that sometimes an error or warning will scroll by so quickly that it cannot be seen. Nor is it always possible to simply scroll up for two reasons (even with --noclear in inittab): when switching to the framebuffer scrolling up to the point before the switch too place is no longer possible, and second, that after X starts, switching to console and trying to scroll up doesn't allow scrolling at all until new text is added to the buffer. Sometimes, certain messages are simply not found in dmesg nor /var/log/messages.
How can I view all the messages?
I see someone here <https://www.linuxquestions.org/questions/linux-newbie-8/please-how-to-pause-scrolling-messages-at-boot-323772/> suggesting that pressing scroll lock might pause it. However, this is a not very elegant solution at best -- some messages will scroll by too quickly, systems can suddenly churn out a lot of text these days when booting.
This is what I ideally want:
* A dmesg | less type solution, if possible, or some other way of single stepping through the boot process.
* A way to ensure that everything printed on the screen also gets logged.
Is there a straightforward way to achieve either of these?
I know of one solution:
CONFIG\_BOOT\_PRINTK\_DELAY: Delay each boot printk message by N milliseconds
Strangely I don't seem allowed to even select BOOT\_PRINTK\_DELAY in my menuconfig, I can find it when searching for it, but under Kernel hacking -> printk and dmesg options ->, I only have "Show timing information on printks" and "Default message log level". Where is the printk delay option? Do I need to enable something else first to make it visible? What? It would be nice to have this as part of an answer, if anyone knows.
But anyway this requires a kernel recompilation which makes this an ugly and invasive hack for a seemingly trivial task. A proper way of doing this would be very much welcome. | 2017/03/14 | [
"https://superuser.com/questions/1188407",
"https://superuser.com",
"https://superuser.com/users/280044/"
]
| One suggestion is to have another laptop film the boot screen with high resolution and frame rates then slow play the resulting (**MOV - MP4 - AVI**) - maybe not the best solution but simply to deploy and its for debugging anyway right ? Just an Idea ... | Grawity's answer is must better described than I would have been able to accomplish for that stage in the boot.
On the physical redirection method, your BIOS has to support it. Server geared boards usually do. The Intel, IBM, and SuperMicro systems typically have a Console Redirection option under the main heading of the BIOS. It cannot be used if your motherboard does not have a physical serial port, e.g. only USB. You may need to attach a physical port to pins on the motherboard if it has it.
Console Redirection can cause wackiness when you get to the point where the operating system is trying to use the serial port for something else. I would say it's primarily used for debugging in a particular case rather than constant use.
To use, you would need to set matching port settings on your receiver com port which could be usb based, then you need to link the two devices with a null modem cable which exchanges the transmit and receive pins between the devices.
The receiving device needs to be fully powered on and watching for the communication during the boot of the source system. The receiving system will get all text based output.
If during boot your OS starts displaying text via a grapical construct rather than as text, the receiving system will get gibberish. |
1,188,407 | Relevant questions are:
[Where Linux places the messages of boot?](https://superuser.com/questions/176165/where-linux-places-the-messages-of-boot)
[Name of log file where boot process is logged](https://superuser.com/questions/132496/name-of-log-file-where-boot-process-is-logged?rq=1)
However, these do not answer this question. This question is concerned with how **all** the boot messages can be viewed.
This is for Gentoo, OpenRC, modern kernels, 4.9.6 if you want to get specific. A generic solution that works for all distributions would however be preferable.
The problem is that sometimes an error or warning will scroll by so quickly that it cannot be seen. Nor is it always possible to simply scroll up for two reasons (even with --noclear in inittab): when switching to the framebuffer scrolling up to the point before the switch too place is no longer possible, and second, that after X starts, switching to console and trying to scroll up doesn't allow scrolling at all until new text is added to the buffer. Sometimes, certain messages are simply not found in dmesg nor /var/log/messages.
How can I view all the messages?
I see someone here <https://www.linuxquestions.org/questions/linux-newbie-8/please-how-to-pause-scrolling-messages-at-boot-323772/> suggesting that pressing scroll lock might pause it. However, this is a not very elegant solution at best -- some messages will scroll by too quickly, systems can suddenly churn out a lot of text these days when booting.
This is what I ideally want:
* A dmesg | less type solution, if possible, or some other way of single stepping through the boot process.
* A way to ensure that everything printed on the screen also gets logged.
Is there a straightforward way to achieve either of these?
I know of one solution:
CONFIG\_BOOT\_PRINTK\_DELAY: Delay each boot printk message by N milliseconds
Strangely I don't seem allowed to even select BOOT\_PRINTK\_DELAY in my menuconfig, I can find it when searching for it, but under Kernel hacking -> printk and dmesg options ->, I only have "Show timing information on printks" and "Default message log level". Where is the printk delay option? Do I need to enable something else first to make it visible? What? It would be nice to have this as part of an answer, if anyone knows.
But anyway this requires a kernel recompilation which makes this an ugly and invasive hack for a seemingly trivial task. A proper way of doing this would be very much welcome. | 2017/03/14 | [
"https://superuser.com/questions/1188407",
"https://superuser.com",
"https://superuser.com/users/280044/"
]
| Grawity's answer is must better described than I would have been able to accomplish for that stage in the boot.
On the physical redirection method, your BIOS has to support it. Server geared boards usually do. The Intel, IBM, and SuperMicro systems typically have a Console Redirection option under the main heading of the BIOS. It cannot be used if your motherboard does not have a physical serial port, e.g. only USB. You may need to attach a physical port to pins on the motherboard if it has it.
Console Redirection can cause wackiness when you get to the point where the operating system is trying to use the serial port for something else. I would say it's primarily used for debugging in a particular case rather than constant use.
To use, you would need to set matching port settings on your receiver com port which could be usb based, then you need to link the two devices with a null modem cable which exchanges the transmit and receive pins between the devices.
The receiving device needs to be fully powered on and watching for the communication during the boot of the source system. The receiving system will get all text based output.
If during boot your OS starts displaying text via a grapical construct rather than as text, the receiving system will get gibberish. | OpenRC Logging
"OpenRC doesn't log anything by default. To log OpenRC's output during boot, uncomment and set the `rc_logger` option in `/etc/rc.conf`. The log will be saved at `/var/log/rc.log` by default."
```
rc_logger="Yes"
```
then
```
cat /var/log/rc.log # After reboot
```
Gentoo Wiki
OpenRC
Chapter 3 Configuration 3.2 Logging
<https://wiki.gentoo.org/wiki/OpenRC> |
1,188,407 | Relevant questions are:
[Where Linux places the messages of boot?](https://superuser.com/questions/176165/where-linux-places-the-messages-of-boot)
[Name of log file where boot process is logged](https://superuser.com/questions/132496/name-of-log-file-where-boot-process-is-logged?rq=1)
However, these do not answer this question. This question is concerned with how **all** the boot messages can be viewed.
This is for Gentoo, OpenRC, modern kernels, 4.9.6 if you want to get specific. A generic solution that works for all distributions would however be preferable.
The problem is that sometimes an error or warning will scroll by so quickly that it cannot be seen. Nor is it always possible to simply scroll up for two reasons (even with --noclear in inittab): when switching to the framebuffer scrolling up to the point before the switch too place is no longer possible, and second, that after X starts, switching to console and trying to scroll up doesn't allow scrolling at all until new text is added to the buffer. Sometimes, certain messages are simply not found in dmesg nor /var/log/messages.
How can I view all the messages?
I see someone here <https://www.linuxquestions.org/questions/linux-newbie-8/please-how-to-pause-scrolling-messages-at-boot-323772/> suggesting that pressing scroll lock might pause it. However, this is a not very elegant solution at best -- some messages will scroll by too quickly, systems can suddenly churn out a lot of text these days when booting.
This is what I ideally want:
* A dmesg | less type solution, if possible, or some other way of single stepping through the boot process.
* A way to ensure that everything printed on the screen also gets logged.
Is there a straightforward way to achieve either of these?
I know of one solution:
CONFIG\_BOOT\_PRINTK\_DELAY: Delay each boot printk message by N milliseconds
Strangely I don't seem allowed to even select BOOT\_PRINTK\_DELAY in my menuconfig, I can find it when searching for it, but under Kernel hacking -> printk and dmesg options ->, I only have "Show timing information on printks" and "Default message log level". Where is the printk delay option? Do I need to enable something else first to make it visible? What? It would be nice to have this as part of an answer, if anyone knows.
But anyway this requires a kernel recompilation which makes this an ugly and invasive hack for a seemingly trivial task. A proper way of doing this would be very much welcome. | 2017/03/14 | [
"https://superuser.com/questions/1188407",
"https://superuser.com",
"https://superuser.com/users/280044/"
]
| One suggestion is to have another laptop film the boot screen with high resolution and frame rates then slow play the resulting (**MOV - MP4 - AVI**) - maybe not the best solution but simply to deploy and its for debugging anyway right ? Just an Idea ... | OpenRC Logging
"OpenRC doesn't log anything by default. To log OpenRC's output during boot, uncomment and set the `rc_logger` option in `/etc/rc.conf`. The log will be saved at `/var/log/rc.log` by default."
```
rc_logger="Yes"
```
then
```
cat /var/log/rc.log # After reboot
```
Gentoo Wiki
OpenRC
Chapter 3 Configuration 3.2 Logging
<https://wiki.gentoo.org/wiki/OpenRC> |
63,574,728 | I've an AWS API gateway in front of a REST API service. I would like to remove one/some HTTP headers when I forward the request to the origin.
I know how to do this using a lambda but I'm just wondering is there is something built in. | 2020/08/25 | [
"https://Stackoverflow.com/questions/63574728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803148/"
]
| I think the simpler approach is boolean logic:
```
SELECT `id`, `title`, `body`, `created_on`
FROM `fcm_messages`
WHERE
(`city` = :city AND `street` = :street AND `building` = :building)
OR (`city` = :city AND `street` = :street AND `building` = '-')
OR (`city` = :city AND `street` = '-' AND `building` = '-')
OR (`city` = '-' AND `street` = '-' AND `building` = '-')
```
Note that this uses query parameters to pass the variables to the query rather than concatenating them into the query string: this is both safer and more efficient. | You can build a query simply by putting each condition into brackets and combine them by a logical OR for each one.
```
$query = "SELECT `id`, `title`, `body`, `created_on` FROM `fcm_messages` WHERE ";
$conditions[] = "(`city`='$city' AND `street`='$street' AND `building`='$building')";
$conditions[] = "(`city`='$city' AND `street`='$street' AND `building`='-')";
$conditions[] = "(`city`='$city' AND `street`='-' AND `building`='-')";
$conditions[] = "(`city`='-' AND `street`='-' AND `building`='-')";
$query .= join(' OR ', $conditions);
``` |
63,574,728 | I've an AWS API gateway in front of a REST API service. I would like to remove one/some HTTP headers when I forward the request to the origin.
I know how to do this using a lambda but I'm just wondering is there is something built in. | 2020/08/25 | [
"https://Stackoverflow.com/questions/63574728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803148/"
]
| I think the simpler approach is boolean logic:
```
SELECT `id`, `title`, `body`, `created_on`
FROM `fcm_messages`
WHERE
(`city` = :city AND `street` = :street AND `building` = :building)
OR (`city` = :city AND `street` = :street AND `building` = '-')
OR (`city` = :city AND `street` = '-' AND `building` = '-')
OR (`city` = '-' AND `street` = '-' AND `building` = '-')
```
Note that this uses query parameters to pass the variables to the query rather than concatenating them into the query string: this is both safer and more efficient. | In MySQL, you can take advantage of tuples:
```
SELECT `id`, `title`, `body`, `created_on`
FROM `fcm_messages`
WHERE (city, street, building) in ( (:city, :street, :building), (:city, :street, '-'), (:city, '-', '-'), ('-', '-', '-') )
```
Note: In many cases, the "generic" value would be stored as `NULL`. That would not work with `IN`, but with `'-'` it does. |
2,448,804 | Sophomore's dream is the identity that states
\begin{equation}
\int\_0^1 x^x dx = \sum\limits\_{n=1}^\infty (-1)^{n+1}n^{-n}
\end{equation}
The proof is found using the series expansion for $e^{-x\log(x)}$ and switching the integral and the sum. But I have a problem : I don't understand why I can replace $x^x$ in the integral by the series expansion of $e^{-x\log(x)}$ because the series is not defined in $x=0$.
In understand that in the integral, we can extend the function $x^x$ in $x=0$ because the limit is finite but then the extended function doesn't admit a series expansion for $x=0$.
What is the easiest way to solve this issue ?
Thank you ! | 2017/09/28 | [
"https://math.stackexchange.com/questions/2448804",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/397986/"
]
| Let $$I(k,n)=\int\limits\_0^1x^k\ln^nxdx.$$
Thus, $$I(k,n)=\int\limits\_0^1x^k\ln^nxdx=\frac{x^{k+1}\ln^nx}{k+1}\big|\_0^1-\frac{n}{k+1}\int\limits\_0^1x^k\ln^{n-1}xdx=-\frac{nI(k,n-1)}{k+1}.$$
Thus,
$$I(k,n)\prod\_{i=2}^{n}I(k,i-1)=I(k,n)\prod\_{i=1}^{n-1}I(k,i)=\prod\_{i=1}^nI(k,i)=$$
$$=\prod\_{i=1}^{n}\left(-\frac{i}{k+1}I(k,i-1)\right)=\frac{(-1)^nn!}{(k+1)^n}\prod\_{i=2}^{n}I(k,i-1)I(k,0)=$$
$$=\frac{(-1)^nn!}{(k+1)^n}\prod\_{i=2}^{n}I(k,i-1)\int\limits\_0^1x^kdx=\frac{(-1)^nn!}{(k+1)^{n+1}}\prod\_{i=2}^{n}I(k,i-1),$$
which gives
$$I(k,n)=\frac{(-1)^nn!}{(k+1)^{n+1}},$$
$$I(k,k)=\frac{(-1)^kk!}{(k+1)^{k+1}}$$ and
$$\int\limits\_{0}^1x^xdx=\int\limits\_0^1e^{x\ln{x}}dx=\sum\_{k=0}^{+\infty}\int\limits\_0^1\frac{x^k\ln^kx}{k!}dx=\sum\_{k=0}^{+\infty}\frac{1}{k!}\int\limits\_0^1x^k\ln^kxdx=$$
$$=\sum\_{k=0}^{+\infty}\left(\frac{1}{k!}\cdot\frac{(-1)^kk!}{(k+1)^{k+1}}\right)=\sum\_{k=0}^{+\infty}\frac{(-1)^k}{(k+1)^{k+1}}=\sum\_{n=1}^{+\infty}\frac{(-1)^{n+1}}{n^n}.$$
Done! | Define
$$ f(x) = \begin{cases} x^x & 0 < x \leq 1, \\
1 & x = 0. \end{cases},
g(x) = \begin{cases} x \ln x & 0 < x \leq 1, \\
0 & x = 0. \end{cases} $$
Both $f,g$ are continuous on $[0,1]$ and we have $f(x) = e^{g(x)}$ for all $x \in [0,1]$. The image of $g$ is a compact subset of $\mathbb{R}$ so it lies in some interval $[-N,N]$. The power series of $e^x$ converges uniformly on any closed interval so if we plug $g$ into the power series of $e^x$ (obtaining a function series, not a power series!), we still have an identity and uniform convergence. Namely,
$$ f(x) = e^{g(x)} = \sum\_{x = 0}^{\infty} \frac{g(x)^n}{n!} $$
where the sum on the right hand side converges uniformly on $[0,1]$ to $e^{g(x)} = f(x)$. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.