kashif/stack-llama-2
Text Generation
•
Updated
•
1.5k
•
15
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
6,073,935 | I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory.
Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`.
Google came to the rescue and gave me 3 viable solutions:
* by copying the dll file into my JRE's bin directory
* by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`)
* load the dll in the program with `System.load()` (I couldn't get this one to work, actually)
My question is: Is there an elegant solution to this problem, that I missed?
It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?) | 2011/05/20 | [
"https://Stackoverflow.com/questions/6073935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639422/"
] | >
> Making my Java program easily distributable
>
>
>
If you mean 'easy for the end user' look to [Java Web Start](https://stackoverflow.com/tags/java-web-start/info).
---
A passer-by asks:
>
> Can you package the dll dependencies with Web Start?
>
>
>
Yes, but much, much better. You can package the natives for each platform in separate Jars, and supply them only to the platform that uses that native, even so far as partitioning the download between 32 & 64 bit versions of the natives.
JWS puts the natives on the run-time class-path of the application, ready for loading in code.
This all happens automatically for the end user, they click a link, approve the trust dialog(s) when asked, and the application installs - possibly with desktop integration, and appears on screen like magic.
JWS apps. that use natives need to be distributed as `all-permissions` security level, because the JVM cannot guarantee the actions of anything that 'goes native'. | If you put the dlls in the same directory than you Jar, does it work?
If yes, you could consider distributing it like this. |
6,073,935 | I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory.
Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`.
Google came to the rescue and gave me 3 viable solutions:
* by copying the dll file into my JRE's bin directory
* by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`)
* load the dll in the program with `System.load()` (I couldn't get this one to work, actually)
My question is: Is there an elegant solution to this problem, that I missed?
It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?) | 2011/05/20 | [
"https://Stackoverflow.com/questions/6073935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639422/"
] | *Edit - After re-reading your question, your issue sounds different. However I'm able to get my running like so, by just dropping all dll files in the same directory as the .bat file starting the java process:*
*java -classpath ./YourJar.jar;./lib/j3dcore.jar;./lib/vecmath.jar;./lib/j3dutils.jar package.MainClass*
*And that works on multiple user's PCs, so I know simply dropping it in the working directory works.*
I believe it depends on the version of Java being used - 64 bit or 32 bit. The correct dll file (of the same name) needs to be in the working directory.
I think I was getting a similar problem when the wrong dll was being used, and it's not OS-dependent (if your 64 bit OS has 32-bit Java installed, you'd need the 32 bit j3dcore-ogl.dll file).
So the question is, which version of Java are you using *(when running outside of your IDE)*, and which version of the dll are you putting (if any) in the working directory? I don't need any dll files in my path settings to get this working on other's PCs, and did not use System.load(), and did NOT copy files into my user's JRE/bin directory - so I know this is possible without the 3 options you mention. | If you put the dlls in the same directory than you Jar, does it work?
If yes, you could consider distributing it like this. |
6,073,935 | I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory.
Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`.
Google came to the rescue and gave me 3 viable solutions:
* by copying the dll file into my JRE's bin directory
* by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`)
* load the dll in the program with `System.load()` (I couldn't get this one to work, actually)
My question is: Is there an elegant solution to this problem, that I missed?
It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?) | 2011/05/20 | [
"https://Stackoverflow.com/questions/6073935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639422/"
] | >
> Making my Java program easily distributable
>
>
>
If you mean 'easy for the end user' look to [Java Web Start](https://stackoverflow.com/tags/java-web-start/info).
---
A passer-by asks:
>
> Can you package the dll dependencies with Web Start?
>
>
>
Yes, but much, much better. You can package the natives for each platform in separate Jars, and supply them only to the platform that uses that native, even so far as partitioning the download between 32 & 64 bit versions of the natives.
JWS puts the natives on the run-time class-path of the application, ready for loading in code.
This all happens automatically for the end user, they click a link, approve the trust dialog(s) when asked, and the application installs - possibly with desktop integration, and appears on screen like magic.
JWS apps. that use natives need to be distributed as `all-permissions` security level, because the JVM cannot guarantee the actions of anything that 'goes native'. | I guess DLL are searched in all folders in %PATH% on windows. (LD\_LIBRARY\_PATH for UNIX flavors)
Could you try by adding the path to dll to %path% variable?
It appears that you are trying package a product with many jars as dependencies. You may benefit from [One-Jar](http://one-jar.sourceforge.net/index.php?page=details&file=native). It claims to have native dll support. |
6,073,935 | I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory.
Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`.
Google came to the rescue and gave me 3 viable solutions:
* by copying the dll file into my JRE's bin directory
* by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`)
* load the dll in the program with `System.load()` (I couldn't get this one to work, actually)
My question is: Is there an elegant solution to this problem, that I missed?
It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?) | 2011/05/20 | [
"https://Stackoverflow.com/questions/6073935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639422/"
] | *Edit - After re-reading your question, your issue sounds different. However I'm able to get my running like so, by just dropping all dll files in the same directory as the .bat file starting the java process:*
*java -classpath ./YourJar.jar;./lib/j3dcore.jar;./lib/vecmath.jar;./lib/j3dutils.jar package.MainClass*
*And that works on multiple user's PCs, so I know simply dropping it in the working directory works.*
I believe it depends on the version of Java being used - 64 bit or 32 bit. The correct dll file (of the same name) needs to be in the working directory.
I think I was getting a similar problem when the wrong dll was being used, and it's not OS-dependent (if your 64 bit OS has 32-bit Java installed, you'd need the 32 bit j3dcore-ogl.dll file).
So the question is, which version of Java are you using *(when running outside of your IDE)*, and which version of the dll are you putting (if any) in the working directory? I don't need any dll files in my path settings to get this working on other's PCs, and did not use System.load(), and did NOT copy files into my user's JRE/bin directory - so I know this is possible without the 3 options you mention. | I guess DLL are searched in all folders in %PATH% on windows. (LD\_LIBRARY\_PATH for UNIX flavors)
Could you try by adding the path to dll to %path% variable?
It appears that you are trying package a product with many jars as dependencies. You may benefit from [One-Jar](http://one-jar.sourceforge.net/index.php?page=details&file=native). It claims to have native dll support. |
44,608,964 | ```
pt=new Date(2019,11,12,8,2,3)
console.log(pt.getFullYear()," ",pt.getMonth());
```
gives result `2019 " " 11`
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
gives the result as `2019 11`
What is the difference between using, and + in this example? | 2017/06/17 | [
"https://Stackoverflow.com/questions/44608964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3967709/"
] | The first of these gives three separate arguments to console.log, while the second appends the three together, then passes that as a single argument to console.log. | With the (,) you're with the console.log you're requesting to show a separate group of items as string, making a kind of array. When you put the (+) symbol you are adding the strings, and in this case the " " is just adding a space between the first and the second string. It is called concatenation. |
44,608,964 | ```
pt=new Date(2019,11,12,8,2,3)
console.log(pt.getFullYear()," ",pt.getMonth());
```
gives result `2019 " " 11`
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
gives the result as `2019 11`
What is the difference between using, and + in this example? | 2017/06/17 | [
"https://Stackoverflow.com/questions/44608964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3967709/"
] | The first of these gives three separate arguments to console.log, while the second appends the three together, then passes that as a single argument to console.log. | console.log is part of the Console API and is accesible in various browsers. You can find its full documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log).
It states that console log has the following parameters:
```
obj1 ... objN
```
>
> A list of JavaScript objects to output. The string representations of
> each of these objects are appended together in the order listed and
> output.
>
>
>
So, when you concatenate the parameters you pass only one object to the function and when you pass multiple parameters `console.log` will do the concatenation for you. |
44,608,964 | ```
pt=new Date(2019,11,12,8,2,3)
console.log(pt.getFullYear()," ",pt.getMonth());
```
gives result `2019 " " 11`
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
gives the result as `2019 11`
What is the difference between using, and + in this example? | 2017/06/17 | [
"https://Stackoverflow.com/questions/44608964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3967709/"
] | ```
console.log(pt.getFullYear()," ",pt.getMonth());
```
The above example passes three separate arguments to console.log. What it outputs depends on how `console.log` is implemented. It has changed over time and is little bit different between browsers. When invoked with arguments like in the example, it has access to the variables and can display them with some magic depending on type, for example if they are arrays or objects. In your example it is displayed as:
```
2019 " " 11
```
where the numbers are in blue text, indicating that it was a variable of type number, and the empty string is shown in red, indicating that is was a string.
Compare this to the following example, where it all is converted to a string before being passed to `console.log` in one argument:
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
where it is displayed as
```
2017 5
```
with black text, indicating that it was passed as a string in the first parameter.
The first parameter to `console.log` can be used as a format string, like `printf` in c and other languages. For example
```
console.log( "%d %d", pt.getFullYear(), pt.getMonth() );
```
where %d is a place holder for a number. The output is in black text and gives the exact same output as your second example.
```
console.log("%d %d", pt.getFullYear(),pt.getMonth(), pt.getDate());
```
In the example above, the year and month will be shown in black text, but the date will be in blue. This is because the format string only have two placeholders, but there are three arguments. `console.log` show the extra arguments, using the magic.
Documentation:
* [Standard](https://console.spec.whatwg.org/)
* [Google Chrome](https://developers.google.com/web/tools/chrome-devtools/console/console-reference).
* [Mozilla Firefox](https://developer.mozilla.org/en-US/docs/Web/API/Console)
* [Microsoft Edge](https://msdn.microsoft.com/library/hh772169.aspx)
* [Apple Safari](https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)
* [Opera](http://www.opera.com/dragonfly/documentation/console/) | With the (,) you're with the console.log you're requesting to show a separate group of items as string, making a kind of array. When you put the (+) symbol you are adding the strings, and in this case the " " is just adding a space between the first and the second string. It is called concatenation. |
44,608,964 | ```
pt=new Date(2019,11,12,8,2,3)
console.log(pt.getFullYear()," ",pt.getMonth());
```
gives result `2019 " " 11`
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
gives the result as `2019 11`
What is the difference between using, and + in this example? | 2017/06/17 | [
"https://Stackoverflow.com/questions/44608964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3967709/"
] | ```
console.log(pt.getFullYear()," ",pt.getMonth());
```
The above example passes three separate arguments to console.log. What it outputs depends on how `console.log` is implemented. It has changed over time and is little bit different between browsers. When invoked with arguments like in the example, it has access to the variables and can display them with some magic depending on type, for example if they are arrays or objects. In your example it is displayed as:
```
2019 " " 11
```
where the numbers are in blue text, indicating that it was a variable of type number, and the empty string is shown in red, indicating that is was a string.
Compare this to the following example, where it all is converted to a string before being passed to `console.log` in one argument:
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
where it is displayed as
```
2017 5
```
with black text, indicating that it was passed as a string in the first parameter.
The first parameter to `console.log` can be used as a format string, like `printf` in c and other languages. For example
```
console.log( "%d %d", pt.getFullYear(), pt.getMonth() );
```
where %d is a place holder for a number. The output is in black text and gives the exact same output as your second example.
```
console.log("%d %d", pt.getFullYear(),pt.getMonth(), pt.getDate());
```
In the example above, the year and month will be shown in black text, but the date will be in blue. This is because the format string only have two placeholders, but there are three arguments. `console.log` show the extra arguments, using the magic.
Documentation:
* [Standard](https://console.spec.whatwg.org/)
* [Google Chrome](https://developers.google.com/web/tools/chrome-devtools/console/console-reference).
* [Mozilla Firefox](https://developer.mozilla.org/en-US/docs/Web/API/Console)
* [Microsoft Edge](https://msdn.microsoft.com/library/hh772169.aspx)
* [Apple Safari](https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)
* [Opera](http://www.opera.com/dragonfly/documentation/console/) | console.log is part of the Console API and is accesible in various browsers. You can find its full documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log).
It states that console log has the following parameters:
```
obj1 ... objN
```
>
> A list of JavaScript objects to output. The string representations of
> each of these objects are appended together in the order listed and
> output.
>
>
>
So, when you concatenate the parameters you pass only one object to the function and when you pass multiple parameters `console.log` will do the concatenation for you. |
343,937 | I need to take some online tests for school.
This website tells me I need Flash Player 11.3.0 or higher. As far as I can see that is not yet avaible for Linux.
I use Ubuntu 12.04 LTS and Chromium. Is there a way I can work around it?
Greetz. Rob. | 2013/09/10 | [
"https://askubuntu.com/questions/343937",
"https://askubuntu.com",
"https://askubuntu.com/users/191781/"
] | The best way to get Flash Player 11.2+ is to use Google Chrome in Ubuntu. There is no other way to get it, because a higher version has not been released for Ubuntu.
[Download Google Chrome From Here](https://www.google.com/intl/en/chrome/browser/)
Select your OS version x86 or x64 and download it to any path.
Then you can open it with the Ubuntu Software Center to install.
You can also install by executing command:
```
sudo dpkg -i <googlechromefile.deb>
```
Hope it helps you somewhat!! | sudo apt-get install wine
Download Firefox for Windows
Visit Youtube and install the addon that pops up. You now have the latest version of Flash! |
40,155,466 | we got homework to make convertor of weights where the fields are updated while typing the number (no need to click "calculate" or anything). one of the students offered the code below.
the code works: when putting a number in field 1, field 2 changes while typing.
what i dont understand is how does that work?
in the `onKey` method, no value is given to `View` `int` and `keyEvent`
so how does the listener "knows" on which view to and what keys to listen to or what event to activate ?
```
public class Screen extends Activity {
double weight = 2.20462;
EditText kgEdit, lbsEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kgEdit = (EditText) findViewById(R.id.kgEdit);
lbsEdit = (EditText) findViewById(R.id.lbsEdit);
kgEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
}
});
lbsEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String lbs = lbsEdit.getText().toString();
if (lbs.isEmpty()) {
kgEdit.setText("");
} else {
double num = Double.valueOf(lbsEdit.getText().toString()) / weight;
kgEdit.setText(num + "");
}
return false;
}
});
}
```
} | 2016/10/20 | [
"https://Stackoverflow.com/questions/40155466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6932394/"
] | I'm going to focus on just 1 of the text fields to answer this. Look at this first line:
`kgEdit = (EditText) findViewById(R.id.kgEdit);`
All this does is get a reference to the `EditText` for entering kg. Now that there is a reference, we can call methods on that object.
Next, we have this:
```
kgEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// ...
}
}
```
What the above does is the following. Take our reference to the `EditText` for kilograms that we retrieved in our first line. The method `setOnKeyListener` does the following (from [here](https://developer.android.com/reference/android/view/View.html#setOnKeyListener(android.view.View.OnKeyListener))): "Register a callback to be invoked when a hardware key is pressed in this view."
What this means is that you've now told the view that you want to be informed every time the user presses a key while this EditText has the focus. You make this call to the Android API and in the background Android handles everything you're asking. It will call the method with the `View view`, `int keyCode` and `KeyEvent event`. You give it a method that then handles those inputs. So nowhere in your code do you need to call the method, Android calls it in the background where you'll never have to see or worry about it.
Now, because you called the method on `kgEdit`, that means the following code will ONLY be called when `kgEdit` is focused and keys are typed, so there's no confusion with the other `EditText`. It gets its own method call later, just below. Here's the rest of the code inside the `setOnKeyListener`:
```
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
```
What this does is get the current text in `kgEdit`, which has already been updated with the key the user pressed. And it just checks if the text is empty, and if so remove the text in `lbsEdit`. If it's not empty, then get the text, convert it to a number, convert the number from kg to lbs and update `lbsEdit` | You have to use addTextChangedListener like this-
```
EditText editText = (EditText) findViewById(R.id.editText1);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//do here your calculation
String data = s.toString();
}
});
``` |
19,074,447 | I have to go into a table to retrieve a parameter, then go back into the same table to retrieve data based on the parameter.
```
<cfquery name = "selnm" datasource = "Moxart">
select SelName from AuxXref
where Fieldname = <cfqueryparam value = "#orig#">
</cfquery>
<cfset selname = selnm.SelName>
<cfquery name = "fld" datasource = "Moxart">
select Fieldname, DBname from AuxXref
where SelName = <cfqueryparam value = "#selname#">
</cfquery>
```
Can this be done in a single query? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19074447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497281/"
] | You can do this in one query like so:
```
<cfquery name = "fld" datasource = "Moxart">
select Fieldname, DBname, SelName from AuxXref
where SelName = <cfqueryparam value = "#orig#">
AND FieldName = <cfqueryparam value = "#orig#">
</cfquery>
``` | Something like this might satisfy your requirements.
```
select fieldname, DBname
from AuxXref
where selname in
(select distinct selname
from auxXref
where fieldname = <cfqueryparam value = "#orig#">
)
and fieldname <> <cfqueryparam value = "#orig#">
```
If the subquery returns more than one row, and you only want one, then you'll have to specify which one you want. |
115,794 | **Rules**
1. Place some pentominoes into an 8 x 8 grid. They do not touch each other. They can touch only diagonally (with corner).
2. Pentominoes cannot repeat in the grid. Rotations and reflections of a pentomino are considered the same shape.
3. Grid is 8 x 8. | 2022/04/17 | [
"https://puzzling.stackexchange.com/questions/115794",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/79520/"
] | With integer programming, I managed to place
>
> 8 pieces, proved to be optimal
>
>
>
like this.
>
> $$\begin{array}{cccccccc} 3&3&3&3& &5&5&5\\ 3& & & & &5& &5\\ &4&4&4&4& &A&\\ 6& & &4& &A&A&A\\ 6&6&6& &8& &A&\\ & &6& &8&8& &B\\ 2&2& &8&8& &B&B\\2&2&2& & &B&B&\\ \end{array}$$
>
>
>
Here is my formulation. I happened to solve a similar model to solve a puzzle called One puzzle a day. Let $B$ be the set of cells in the 8x8 board, and $P$ be the set of all kinds of pieces (rotating and flipping count difference here), so I have $|P|=63$, then we need to choose a subset of $P$ and place them only by translation. Let binary variable $x\_{pb}$ indicate whether the piece $p$ is placed on the cell $b$ (some predefined reference point on the piece being on $b$). Let the set $P\_i\subset P$ represent all flipped and rotated version of a same pentomino, and binary variable $y\_i$ indicates whether the pentomino $i$ is placed on the board, so we have
$$
y\_i = \sum\_{p\in P\_i} \sum\_{b\in B} x\_{pb}
$$
and the objective is to maximize $\sum\_i y\_i$.
Putting the reference point on some cells make the tile out of the board, let that set be $F\_p$, we have
$$
x\_{pb} = 0 \quad\forall b \in F\_p.
$$
Now the main part. Actually in every cell $b$, we could find all possible $(p,b')$ that will cover the cell $b$, say the set is $Covered(b)$. By constraining $\sum\_{Covered(b)} x\_{pb'} \leq 1$, we could prevent overlap. To prevent neighboring, I build sets $Edge(b) = \{(p, b')\}$ similarly, which means if putting $p$ in $b'$, the cell $b$ will be on the edge of that piece. Then we need some constraints like
$$
\alpha \sum\_{(p,b')\in Covered(b)} x\_{pb'} + \beta \sum\_{(p,b') \in Edge(b)} x\_{pb'} \leq \delta
$$
The parameters $\alpha, \beta, \delta >0$should satisfy that $\alpha \leq \delta$, $4\beta \leq \delta$, $\alpha + \beta > \delta$, $2\alpha > \delta$, meaning that "one cover is allowed", "four edges on the same cell is allowed", "one cover and one edge is not allowed" (that is when two pieces are next to each other) and "no overlap".
I chose $\alpha=\delta=1, \beta=0.25$ (actually any $\beta > 0$ works...).
That is all constraints we need. | I can manage
>
> seven pentominoes, in a few different ways:
>
>
>
> [![seven pentominoes](https://i.stack.imgur.com/FPIEH.png)](https://i.stack.imgur.com/FPIEH.png) [![seven again](https://i.stack.imgur.com/rVcqQ.png)](https://i.stack.imgur.com/rVcqQ.png)
>
>
>
There is an obvious upper bound of
>
> twelve (the total number of distinct pentominoes, and $12\times5$ is still less than the number of squares on the board),
>
>
>
but this is nowhere near achievable given the restriction that pentominoes are not allowed to touch each other orthogonally. This means that
>
> every placed pentomino creates at least 4 squares around it that no other pentomino can occupy. *At least* 4, in the best possible scenario where the pentomino is placed in a corner - usually more. (I think 4 is only achievable with the P-pentomino in the corner and 5 is only achievable with the symmetric L-pentomino in the corner, otherwise it's more.)
>
>
>
Because of this, I'm pretty sure the number I managed above is optimal and it's not possible to place more. |
115,794 | **Rules**
1. Place some pentominoes into an 8 x 8 grid. They do not touch each other. They can touch only diagonally (with corner).
2. Pentominoes cannot repeat in the grid. Rotations and reflections of a pentomino are considered the same shape.
3. Grid is 8 x 8. | 2022/04/17 | [
"https://puzzling.stackexchange.com/questions/115794",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/79520/"
] | I solved this completely by hand.
>
> ![solution with 8 pentominos](https://i.stack.imgur.com/0ksZz.png)
>
>
>
Here is a clean proof of its optimality. No computer is needed. Mere pencil and paper suffice.
Expand each pentomino by adding little right-angled isosceles triangles with area 1/4 as follows:
1. For each (unit) cell with edge $A$ along its perimeter, add a little triangle with hypotenuse $A$ beside that cell.
2. For each pair of adjacent cells with adjacent edges $A,B$ along its perimeter, add a little triangle beside both the triangles that had been added beside those cells at $A,B$.
3. For the V-pentomino, add 2 more little triangles to completely fill in the region between the two arms of the "V".
Here is an example (with added triangles yellow in step 1 and green in step 2):
![F-pentomino with 12 triangles added in step 1 and 2 triangles added in step 2](https://i.stack.imgur.com/4Yh3T.png)
Observe that the number of little triangles added is at least the perimeter, regardless of the pentomino. The perimeter is at least 12 except for the P-pentomino, but the P-pentomino has 4 little triangles added in step 2. Except the X-pentomino, every other pentomino has at least 2 little triangles added in step 2. Thus the expanded X-pentomino has area $5+12/4 = 8$, and the expanded P,F,W-pentominos have area $5+14/4 = 8.5$, and every other pentomino has area at least $5+16/4 = 9$.
It is easy to see that, for any solution to the puzzle, the expanded pentominos will still not overlap. So if there are 9 distinct pentominos, then their total area is at least $8 + 8.5×3 + 9×5 = 78.5$.
Now expand the 8×8 board as well in the same manner, which adds 15 little triangles to each side. The expanded board has area $8×8 + 15 = 79$, but at least one of the added triangles next to each side of the board will not be covered, so the actual covered area is at most 78. Hence 9 distinct pentominos cannot fit.
---
In fact, we can show that 9 pentominos cannot fit even if each pentomino can be used 4 times! To see why, observe that each pentomino can only cover 6 units of the board perimeter, after which there is a gap of at least 1 unit before the next pentomino along the board perimeter. Let T be the expanded board area. Due to the gaps, not all of T can be covered by the pentominos. First, each isolated gap 'reduces' T by 1 unit. Two adjacent gaps 'reduces' T by at least 1.5 units (attained at the board corner). In general, $(k+1)$ adjacent gaps 'reduces' T by at least $(k+1)/2$ units. Thus the average reduction is at least 1/7 per board perimeter. Thus the gaps 'reduces' T by at least $\lceil32×1/7\rceil = 5$, so the covered expanded board area is at most $8×8 + 15 − 5 = 74$. But 9 pentominos (even with quadrupled pentominos) would have total area at least $8×4 + 8.5×5 = 74.5$. I presume that these bounds can be improved to show that 9 pentominos regardless of how many repeats cannot fit, but I did not bother to squeeze this last bit.
---
An equivalent counting method is to count the cell edges instead of area. Each pentomino already has 15 or 16 cell edges, and between each pair of adjacent cells along its perimeter we can add 1/2 edge sticking out, because that goes at most halfway to any other pentomino. In total we would get at least 17 edges per pentomino except 16 for the X-pentomino, which corresponds to 8.5 area for each pentomino except 8 for the X-pentomino.
The slight advantage of this counting is that it is easier to see where we are making losses. For instance, every untouched corner incurs a loss of at least 1 edge (i.e. 1/2×2), and this applies at the boundary as well, so we automatically know that we want to minimize the number of untouched corners. Also, every empty 2×2 square in the board incurs a loss of at least 2 edges, twice as bad as an untouched corner.
I initially did not mention this approach because the area equivalent is a bit easier to understand. However, I have decided to add it in, because it is much easier to *write a program* that uses this for a branch-and-bound search that counts the total edges *plus the (necessary) losses* so far. This makes it easy to prune most branches of the search. We even get a reasonable heuristic for branch-ordering, namely to first try placing the next pentomino to minimize the total edges+loss so far. | I can manage
>
> seven pentominoes, in a few different ways:
>
>
>
> [![seven pentominoes](https://i.stack.imgur.com/FPIEH.png)](https://i.stack.imgur.com/FPIEH.png) [![seven again](https://i.stack.imgur.com/rVcqQ.png)](https://i.stack.imgur.com/rVcqQ.png)
>
>
>
There is an obvious upper bound of
>
> twelve (the total number of distinct pentominoes, and $12\times5$ is still less than the number of squares on the board),
>
>
>
but this is nowhere near achievable given the restriction that pentominoes are not allowed to touch each other orthogonally. This means that
>
> every placed pentomino creates at least 4 squares around it that no other pentomino can occupy. *At least* 4, in the best possible scenario where the pentomino is placed in a corner - usually more. (I think 4 is only achievable with the P-pentomino in the corner and 5 is only achievable with the symmetric L-pentomino in the corner, otherwise it's more.)
>
>
>
Because of this, I'm pretty sure the number I managed above is optimal and it's not possible to place more. |
44,410,809 | I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file.
Here is the my xml code and gradle code snippets
myactivity.xml
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<include layout="@layout/toolbar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:autoSizeTextType="uniform"/>
</LinearLayout>
```
Gradle snippet
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:support-v4:25.2.0'//Added support library
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
}
``` | 2017/06/07 | [
"https://Stackoverflow.com/questions/44410809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3824298/"
] | As stated in the [docs](https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html#setting-textview-autosize):
>
> The Support Library 26.0 provides full support to the autosizing TextView feature on devices running Android versions prior to Android 8.0 (API level 26). The library provides support to Android 4.0 (API level 14) and higher. **The android.support.v4.widget package contains the TextViewCompat** class to access features in a backward-compatible fashion.
>
>
>
You need to replace `TextView` with `AppCompatTextView` and upgrade your support lib to v26.0.0 in order to use that feature.
```
compile 'com.android.support:support-v4:26.0.0'
```
Don't forget to upgrade your `buildToolsVersion` to `26.0.0` and `compileSdkVersion` to `26` as well. | This API is available only from API level 26. |
44,410,809 | I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file.
Here is the my xml code and gradle code snippets
myactivity.xml
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<include layout="@layout/toolbar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:autoSizeTextType="uniform"/>
</LinearLayout>
```
Gradle snippet
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:support-v4:25.2.0'//Added support library
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
}
``` | 2017/06/07 | [
"https://Stackoverflow.com/questions/44410809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3824298/"
] | Use AppCompatTextView and supportLibrary 26.0.1
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="200dp"
app:autoSizeTextType="uniform" />
</LinearLayout>
``` | This API is available only from API level 26. |
44,410,809 | I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file.
Here is the my xml code and gradle code snippets
myactivity.xml
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<include layout="@layout/toolbar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:autoSizeTextType="uniform"/>
</LinearLayout>
```
Gradle snippet
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:support-v4:25.2.0'//Added support library
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
}
``` | 2017/06/07 | [
"https://Stackoverflow.com/questions/44410809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3824298/"
] | As stated in the [docs](https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html#setting-textview-autosize):
>
> The Support Library 26.0 provides full support to the autosizing TextView feature on devices running Android versions prior to Android 8.0 (API level 26). The library provides support to Android 4.0 (API level 14) and higher. **The android.support.v4.widget package contains the TextViewCompat** class to access features in a backward-compatible fashion.
>
>
>
You need to replace `TextView` with `AppCompatTextView` and upgrade your support lib to v26.0.0 in order to use that feature.
```
compile 'com.android.support:support-v4:26.0.0'
```
Don't forget to upgrade your `buildToolsVersion` to `26.0.0` and `compileSdkVersion` to `26` as well. | Use AppCompatTextView and supportLibrary 26.0.1
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="200dp"
app:autoSizeTextType="uniform" />
</LinearLayout>
``` |
2,829,287 | For example,
User adds this "iamsmelly.com".
And if I add an href to this, the link would be
www.mywebsite.com/iamsmelly.com
Is there a way to make it absolute if its not prepended by an http:// ?
Or should I revert to jQuery for this? | 2010/05/13 | [
"https://Stackoverflow.com/questions/2829287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93311/"
] | Probably a good place to handle this is in a `before_save` on your model. I'm not aware of a predefined helper (though `auto_link` comes somewhat close) but a relatively simple regexp should do the job:
```
class User < ActiveRecord::Base
before_save :check_links
def check_links
self.link = "http://" + self.link unless self.link.match /^(https?|ftp):\/\//
end
end
``` | I've looked for something similar before with no luck. I made a helper method like so:
```
def ensure_absolute(str_link)
(str_link.include?("http://") || str_link.include?("https://")) ? str_link : ("http://"+str_link)
end
``` |
16,114,993 | I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`:
```
<html>
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("#content").attr("src","http://vietduc24h.com");
})
</script>
</head>
<body>
<div id="content"></div>
</body>
</html
```
I don't want to use an iframe. How can I do this? | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300976/"
] | You need to think about CORS in this aspect. The code you need to have is:
```
<script type="text/javascript">
$(document).ready(function()
{
$("#content").load("http://vietduc24h.com");
})
</script>
```
When your domain is not inside `vietduc24h.com`, you might get some security exception. In order to avoid that, you can host a local proxy here. In PHP, we do this way (`url.php`):
```
<?php
$url = file_get_contents(urlencode($_GET["url"]));
echo $url;
?>
```
And in the script, you need to modify this way:
```
<script type="text/javascript">
$(document).ready(function()
{
$("#content").load("proxy.php?url=http://vietduc24h.com");
})
</script>
``` | Try this code with the jQuery `Load` function:
```
$('#content').load('http://vietduc24h.com', function() {
alert('Load was performed.');
});
```
If you encounter in security issues because of the Cross-Origin-Resource-Sharing policy than you have to use a proxy in your server code. |
16,114,993 | I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`:
```
<html>
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("#content").attr("src","http://vietduc24h.com");
})
</script>
</head>
<body>
<div id="content"></div>
</body>
</html
```
I don't want to use an iframe. How can I do this? | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300976/"
] | Try this code with the jQuery `Load` function:
```
$('#content').load('http://vietduc24h.com', function() {
alert('Load was performed.');
});
```
If you encounter in security issues because of the Cross-Origin-Resource-Sharing policy than you have to use a proxy in your server code. | Try this:
```
$("#content").html('<object data="http://vietduc24h.com">');
```
Taken from [this answer](https://stackoverflow.com/a/9964050/646668). |
16,114,993 | I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`:
```
<html>
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("#content").attr("src","http://vietduc24h.com");
})
</script>
</head>
<body>
<div id="content"></div>
</body>
</html
```
I don't want to use an iframe. How can I do this? | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300976/"
] | You need to think about CORS in this aspect. The code you need to have is:
```
<script type="text/javascript">
$(document).ready(function()
{
$("#content").load("http://vietduc24h.com");
})
</script>
```
When your domain is not inside `vietduc24h.com`, you might get some security exception. In order to avoid that, you can host a local proxy here. In PHP, we do this way (`url.php`):
```
<?php
$url = file_get_contents(urlencode($_GET["url"]));
echo $url;
?>
```
And in the script, you need to modify this way:
```
<script type="text/javascript">
$(document).ready(function()
{
$("#content").load("proxy.php?url=http://vietduc24h.com");
})
</script>
``` | Try this:
```
$("#content").html('<object data="http://vietduc24h.com">');
```
Taken from [this answer](https://stackoverflow.com/a/9964050/646668). |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | It is always safe! (Math agrees with me.)
The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor.
I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.) | As Marc B alluded to, Java will promote `b` to a `long` before actually doing the `%` operation. This promotion applies to all the arithmetic operations, even `<<` and `>>` I believe.
In other words, if you have a binary operation and the two arguments don't have the same type, the smaller one will be promoted so that both sides will have the same type. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this:
```
long a = ...;
int b = ...;
long c = a % b + Integer.MAX_VALUE;
```
If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value.
This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly.
Update
------
Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one. | It is always safe! (Math agrees with me.)
The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor.
I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.) |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | It is always safe! (Math agrees with me.)
The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor.
I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.) | >
> does any one know why Java has a longer type for % than needed?
>
>
>
I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | It is always safe! (Math agrees with me.)
The result of a mod operation is always less than the divisor. Since the result of a mod operation is essentially the remainder after performing integer division, you will never have a remainder larger than the divisor.
I suspect the reason for having the operation return a `long` is because the divisor gets expanded to a `long` before the operation takes place. This makes a `long` result possible. (*note* even though the variable is expanded in memory, its value will not change. An expanded `int` will never be larger than an `int` can hold.) | This is a late party chime-in but the reason is pretty simple:
The bytecode operands do need explicit casts (`L2I`) and longs need 2 stack positions compared to 1 for int, char, short, byte [casting from byte to int doesn't need a bytecode instruction]. After the mod operation the result takes 2 positions on the top of stack.
*edit:* Also, I forgot to mention Java doesn't have division/remainder of 64b/32b. There are only 64->64bit operations, i.e. `LDIV` and `LREM`. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this:
```
long a = ...;
int b = ...;
long c = a % b + Integer.MAX_VALUE;
```
If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value.
This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly.
Update
------
Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one. | As Marc B alluded to, Java will promote `b` to a `long` before actually doing the `%` operation. This promotion applies to all the arithmetic operations, even `<<` and `>>` I believe.
In other words, if you have a binary operation and the two arguments don't have the same type, the smaller one will be promoted so that both sides will have the same type. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | As Marc B alluded to, Java will promote `b` to a `long` before actually doing the `%` operation. This promotion applies to all the arithmetic operations, even `<<` and `>>` I believe.
In other words, if you have a binary operation and the two arguments don't have the same type, the smaller one will be promoted so that both sides will have the same type. | >
> does any one know why Java has a longer type for % than needed?
>
>
>
I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this:
```
long a = ...;
int b = ...;
long c = a % b + Integer.MAX_VALUE;
```
If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value.
This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly.
Update
------
Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one. | >
> does any one know why Java has a longer type for % than needed?
>
>
>
I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this:
```
long a = ...;
int b = ...;
long c = a % b + Integer.MAX_VALUE;
```
If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value.
This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly.
Update
------
Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one. | This is a late party chime-in but the reason is pretty simple:
The bytecode operands do need explicit casts (`L2I`) and longs need 2 stack positions compared to 1 for int, char, short, byte [casting from byte to int doesn't need a bytecode instruction]. After the mod operation the result takes 2 positions on the top of stack.
*edit:* Also, I forgot to mention Java doesn't have division/remainder of 64b/32b. There are only 64->64bit operations, i.e. `LDIV` and `LREM`. |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | This is a late party chime-in but the reason is pretty simple:
The bytecode operands do need explicit casts (`L2I`) and longs need 2 stack positions compared to 1 for int, char, short, byte [casting from byte to int doesn't need a bytecode instruction]. After the mod operation the result takes 2 positions on the top of stack.
*edit:* Also, I forgot to mention Java doesn't have division/remainder of 64b/32b. There are only 64->64bit operations, i.e. `LDIV` and `LREM`. | >
> does any one know why Java has a longer type for % than needed?
>
>
>
I don't know for sure. Maybe to make it work exactly the same way as the other multiplicative operators: `*` and `\`. In the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17) `The type of a multiplicative expression is the promoted type of its operands.` Adding an exception to `long % int` would be confusing. |
45,507,197 | This is about converting the enumeration values to a string array. I have an enumeration:
```
enum Weather {
RAINY, SUNNY, STORMY
}
```
And I want to convert this to a string array with minimal effort and no loops with Java 8+. This is the best I came up with:
```
Arrays.stream(Weather.values()).map(Enum::toString).toArray(String[]::new)
```
Any other and similarly or more convenient ways to do the same thing? | 2017/08/04 | [
"https://Stackoverflow.com/questions/45507197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2735286/"
] | Original post
=============
Yes, that's a good Java 8 way, but...
The `toString` can be overridden, so you'd better go with `Weather::name` which returns the name of an enum constant (exactly as declared in the enum declaration) and can't be changed:
```
Stream.of(Weather.values()).map(Weather::name).toArray(String[]::new);
```
---
A bit of generics
=================
I wrote a helper class to deal with any enum in a generic way:
```
class EnumUtils {
public static <T extends Enum<T>> String[] getStringValues(Class<T> enumClass) {
return getStringValuesWithStringExtractor(enumClass, Enum::name);
}
public static <T extends Enum<T>> String[] getStringValuesWithStringExtractor(
Class<T> enumClass,
Function<? super T, String> extractor
) {
return of(enumClass.getEnumConstants()).map(extractor).toArray(String[]::new);
}
}
```
Here is a demonstration:
```
enum Weather {
RAINY, SUNNY, STORMY;
@Override
public String toString() {
return String.valueOf(hashCode());
}
public static void main(String[] args) {
System.out.println(Arrays.toString(EnumUtils.getStringValues(Weather.class)));
System.out.println(Arrays.toString(EnumUtils.getStringValuesWithStringExtractor(Weather.class, Weather::toString)));
}
}
```
And the output:
```
[RAINY, SUNNY, STORMY]
[359023572, 305808283, 2111991224]
``` | If you're frequently converting enum values to any kind of array you can as well precompute it values as static field:
```
enum Weather {
RAINY, SUNNY, STORMY;
public static final String[] STRINGS = Arrays.stream(Weather.values())
.map(Enum::name)
.collect(Collectors.toList())
.toArray(new String[0]);
}
```
And use it just like that `Weather.STRINGS;`. |
26,351 | I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below.
1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall)
2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?)
So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out? | 2016/03/23 | [
"https://aviation.stackexchange.com/questions/26351",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/6831/"
] | Lets start with the very basic concepts....
In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment.
The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1
***Positive and Negative Angle of Attack***
![enter image description here](https://i.stack.imgur.com/60asc.jpg)
Figure 1 - Positive and Negative Angle of Attack
If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur.
When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane.
Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall.
**Tailplane Stall Aerodynamics**
1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA).
[As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.]
2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser.
3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft.
4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA.
5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2
6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA.
7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall.
8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment.
**Effect of mainplane flap on downwash**
![enter image description here](https://i.stack.imgur.com/xHo2B.jpg)
Figure 2 - Effect of mainplane flap on downwash
On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert.
**now match with your recovery actions**
1. You have no doubt with your 1st point.
2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure.
3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition. | There was a NASA report on the [NASA/FAA Tailplane Icing Program Overview](http://ntrs.nasa.gov/search.jsp?R=19990019485&hterms=19990019485&qs=Ntk%3DDocument-ID%26Ntt%3D19990019485%26N%3D0), which covers the points raised by you. It lists certain actions that can be done to recover from a tail plane stall:
>
> When the full tail stall was experienced during the power transition, the stall recovery procedure was:
>
>
> • Reduce thrust (may be airplane specific)
>
>
> • Pull back on yoke/ increase $\alpha$
>
>
> • Raise flaps
>
>
>
* Raise flaps to previous setting
This is done mainly to undo the changes that caused the stall in the first place (reducing thrust is also done for this reason). The report says,
>
> The major lesson learned to recover from a tail stall was to undo what was
> just done to cause the event.
>
>
>
* Apply nose up elevator pressure
Basically you are pulling back on the yoke to increase the tail download so that the aircraft nose-down pitching moment is countered. From the report:
>
> Pulling back on the yoke increased the camber of the tailplane, which provided enough tail download to counteract the nose-down pitching moment and increase the $\alpha\_{tail}$
>
>
>
This sounds counterintutive as the conventional tail produces force in the direction opposite to the main wing. The report notes:
>
> It was noted that this tail stall recovery procedure is opposite of the recovery from a wing stall. The reason for the difference is the location of the flow separation. In a wing stall, the flow separates from the upper surface of the wing, therefore reattachment is made by decreasing the wing $\alpha$. In a tail stall event, the flow separates from the lower surface of the tail and requires a positive increase in tail to reattach the flow.
>
>
>
* Do not increase airspeed unless it is necessary to avoid a wing stall
The aircraft is already at a nose down attitude. Increasing speed will further excabarate the situation, which may put the corrective action beyond the capability of the tailplane. |
26,351 | I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below.
1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall)
2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?)
So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out? | 2016/03/23 | [
"https://aviation.stackexchange.com/questions/26351",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/6831/"
] | Lets start with the very basic concepts....
In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment.
The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1
***Positive and Negative Angle of Attack***
![enter image description here](https://i.stack.imgur.com/60asc.jpg)
Figure 1 - Positive and Negative Angle of Attack
If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur.
When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane.
Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall.
**Tailplane Stall Aerodynamics**
1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA).
[As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.]
2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser.
3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft.
4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA.
5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2
6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA.
7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall.
8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment.
**Effect of mainplane flap on downwash**
![enter image description here](https://i.stack.imgur.com/xHo2B.jpg)
Figure 2 - Effect of mainplane flap on downwash
On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert.
**now match with your recovery actions**
1. You have no doubt with your 1st point.
2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure.
3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition. | For those recommended actions to be effective, two preconditions have been quietly assumed:
1. The tail surface produces downward lift and
2. The wing has positive camber.
Both can be assumed to be correct in almost any case. Now let’s look at the three recommendations in detail:
>
> raise flaps to the previous setting.
>
>
>
Flaps increase camber and shift the center of pressure backwards. In order to balance the aircraft with the same center of gravity location, the tail needs to produce [more downward force](https://aviation.stackexchange.com/questions/13855/why-cant-planes-use-only-flaps-in-the-tail-section-instead-of-stabilizers/13861#13861) with lowered flaps. Retracting flaps will unload the horizontal tail and reduce the stall condition.
>
> apply nose up elevator pressure.
>
>
>
This [adds tail camber](https://aviation.stackexchange.com/questions/44338/is-it-correct-to-say-the-up-elevator-position-decreases-the-camber-of-the-eleva) and helps to produce the same downward force at a less negative local angle of attack of the stabilizer. The induced angle of attack of the added tail camber will increase the local angle of attack at the stabilizer. This can only help momentarily, though, because it will make the aircraft pitch up and lose speed - unless you have a movable stabilizer which is used for trim. Re-trim with the new elevator setting and the change becomes permanent.
>
> do not increase airspeed unless it is necessary to avoid a wing stall.
>
>
>
When the main wing has positive camber, a lower wing angle of attack [shifts its center of pressure backwards](https://aviation.stackexchange.com/questions/47306/does-static-longitudinal-stability-require-download-on-the-tail/47308#47308). Therefore, the tail load and lift coefficient are lowest at low speed, and flying slowly will unload the tail. With rear center of gravity, tail load normally can even become slightly positive at low speed.
So in all cases the recommendations help to unload the tail and reduce the condition that let the iced tail stall. |
26,351 | I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below.
1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall)
2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?)
So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out? | 2016/03/23 | [
"https://aviation.stackexchange.com/questions/26351",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/6831/"
] | Lets start with the very basic concepts....
In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment.
The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1
***Positive and Negative Angle of Attack***
![enter image description here](https://i.stack.imgur.com/60asc.jpg)
Figure 1 - Positive and Negative Angle of Attack
If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur.
When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane.
Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall.
**Tailplane Stall Aerodynamics**
1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA).
[As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.]
2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser.
3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft.
4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA.
5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2
6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA.
7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall.
8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment.
**Effect of mainplane flap on downwash**
![enter image description here](https://i.stack.imgur.com/xHo2B.jpg)
Figure 2 - Effect of mainplane flap on downwash
On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert.
**now match with your recovery actions**
1. You have no doubt with your 1st point.
2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure.
3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition. | I have a theory on applying the backstick on a tail stall induced while lowering the flaps. OP’s comment:
>
> apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
>
>
>
If the tail stalls, then the nose pitches forward. The center of rotation is about somewhere near the wing and CG, well forward of the tail. So the tail instantly sees a step increase in AOA, to well beyond the stall AOA. Probably really high AOA. The aircraft develops inertia in pitch too.
At this point, you are doing triage while you lower the flaps and undo what you did. While you’re not getting much lift (downward) from the tail, it is resisting the forward pitch with drag. Letting the stick or yoke come forward would dump this pitch resisting force, and the aircraft would go right over its nose before the flaps could raise.
There’s my theory. |
26,351 | I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below.
1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall)
2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?)
So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out? | 2016/03/23 | [
"https://aviation.stackexchange.com/questions/26351",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/6831/"
] | There was a NASA report on the [NASA/FAA Tailplane Icing Program Overview](http://ntrs.nasa.gov/search.jsp?R=19990019485&hterms=19990019485&qs=Ntk%3DDocument-ID%26Ntt%3D19990019485%26N%3D0), which covers the points raised by you. It lists certain actions that can be done to recover from a tail plane stall:
>
> When the full tail stall was experienced during the power transition, the stall recovery procedure was:
>
>
> • Reduce thrust (may be airplane specific)
>
>
> • Pull back on yoke/ increase $\alpha$
>
>
> • Raise flaps
>
>
>
* Raise flaps to previous setting
This is done mainly to undo the changes that caused the stall in the first place (reducing thrust is also done for this reason). The report says,
>
> The major lesson learned to recover from a tail stall was to undo what was
> just done to cause the event.
>
>
>
* Apply nose up elevator pressure
Basically you are pulling back on the yoke to increase the tail download so that the aircraft nose-down pitching moment is countered. From the report:
>
> Pulling back on the yoke increased the camber of the tailplane, which provided enough tail download to counteract the nose-down pitching moment and increase the $\alpha\_{tail}$
>
>
>
This sounds counterintutive as the conventional tail produces force in the direction opposite to the main wing. The report notes:
>
> It was noted that this tail stall recovery procedure is opposite of the recovery from a wing stall. The reason for the difference is the location of the flow separation. In a wing stall, the flow separates from the upper surface of the wing, therefore reattachment is made by decreasing the wing $\alpha$. In a tail stall event, the flow separates from the lower surface of the tail and requires a positive increase in tail to reattach the flow.
>
>
>
* Do not increase airspeed unless it is necessary to avoid a wing stall
The aircraft is already at a nose down attitude. Increasing speed will further excabarate the situation, which may put the corrective action beyond the capability of the tailplane. | For those recommended actions to be effective, two preconditions have been quietly assumed:
1. The tail surface produces downward lift and
2. The wing has positive camber.
Both can be assumed to be correct in almost any case. Now let’s look at the three recommendations in detail:
>
> raise flaps to the previous setting.
>
>
>
Flaps increase camber and shift the center of pressure backwards. In order to balance the aircraft with the same center of gravity location, the tail needs to produce [more downward force](https://aviation.stackexchange.com/questions/13855/why-cant-planes-use-only-flaps-in-the-tail-section-instead-of-stabilizers/13861#13861) with lowered flaps. Retracting flaps will unload the horizontal tail and reduce the stall condition.
>
> apply nose up elevator pressure.
>
>
>
This [adds tail camber](https://aviation.stackexchange.com/questions/44338/is-it-correct-to-say-the-up-elevator-position-decreases-the-camber-of-the-eleva) and helps to produce the same downward force at a less negative local angle of attack of the stabilizer. The induced angle of attack of the added tail camber will increase the local angle of attack at the stabilizer. This can only help momentarily, though, because it will make the aircraft pitch up and lose speed - unless you have a movable stabilizer which is used for trim. Re-trim with the new elevator setting and the change becomes permanent.
>
> do not increase airspeed unless it is necessary to avoid a wing stall.
>
>
>
When the main wing has positive camber, a lower wing angle of attack [shifts its center of pressure backwards](https://aviation.stackexchange.com/questions/47306/does-static-longitudinal-stability-require-download-on-the-tail/47308#47308). Therefore, the tail load and lift coefficient are lowest at low speed, and flying slowly will unload the tail. With rear center of gravity, tail load normally can even become slightly positive at low speed.
So in all cases the recommendations help to unload the tail and reduce the condition that let the iced tail stall. |
26,351 | I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below.
1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall)
2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?)
So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out? | 2016/03/23 | [
"https://aviation.stackexchange.com/questions/26351",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/6831/"
] | There was a NASA report on the [NASA/FAA Tailplane Icing Program Overview](http://ntrs.nasa.gov/search.jsp?R=19990019485&hterms=19990019485&qs=Ntk%3DDocument-ID%26Ntt%3D19990019485%26N%3D0), which covers the points raised by you. It lists certain actions that can be done to recover from a tail plane stall:
>
> When the full tail stall was experienced during the power transition, the stall recovery procedure was:
>
>
> • Reduce thrust (may be airplane specific)
>
>
> • Pull back on yoke/ increase $\alpha$
>
>
> • Raise flaps
>
>
>
* Raise flaps to previous setting
This is done mainly to undo the changes that caused the stall in the first place (reducing thrust is also done for this reason). The report says,
>
> The major lesson learned to recover from a tail stall was to undo what was
> just done to cause the event.
>
>
>
* Apply nose up elevator pressure
Basically you are pulling back on the yoke to increase the tail download so that the aircraft nose-down pitching moment is countered. From the report:
>
> Pulling back on the yoke increased the camber of the tailplane, which provided enough tail download to counteract the nose-down pitching moment and increase the $\alpha\_{tail}$
>
>
>
This sounds counterintutive as the conventional tail produces force in the direction opposite to the main wing. The report notes:
>
> It was noted that this tail stall recovery procedure is opposite of the recovery from a wing stall. The reason for the difference is the location of the flow separation. In a wing stall, the flow separates from the upper surface of the wing, therefore reattachment is made by decreasing the wing $\alpha$. In a tail stall event, the flow separates from the lower surface of the tail and requires a positive increase in tail to reattach the flow.
>
>
>
* Do not increase airspeed unless it is necessary to avoid a wing stall
The aircraft is already at a nose down attitude. Increasing speed will further excabarate the situation, which may put the corrective action beyond the capability of the tailplane. | I have a theory on applying the backstick on a tail stall induced while lowering the flaps. OP’s comment:
>
> apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
>
>
>
If the tail stalls, then the nose pitches forward. The center of rotation is about somewhere near the wing and CG, well forward of the tail. So the tail instantly sees a step increase in AOA, to well beyond the stall AOA. Probably really high AOA. The aircraft develops inertia in pitch too.
At this point, you are doing triage while you lower the flaps and undo what you did. While you’re not getting much lift (downward) from the tail, it is resisting the forward pitch with drag. Letting the stick or yoke come forward would dump this pitch resisting force, and the aircraft would go right over its nose before the flaps could raise.
There’s my theory. |
2,093,466 | I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible?
*Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points.
Is it just defined this way or is there a particular reason ?
**Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
$f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$. | 2017/01/11 | [
"https://math.stackexchange.com/questions/2093466",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406041/"
] | They are the same *almost everywhere*. But clearly one of them does not exist for $x=1$ (since "$\tfrac{0}{0}$" is undefined), while the other one is simply $1$ at $x=1$.
>
> I understand that division by zero isn't allowed, but we merely just multiplied f(x) = 1 by (x-1)/(x-1)
>
>
>
You can multiply by any fraction $\tfrac{a}{a}$; but not when $a=0$ because the fraction you want to multiply with, isn't even defined then. So multiplying by $\tfrac{x-1}{x-1}$ is fine, but only valid for $x \ne 1$.
>
> why don't we simplify f(x) = (x-1)/(x-1) to f(x) = 1 before plotting the points.
> Is it just defined this way or is there a particular reason ?
>
>
>
You can simplify, but recall that simplifying is actually dividing numerator and denominator by the same number: you can simplify $\tfrac{ka}{kb}$ to $\tfrac{a}{b}$ by dividing by $k$. But also then: this only works for $k \ne 0$ since you can't divide by $0$. So "simplifying" $\tfrac{x-1}{x-1}$ to $1$ is fine, for $x-1 \ne 0$ so for $x \ne 1$.
---
>
> **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
> $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$.
>
>
>
Technically, the domain is a part of the function: it should be given (as well as the codomain). It is very common though that when unspecified, in the context of real-valued functions of a real variable, we assume the 'maximal domain' is intended (and $\mathbb{R}$ is taken as codomain). Then look at:
$$f : \mathbb{R} \to \mathbb{R} : x \mapsto f(x) = 1$$
and
$$g : \mathbb{R} \setminus \left\{ 1 \right\} \to \mathbb{R} : x \mapsto g(x) = \frac{x-1}{x-1}$$
The functions $f$ and $g$ are different, but $f(x) = g(x)=1$ for all $x$ except when $x=1$, where $g$ is undefined. | **Question**: What is a function?
**Answer**: Maybe simply said it is a map (receipe), $f(x)$, that projects some elements, $x$, contained in a specifically defined set, Domain $D$, into another set, Range $R$.
**Discussion**: Hence when defining a function one must define the Domain as well as the functional form. Otherwise the function is not defined.
**Conclusion**: If two funtions have the same domain and the same receipe then they are the same "maps" otherwise they are not. |
2,093,466 | I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible?
*Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points.
Is it just defined this way or is there a particular reason ?
**Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
$f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$. | 2017/01/11 | [
"https://math.stackexchange.com/questions/2093466",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406041/"
] | They are the same *almost everywhere*. But clearly one of them does not exist for $x=1$ (since "$\tfrac{0}{0}$" is undefined), while the other one is simply $1$ at $x=1$.
>
> I understand that division by zero isn't allowed, but we merely just multiplied f(x) = 1 by (x-1)/(x-1)
>
>
>
You can multiply by any fraction $\tfrac{a}{a}$; but not when $a=0$ because the fraction you want to multiply with, isn't even defined then. So multiplying by $\tfrac{x-1}{x-1}$ is fine, but only valid for $x \ne 1$.
>
> why don't we simplify f(x) = (x-1)/(x-1) to f(x) = 1 before plotting the points.
> Is it just defined this way or is there a particular reason ?
>
>
>
You can simplify, but recall that simplifying is actually dividing numerator and denominator by the same number: you can simplify $\tfrac{ka}{kb}$ to $\tfrac{a}{b}$ by dividing by $k$. But also then: this only works for $k \ne 0$ since you can't divide by $0$. So "simplifying" $\tfrac{x-1}{x-1}$ to $1$ is fine, for $x-1 \ne 0$ so for $x \ne 1$.
---
>
> **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
> $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$.
>
>
>
Technically, the domain is a part of the function: it should be given (as well as the codomain). It is very common though that when unspecified, in the context of real-valued functions of a real variable, we assume the 'maximal domain' is intended (and $\mathbb{R}$ is taken as codomain). Then look at:
$$f : \mathbb{R} \to \mathbb{R} : x \mapsto f(x) = 1$$
and
$$g : \mathbb{R} \setminus \left\{ 1 \right\} \to \mathbb{R} : x \mapsto g(x) = \frac{x-1}{x-1}$$
The functions $f$ and $g$ are different, but $f(x) = g(x)=1$ for all $x$ except when $x=1$, where $g$ is undefined. | $f(x)=(x-1)/(x-1)$ does not have a value when $x=1$, different thing happens to $f(x)=1$ |
2,093,466 | I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible?
*Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points.
Is it just defined this way or is there a particular reason ?
**Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
$f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$. | 2017/01/11 | [
"https://math.stackexchange.com/questions/2093466",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406041/"
] | **Question**: What is a function?
**Answer**: Maybe simply said it is a map (receipe), $f(x)$, that projects some elements, $x$, contained in a specifically defined set, Domain $D$, into another set, Range $R$.
**Discussion**: Hence when defining a function one must define the Domain as well as the functional form. Otherwise the function is not defined.
**Conclusion**: If two funtions have the same domain and the same receipe then they are the same "maps" otherwise they are not. | $f(x)=(x-1)/(x-1)$ does not have a value when $x=1$, different thing happens to $f(x)=1$ |
59,133,760 | I have following HTML code
```
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false">
<label class="checkbox__label" for= "adapt-checkbox-453-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - ABC</span>
</div>
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted">
<label class="checkbox__label" for="adapt-checkbox-454-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - XYZ</span>
</div>
```
[Please check screenshot here](https://i.stack.imgur.com/0iOkd.png)
From which
1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC"
So I have written code as follows
```
WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']")));
selectCompatibleProduct1.click();
```
**Which is working fine. Its selecting the correct check-box.**
2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox.
Code for 2nd checkbox is:-
```
WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']")));
selectCompatibleProduct2.click();
```
Selenium Version is:- 4.0.0-alpha-3
Please can someone help me on this?
Thanks in advance. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59133760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189243/"
] | Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs`
```js
var data= [
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'base',
pos: 0,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 1,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 2,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'boomerang',
pos: 3,
gfs: ['a','b','c']
}
]
// You can access like this
console.log(data[data.length-1].gfs)
``` | You can access the array value by `index` so you can use loop to access it by index or you can directly access it using `index` number.
Check out these docs. It will help out to better understand
[Loops\_and\_iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
[Property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
```js
let data = [
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'base',
pos: 0,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 1,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 2,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'boomerang',
pos: 3,
gfs: [1, 2, 4, 5]
}
];
// by looping
for(let i = 0; i < data.length; i++) { // iterate on data, for(initilize, condition, increment)
let item = data[i]; // access item from data by bracket notation property accessors, pass index number i
let gfsList = item['gfs'] // grab the gfs object from item by bracket notation property accessors
if(Array.isArray(gfsList)) { // check if gfs is array or not
for(let j = 0; j < gfsList.length; j++) { //gfs is array so we can iterate again on each item of it
let gfsItem = gfsList[j];
console.log(gfsItem);
}
}
}
// direct access
console.log(data[data.length - 1]['gfs'])
``` |
59,133,760 | I have following HTML code
```
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false">
<label class="checkbox__label" for= "adapt-checkbox-453-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - ABC</span>
</div>
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted">
<label class="checkbox__label" for="adapt-checkbox-454-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - XYZ</span>
</div>
```
[Please check screenshot here](https://i.stack.imgur.com/0iOkd.png)
From which
1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC"
So I have written code as follows
```
WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']")));
selectCompatibleProduct1.click();
```
**Which is working fine. Its selecting the correct check-box.**
2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox.
Code for 2nd checkbox is:-
```
WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']")));
selectCompatibleProduct2.click();
```
Selenium Version is:- 4.0.0-alpha-3
Please can someone help me on this?
Thanks in advance. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59133760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189243/"
] | Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs`
```js
var data= [
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'base',
pos: 0,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 1,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 2,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'boomerang',
pos: 3,
gfs: ['a','b','c']
}
]
// You can access like this
console.log(data[data.length-1].gfs)
``` | JSON.parse() gives JavaScript object. Here it is the Array object, so you can access it by looping the array or specifying the array index directly.
```
var data = [
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'base',
pos: 0,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 1,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 2,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'boomerang',
pos: 3,
gfs: [Array]
}
]
data.forEach(data => {
console.log(data.gfs); //Print the gfs value of every object in the array
})
``` |
59,133,760 | I have following HTML code
```
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false">
<label class="checkbox__label" for= "adapt-checkbox-453-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - ABC</span>
</div>
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted">
<label class="checkbox__label" for="adapt-checkbox-454-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - XYZ</span>
</div>
```
[Please check screenshot here](https://i.stack.imgur.com/0iOkd.png)
From which
1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC"
So I have written code as follows
```
WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']")));
selectCompatibleProduct1.click();
```
**Which is working fine. Its selecting the correct check-box.**
2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox.
Code for 2nd checkbox is:-
```
WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']")));
selectCompatibleProduct2.click();
```
Selenium Version is:- 4.0.0-alpha-3
Please can someone help me on this?
Thanks in advance. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59133760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189243/"
] | Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs`
```js
var data= [
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'base',
pos: 0,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 1,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 2,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'boomerang',
pos: 3,
gfs: ['a','b','c']
}
]
// You can access like this
console.log(data[data.length-1].gfs)
``` | Accessed it by using
`console.log(obj.data[3].gfs)`
I didn't take into account that the data key stored inside data inside obj(which I assigned)/ |
299,700 | I was following [this tutorial](https://www.youtube.com/watch?v=lrvLnhm6Rqw&list=PLpVC00PAQQxHi-llE9Z8-Q747NYWpsq6t&index=32) on Drupal module development. It talks about database query joins in module development. The tutorial is made for Drupal 8 and I'm using Drupal 9.
Then I made this (look at the join part):
```
protected function load () {
$select = Database::getConnection()->select('rsvplist', 'r');
$select.join('users_field_data', 'u', 'r.uid = u.uid');
$select->join('node_field_data', 'n', 'r.nid = n.nid');
$select->addField('u', 'name');
$select->addField('n', 'title');
$select->addField('r', 'mail');
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $entries;
}
```
But get this error:
```
warning: join() expects at most 2 parameters, 3 given in Drupal\rsvplist\Controller\ReportController->load() (line 24 of /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php)
#0 /var/www/htdocs/drupal-modules/core/includes/bootstrap.inc(305): _drupal_error_handler_real(2, 'join() expects ...', '/var/www/htdocs...', 24)
#1 [internal function]: _drupal_error_handler(2, 'join() expects ...', '/var/www/htdocs...', 24, Array)
#2 /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php(24): join('users_field_dat...', 'u', 'r.uid = u.uid')
#3 /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php(52): Drupal\rsvplist\Controller\ReportController->load()
#4 [internal function]: Drupal\rsvplist\Controller\ReportController->report()
#5 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
#6 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/Render/Renderer.php(573): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#7 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#8 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
#9 /var/www/htdocs/drupal-modules/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#10 /var/www/htdocs/drupal-modules/vendor/symfony/http-kernel/HttpKernel.php(80): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#11 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#12 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#13 /var/www/htdocs/drupal-modules/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#14 /var/www/htdocs/drupal-modules/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#15 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#16 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /var/www/htdocs/drupal-modules/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/DrupalKernel.php(706): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /var/www/htdocs/drupal-modules/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#20 {main}
```
Drupal 9's join don't accepts the third argument:
```
'r.uid = u.uid'
```
A made some research but I was not able to find an equivalent example about how to use join this way in Drupap 9 documentation and other sources.
How can I add joins to a query in Drupal 9? | 2021/01/25 | [
"https://drupal.stackexchange.com/questions/299700",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/102226/"
] | In PHP:
* `.` is the string concatenation operator, not the one to call an object method
* [`join()`](https://www.php.net/manual/en/function.join.php) is an alias for the [`implode()`](https://www.php.net/manual/en/function.implode.php) function, which effectively requires 2 arguments, not 3
This means that `$select.join('users_field_data', 'u', 'r.uid = u.uid')` (which PHP reads as `$select . join('users_field_data', 'u', 'r.uid = u.uid')`) is:
* Converting the value contained in `$select` to a string
* Concatenating that string with the string returned by `implode()`
The arguments accepted by [`implode()`](https://www.php.net/manual/en/function.implode.php) has been changed in the latest PHP versions, but the function has never accepted three arguments, and the first two arguments has never been two strings.
This explains the error you are getting.
In Drupal 9, if `$select` is an object implementing [`SelectInterface`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/9.0.x), [`$select->join()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/function/Select%3A%3Ajoin/9.0.x) is an available method.
```php
public function join($table, $alias = NULL, $condition = NULL, $arguments = []) {
return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
}
```
Instead of `$select->join()`, you could call `$select->addJoin()`.
The first method doesn't require to specify the first or the last argument of `$select->addJoin()`, and it's the normally called method.
As side note, instead of using `$select` on database tables used for entity data, it's generally preferable to use the class returned from [`Drupal::entityQuery()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AentityQuery/9.0.x). | Solution:
In Drupal 9, I needed to replace joins so it works:
```
//$select.join('users_field_data', 'u', 'r.uid = u.uid');
$select->addJoin('inner','users_field_data','u','r.uid = u.uid');
//$select->join('node_field_data', 'n', 'r.nid = n.nid');
$select->addJoin('inner','node_field_data','n','r.nid = n.nid');
``` |
74,243,879 | I want to use UTC dates in my Node.js backend app, however, I need to be able to set time (hours and minutes) in a local/user-specified timezone.
I am looking for a solution in either pure JS or using `dayjs`. I am not looking for a solution in `moment`.
It seemed like using `dayjs` I could solve this problem quite easily, however, I could not find a way to accomplish this.
I can use UTC timezone by using [`dayjs.utc()`](https://day.js.org/docs/en/plugin/utc) or using [`dayjs.tz(someDate, 'Etc/UTC')`](https://day.js.org/docs/en/timezone/timezone).
When using `dayjs.utc()`, I cannot use/specify other timezones for *anything*, therefore I could not find a way to tell `dayjs` I want to set hours/minutes in a particular (non-UTC) timezone.
When using `dayjs.tz()`, I still cannot define a timezone of time I want to set to a particular date.
### Example in plain JS
My locale timezone is `Europe/Slovakia` (CEST = UTC+02 with DST, CET = UTC+1 without DST), however, I want this to work with any timezone.
```js
// Expected outcome
// old: 2022-10-29T10:00:00.000Z
// new time: 10h 15m CEST
// new: 2022-10-29T08:15:00.000Z
// Plain JS
const now = new Date('2022-10-29T10:00:00.000Z')
const hours = 10
const minutes = 15
now.setHours(10)
now.setMinutes(15)
// As my default timezone is `Europe/Bratislava`, it seems to work as expected
console.log(now)
// Output: 2022-10-29T08:15:00.000Z
// However, it won't work with timezones other than my local timezone
```
### (Nearly) a solution
***Update: I posted a working function in [this answer](https://stackoverflow.com/a/74245936/3408342).***
The following functions seems to work for most test cases, however, it fails for 6 4 cases known to me (any help is greatly appreciated):
* [DST to ST] `now` in DST before double hour, `newDate` in ST during double hour;
* [DST to ST] `now` in DST during double hour, `newDate` in ST during double hour;
* [DST to ST] `now` in ST during double hour, `newDate` in DST during double hour;
* [DST to ST] `now` in ST after double hour, `newDate` in DST during double hour;
* [ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour;
* [ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour.
I think the only missing piece is to find a way to check if a particular date in a non-UTC timezone falls into double hour. By *double hour* I mean a situation caused by changint DST to ST, i.e. setting our clock back an hour (e.g. at 3am to 2am → double hour is between `02:00:00.000` and `02:59:59.999`, which occur both in DST and ST).
```js
/**
* Set time provided in a timezone
*
* @param {Date} [dto.date = new Date()] Date object to work with
* @param {number} [dto.time.h = 0] Hour to set
* @param {number} [dto.time.m = 0] Minute to set
* @param {number} [dto.time.s = 0] Second to set
* @param {number} [dto.time.ms = 0] Millisecond to set
* @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time`
*
* @return {Date} Date object
*/
function setLocalTime(dto = {
date: new Date(),
// TODO: Rename the property to `{h, m, s, ms}`.
time: {h: 0, m: 0, ms: 0, s: 0},
timezone: 'Europe/Bratislava'
}) {
const defaultTime = {h: 0, m: 0, ms: 0, s: 0}
const defaultTimeKeys = Object.keys(defaultTime)
// src: https://stackoverflow.com/a/44118363/3408342
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment')
}
if (!(dto.date instanceof Date)) {
throw Error('`date` must be a `Date` object.')
}
try {
Intl.DateTimeFormat(undefined, {timeZone: dto.timezone})
} catch (e) {
throw Error('`timezone` must be a valid IANA timezone.')
}
if (
typeof dto.time !== 'undefined'
&& typeof dto.time !== 'object'
&& dto.time instanceof Object
&& Object.keys(dto.time).every(v => defaultTimeKeys.indexOf(v) !== -1)
) {
throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.')
}
dto.time = Object.assign({}, defaultTime, dto.time)
const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => {
let offsetString
if (localisedDate) {
offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
} else {
offsetString = new Intl
.DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'})
.formatToParts(date)
.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
}
return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString
}
const pad = (n, len) => `00${n}`.slice(-len)
let [datePart, offset] = dto.date.toLocaleDateString('sv', {
timeZone: dto.timezone,
timeZoneName: 'longOffset'
}).split(/ GMT|\//)
offset = offset.replace(String.fromCharCode(8722), '-')
const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}`
let newDate = new Date(`${newDateWithoutOffset}${offset}`)
const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone})
// Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate`
newDate = newDateTimezoneOffsetHours === offset
? newDate
: new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`)
if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) {
newDate = new Date('')
}
return newDate
}
const timezoneIana = 'Europe/Bratislava'
const tests = [
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
}
// TODO: Add a test of a date in DST and ST on a day on which there is no timezone change (two tests in total, one for DST and another for ST).
]
const results = tests.map(t => {
const newDate = setLocalTime({date: t.now, time: t.time, timezone: timezoneIana})
const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'})
const testResult = newDateString === t.expString
if (testResult) {
console.log(testResult, `: ${t.testName} : ${newDateString}`)
} else {
console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t})
}
return testResult
}).reduce((a, c, i) => {
if (c) {
a.passed++
} else {
a.failed++
a.failedTestIds.push(i)
}
return a
}, {failed: 0, failedTestIds: [], passed: 0})
console.log(results)
``` | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408342/"
] | I created the following function that sets the time in a local timezone, for example, if you have `Date` object and you want to change its time (but not date in a particular timezone, regardless of the UTC date of that time), you provide this function with that `Date` object, the required time, timezone and optionally whether you prefer using the new timezone (see below).
I had to add `preferNewTimezone` parameter because off so-called *double hours* (hours in a non-UTC timezone that occur twice because of setting the clock back by an hour), as those failed to output the date (including timezone offset) I expected.
I don’t say it is fast nor perfect, however, it works. :)
I have created 52 tests of this function in `Europe/Bratislava` timezone. They all pass. I presume it’ll work for any timezone. If not and you find an issue or have an improvement/optimisation, I want to hear about it.
```js
/**
* Set time provided in a timezone
*
* @param {Date} [dto.date = new Date()] Date object to work with
* @param {boolean} [dto.preferNewTimezone = false] Whether to prefer new timezone for double hours
* @param {number} [dto.time.h = 0] Hour to set
* @param {number} [dto.time.m = 0] Minute to set
* @param {number} [dto.time.s = 0] Second to set
* @param {number} [dto.time.ms = 0] Millisecond to set
* @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time`
*
* @return {Date} Date object
*/
function setLocalTime(dto = {
date: new Date(),
preferNewTimezone: false,
time: {h: 0, m: 0, ms: 0, s: 0},
timezone: 'Europe/Bratislava'
}) {
const defaultTime = {h: 0, m: 0, ms: 0, s: 0}
const defaultTimeKeys = Object.keys(defaultTime)
// src: https://stackoverflow.com/a/44118363/3408342
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment')
}
if (!(dto.date instanceof Date)) {
throw Error('`date` must be a `Date` object.')
}
try {
Intl.DateTimeFormat(undefined, {timeZone: dto.timezone})
} catch (e) {
throw Error('`timezone` must be a valid IANA timezone.')
}
if (
typeof dto.time !== 'undefined'
&& typeof dto.time !== 'object'
&& dto.time instanceof Object
&& Object.keys(dto.time).every(v => defaultTimeKeys.includes(v))
) {
throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.')
}
dto.time = Object.assign({}, defaultTime, dto.time)
/**
* Whether a date falls in double hour in a particular timezone
*
* @param {Date} dto.date Date
* @param {string} dto.timezone IANA timezone
* @return {boolean} `true` if the specified Date falls in double hour in a particular timezone, `false` otherwise
*/
const isInDoubleHour = (dto = {date: new Date(), timezone: 'Europe/Bratislava'}) => {
// Get hour in `dto.timezone` of timezones an hour before and after `dto.date`
const hourBeforeHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(new Date(new Date(dto.date).setUTCHours(dto.date.getUTCHours() - 1)))?.[0].value
const hourDateHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(dto.date)?.[0].value
const hourAfterHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(new Date(new Date(dto.date).setUTCHours(dto.date.getUTCHours() + 1)))?.[0].value
return hourBeforeHour === hourDateHour || hourAfterHour === hourDateHour
}
const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => {
let offsetString
if (localisedDate) {
offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
} else {
offsetString = new Intl
.DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'})
.formatToParts(date)
.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
}
return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString
}
/**
* Pad a number with zeros from left to a required length
*
* @param {number} n Number
* @param {number} len Length
* @return {string} Padded number
*/
const pad = (n, len) => `00${n}`.slice(-len)
let [datePart, offset] = dto.date.toLocaleDateString('sv', {
timeZone: dto.timezone,
timeZoneName: 'longOffset'
}).split(/ GMT|\//)
offset = offset.replace(String.fromCharCode(8722), '-')
const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}`
let newDate = new Date(`${newDateWithoutOffset}${offset}`)
const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone})
// Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate`
newDate = newDateTimezoneOffsetHours === offset
? newDate
: new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`)
// Invalidate the date in `newDate` when the hour defined by user is not the same as the hour of `newDate` formatted in the user-defined timezone
if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) {
newDate = new Date('')
}
// Check if the user prefers using the new timezone when `newDate` is in double hour
newDate = dto.preferNewTimezone && !isNaN(newDate) && isInDoubleHour({date: newDate, timezone: dto.timezone})
? new Date(`${newDateWithoutOffset}${getTimezoneOffsetHours({date: new Date(new Date(newDate).setUTCHours(dto.date.getUTCHours() + 1)), timezone: dto.timezone})}`)
: newDate
return newDate
}
const timezoneIana = 'Europe/Bratislava'
const tests = [
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '01/01/2023, 03:55:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in ST, `newDate` in ST before `now` [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '01/01/2023, 12:00:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in ST, `newDate` in ST after `now` [prefer new timezone] ',
time: {h: 12}
},
{
expString: '01/07/2023, 03:55:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in DST, `newDate` in DST before `now` [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '01/07/2023, 12:00:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in DST, `newDate` in DST after `now` [prefer new timezone] ',
time: {h: 12}
},
{
expString: '01/01/2023, 03:55:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in ST, `newDate` in ST before `now` [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '01/01/2023, 12:00:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in ST, `newDate` in ST after `now` [don\'t prefer new timezone]',
time: {h: 12}
},
{
expString: '01/07/2023, 03:55:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in DST, `newDate` in DST before `now` [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '01/07/2023, 12:00:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in DST, `newDate` in DST after `now` [don\'t prefer new timezone]',
time: {h: 12}
}
]
const results = tests.map(t => {
const newDate = setLocalTime({date: t.now, preferNewTimezone: t.preferNewTimezone, time: t.time, timezone: timezoneIana})
const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'})
const testResult = newDateString === t.expString
if (testResult) {
console.log(testResult, `: ${t.testName} : ${newDateString}`)
} else {
console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t})
}
return testResult
}).reduce((a, c, i) => {
if (c) {
a.passed++
} else {
a.failed++
a.failedTestIds.push(i)
}
return a
}, {failed: 0, failedTestIds: [], passed: 0})
console.log(results)
``` | In JavaScript the `Date` objects usually expect time definitions in the local (browser) time and store it in UTC time. You can explicitly set a
time in the UTC timezone with the `.setUTC<time part>()` methods. You can set the time `hours` for the timezone GMT+2 by using the `.setUTCHours()` function with an argument of `hours-2`.
```js
const d=new Date(),hours=10,minutes=40;
d.setUTCHours(hours-2);d.setUTCMinutes(minutes);
console.log("GMT/UTC:",d); // UTC time ("Z")
console.log("New York:",d.toLocaleString("en-US",{timeZone:"America/New_York"})); // local time US
console.log("Berlin:",d.toLocaleString("de-DE",{timeZone:"Europe/Berlin"})); // local time Germany (GMT+2)
```
The method `.setUTCMinutes()` and `setMinutes()` will in most cases achieve the same result. One notable exception is the time zone "Asia/Kolkata" which will apply a 30 minutes offset. |
74,243,879 | I want to use UTC dates in my Node.js backend app, however, I need to be able to set time (hours and minutes) in a local/user-specified timezone.
I am looking for a solution in either pure JS or using `dayjs`. I am not looking for a solution in `moment`.
It seemed like using `dayjs` I could solve this problem quite easily, however, I could not find a way to accomplish this.
I can use UTC timezone by using [`dayjs.utc()`](https://day.js.org/docs/en/plugin/utc) or using [`dayjs.tz(someDate, 'Etc/UTC')`](https://day.js.org/docs/en/timezone/timezone).
When using `dayjs.utc()`, I cannot use/specify other timezones for *anything*, therefore I could not find a way to tell `dayjs` I want to set hours/minutes in a particular (non-UTC) timezone.
When using `dayjs.tz()`, I still cannot define a timezone of time I want to set to a particular date.
### Example in plain JS
My locale timezone is `Europe/Slovakia` (CEST = UTC+02 with DST, CET = UTC+1 without DST), however, I want this to work with any timezone.
```js
// Expected outcome
// old: 2022-10-29T10:00:00.000Z
// new time: 10h 15m CEST
// new: 2022-10-29T08:15:00.000Z
// Plain JS
const now = new Date('2022-10-29T10:00:00.000Z')
const hours = 10
const minutes = 15
now.setHours(10)
now.setMinutes(15)
// As my default timezone is `Europe/Bratislava`, it seems to work as expected
console.log(now)
// Output: 2022-10-29T08:15:00.000Z
// However, it won't work with timezones other than my local timezone
```
### (Nearly) a solution
***Update: I posted a working function in [this answer](https://stackoverflow.com/a/74245936/3408342).***
The following functions seems to work for most test cases, however, it fails for 6 4 cases known to me (any help is greatly appreciated):
* [DST to ST] `now` in DST before double hour, `newDate` in ST during double hour;
* [DST to ST] `now` in DST during double hour, `newDate` in ST during double hour;
* [DST to ST] `now` in ST during double hour, `newDate` in DST during double hour;
* [DST to ST] `now` in ST after double hour, `newDate` in DST during double hour;
* [ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour;
* [ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour.
I think the only missing piece is to find a way to check if a particular date in a non-UTC timezone falls into double hour. By *double hour* I mean a situation caused by changint DST to ST, i.e. setting our clock back an hour (e.g. at 3am to 2am → double hour is between `02:00:00.000` and `02:59:59.999`, which occur both in DST and ST).
```js
/**
* Set time provided in a timezone
*
* @param {Date} [dto.date = new Date()] Date object to work with
* @param {number} [dto.time.h = 0] Hour to set
* @param {number} [dto.time.m = 0] Minute to set
* @param {number} [dto.time.s = 0] Second to set
* @param {number} [dto.time.ms = 0] Millisecond to set
* @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time`
*
* @return {Date} Date object
*/
function setLocalTime(dto = {
date: new Date(),
// TODO: Rename the property to `{h, m, s, ms}`.
time: {h: 0, m: 0, ms: 0, s: 0},
timezone: 'Europe/Bratislava'
}) {
const defaultTime = {h: 0, m: 0, ms: 0, s: 0}
const defaultTimeKeys = Object.keys(defaultTime)
// src: https://stackoverflow.com/a/44118363/3408342
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment')
}
if (!(dto.date instanceof Date)) {
throw Error('`date` must be a `Date` object.')
}
try {
Intl.DateTimeFormat(undefined, {timeZone: dto.timezone})
} catch (e) {
throw Error('`timezone` must be a valid IANA timezone.')
}
if (
typeof dto.time !== 'undefined'
&& typeof dto.time !== 'object'
&& dto.time instanceof Object
&& Object.keys(dto.time).every(v => defaultTimeKeys.indexOf(v) !== -1)
) {
throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.')
}
dto.time = Object.assign({}, defaultTime, dto.time)
const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => {
let offsetString
if (localisedDate) {
offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
} else {
offsetString = new Intl
.DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'})
.formatToParts(date)
.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
}
return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString
}
const pad = (n, len) => `00${n}`.slice(-len)
let [datePart, offset] = dto.date.toLocaleDateString('sv', {
timeZone: dto.timezone,
timeZoneName: 'longOffset'
}).split(/ GMT|\//)
offset = offset.replace(String.fromCharCode(8722), '-')
const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}`
let newDate = new Date(`${newDateWithoutOffset}${offset}`)
const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone})
// Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate`
newDate = newDateTimezoneOffsetHours === offset
? newDate
: new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`)
if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) {
newDate = new Date('')
}
return newDate
}
const timezoneIana = 'Europe/Bratislava'
const tests = [
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
}
// TODO: Add a test of a date in DST and ST on a day on which there is no timezone change (two tests in total, one for DST and another for ST).
]
const results = tests.map(t => {
const newDate = setLocalTime({date: t.now, time: t.time, timezone: timezoneIana})
const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'})
const testResult = newDateString === t.expString
if (testResult) {
console.log(testResult, `: ${t.testName} : ${newDateString}`)
} else {
console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t})
}
return testResult
}).reduce((a, c, i) => {
if (c) {
a.passed++
} else {
a.failed++
a.failedTestIds.push(i)
}
return a
}, {failed: 0, failedTestIds: [], passed: 0})
console.log(results)
``` | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408342/"
] | The following follows your method of getting the date and offset in the target timezone then using it with the time parts to generate a timestamp that is parsed by the built–in parser.
It doesn't fix the issue of the initial date and the result crossing an offset (likely DST), it's just a bit less code. You really should use a suitable library.
E.g.
```js
function setLocalTime(
date = new Date(),
time = {h: 0, m: 0, s: 0, ms: 0},
tz = 'Europe/Bratislava') {
let {h, m, s, ms} = time;
let z = (n,len) => ('00'+n).slice(-len);
let [datePart, offset] = date.toLocaleDateString('sv', {
timeZone:tz, timeZoneName:'longOffset'
}).split(' GMT');
let timestamp = `${datePart}T` +
`${z(h||0,2)}:${z(m||0,2)}:${z(s||0,2)}.${z(ms||0,3)}` +
`${offset.replace(String.fromCharCode(8722),'-')}`;
return new Date(timestamp);
}
let tz, d;
tz = 'Europe/Bratislava';
d = setLocalTime(new Date(), {h: 15, m: 30, s: 0, ms: 0}, tz);
console.log('UTC: ' + d.toISOString());
console.log(tz + ': ' + d.toLocaleString('en-gb',{timeZone: tz, timeZoneName: 'long'}));
tz = 'America/New_York';
d = setLocalTime(new Date(), {h: 15, m: 30, s: 0, ms: 0}, tz);
console.log('UTC: '+ d.toISOString());
console.log(tz + ': ' + d.toLocaleString('en-gb',{timeZone: tz, timeZoneName: 'long'}));
```
In Safari, "−" character (charCode 8722) in a negative offset isn't parsed correctly so it's replaced with a hyphen. Also, `timeZoneName:'longOffset'` may not be that widely supported yet. | In JavaScript the `Date` objects usually expect time definitions in the local (browser) time and store it in UTC time. You can explicitly set a
time in the UTC timezone with the `.setUTC<time part>()` methods. You can set the time `hours` for the timezone GMT+2 by using the `.setUTCHours()` function with an argument of `hours-2`.
```js
const d=new Date(),hours=10,minutes=40;
d.setUTCHours(hours-2);d.setUTCMinutes(minutes);
console.log("GMT/UTC:",d); // UTC time ("Z")
console.log("New York:",d.toLocaleString("en-US",{timeZone:"America/New_York"})); // local time US
console.log("Berlin:",d.toLocaleString("de-DE",{timeZone:"Europe/Berlin"})); // local time Germany (GMT+2)
```
The method `.setUTCMinutes()` and `setMinutes()` will in most cases achieve the same result. One notable exception is the time zone "Asia/Kolkata" which will apply a 30 minutes offset. |
199,880 | Is there any way to show a calculated field when I'm filling out a new item for a list?
For example:
If I select "Blue" in field1, and "Bird" in field2,
then, on the same page where I am filling in information, I can see field3(Calculated field) show a value of "Blue Jay"
Currently, the calculated field doesn't show until I add a new item.
It would be even better if the update was in real time, though I don't expect that. | 2016/11/17 | [
"https://sharepoint.stackexchange.com/questions/199880",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61825/"
] | **As a short answer** : unfortunately , No, the calculated field is calculated after the item added or updated
If you are using Enterprise Edition of SharePoint then try editing list form with InfoPath and insert field which will do the calculation for you. Make that field read-only and then publish the form.
In InfoPath , You can
* Add a Textbox as `field3` in your form
* At `field2` add new a `Action rule` and at **run these action select** `set a fields value`
* At **Field** Value select Field3
* At **Value** concatenate your `field1` and `field2`
[![enter image description here](https://i.stack.imgur.com/SN6jP.gif)](https://i.stack.imgur.com/SN6jP.gif) | Calculated columns don't work that way, they are visible on the display form only or in views and only recalculate when items are edited.
If you want that type of preview feature, you'll have to incorporate custom javascript on your forms. |
77,133 | There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite?
Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right)
If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible.
Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome!
Thanks for your time :) | 2009/11/30 | [
"https://superuser.com/questions/77133",
"https://superuser.com",
"https://superuser.com/users/19668/"
] | OK, hopefully supplying a *useful* answer this time, instead of the inverse of the actual answer you wanted...
How about an AutoHotkey script for [mouse gestures](http://www.autohotkey.com/docs/scripts/MouseGestures.htm)? You haven't indicated what sort of control you require, so perhaps a set of gestures is adequate. If, however, you're looking to essentially replace the whole keyboard with one mouse, well, this may not be the answer you need. Or, good luck memorizing all those gestures. :-D
---
As is so often the case, [AutoHotkey](http://www.autohotkey.com) is your tool. I won't bore you with extensive review or details, as Google (and even SuperUser) are loaded with info about it.
EDIT: In fact, here's a [ready-made script](http://www.autohotkey.com/docs/scripts/NumpadMouse.htm) that'll enable you to use your numeric keypad as a mouse, with several customizations. | If you want something where you can type with your mouse, then I suggest you take a look at [Dasher](http://www.inference.phy.cam.ac.uk/dasher/).
That is, if I take your question title as the question. As I really don't quite understand your question. |
77,133 | There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite?
Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right)
If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible.
Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome!
Thanks for your time :) | 2009/11/30 | [
"https://superuser.com/questions/77133",
"https://superuser.com",
"https://superuser.com/users/19668/"
] | If you're on Windows, what about the On-Screen Keyboard?
It's found under **All Programs -> Accessories -> Accessibility** on XP (similar for Vista+)
![alt text](https://i.stack.imgur.com/nPFOE.png) | If you want something where you can type with your mouse, then I suggest you take a look at [Dasher](http://www.inference.phy.cam.ac.uk/dasher/).
That is, if I take your question title as the question. As I really don't quite understand your question. |
77,133 | There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite?
Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right)
If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible.
Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome!
Thanks for your time :) | 2009/11/30 | [
"https://superuser.com/questions/77133",
"https://superuser.com",
"https://superuser.com/users/19668/"
] | OK, hopefully supplying a *useful* answer this time, instead of the inverse of the actual answer you wanted...
How about an AutoHotkey script for [mouse gestures](http://www.autohotkey.com/docs/scripts/MouseGestures.htm)? You haven't indicated what sort of control you require, so perhaps a set of gestures is adequate. If, however, you're looking to essentially replace the whole keyboard with one mouse, well, this may not be the answer you need. Or, good luck memorizing all those gestures. :-D
---
As is so often the case, [AutoHotkey](http://www.autohotkey.com) is your tool. I won't bore you with extensive review or details, as Google (and even SuperUser) are loaded with info about it.
EDIT: In fact, here's a [ready-made script](http://www.autohotkey.com/docs/scripts/NumpadMouse.htm) that'll enable you to use your numeric keypad as a mouse, with several customizations. | If you're on Windows, what about the On-Screen Keyboard?
It's found under **All Programs -> Accessories -> Accessibility** on XP (similar for Vista+)
![alt text](https://i.stack.imgur.com/nPFOE.png) |
95,407 | I was playing some math games intended for children, in Japanese, and the subject was 引き算.
The isolated question came up "14は10といくつ?" In the context of 引き算 it makes sense that the answer turned out to be 4, but I don't understand the question structurally. How does it imply "If you take 10 away from 14, what's left?" Is this to be understood only in the context? Assuming the と is conditional, my rough translation is "As for 14... if (you take away) 10... how much(left)?" with everything in parenthesis being only implied. Is this correct? Are the は and と particles doing what I think? | 2022/07/15 | [
"https://japanese.stackexchange.com/questions/95407",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/41549/"
] | >
> Is this to be understood only in the context? Assuming the と is conditional
>
>
>
The と is not conditional, and you can tell that from the word followed by the と.
**The conditional と should follow 活用語の終止形/the terminal form of a conjugatable word**, such as verb, i/na-adjective, auxiliary, eg 「話す」「寒い」「静かだ」「〇〇だ」「~ない」. It *cannot* follow a 体言(unconjugatable word).
>
> Eg.
>
> **食べると**太ってしまう
>
> **明るいと**眠れない
>
> **静かだと**勉強がはかどる
>
> 佐藤さんが**いないと**困る
>
>
>
When と is attached to a 体言 (unconjugatable word) as in your example where と is attached to 「10」, it should be the case particle (格助詞).
The case particle と can attach to words of various part-of-speech (because of its quotative usage). It can be used for saying "~ and ~" (enumeration), "with (someone)", (same/different) as/from..." (comparison), "(saying) that..."(quotation), etc., as you probably know.
>
> Eg.
>
> **13と**14 -- "~ and ~" ← と follows 体言
>
> **リンゴとバナナと**ヨーグルト -- "~ and ~" ← と follows 体言
>
> **妹と**一緒に勉強する -- "with (someone)" ← と follows 体言
>
> **山田さんと**同じクラス -- "(same) as ~" ← と follows 体言
>
> いや**だと**言う -- "(say) that..." ← と can follow various words
>
>
>
And as you can see, と in the sense "~ and ~" would make the most sense in your example.
---
>
> "14**は**10**と**いくつ?"
>
>
>
I'd say the は is the topic marker, or the thematic は (主題の「は」).
>
> *lit.* **As for** 14, 10 **and** how many (is it)?
>
>
> | I think it is an odd way to ask, but the structure is:
* 14 は 10 と いくつ
* 14 = 10 + ?
so that it is essentially a subtraction.
Grammatically, は is the subject marker and と is *and* (In words, *14 is 10 and how many?*) |
57,779,158 | I am using material-ui for my project and I have a need to get the selected text (not the value) and do some parsing. I can't seem to find a way to do this.
Here is what my component looks like:
```
<TextField
select
margin="dense"
label="Name"
variant="outlined"
className={classes.textField}
value={values.nameId}
onChange={handleChange('nameId')}
>
{names.map(row => (
<MenuItem key={row.Id} value={row.Id}>{row.Name}</MenuItem>
))}
</TextField>
```
handler looks like this:
```
const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value });
};
```
Obviously event.target.value gets my selected value, but I want to also get the selected innerText of the selected index. Any ideas? | 2019/09/03 | [
"https://Stackoverflow.com/questions/57779158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8484824/"
] | This regex match should get you what you're looking for
```js
let regex = /1-[0-9]{3}-[0-9]{3}-[0-9]{4}/
``` | Try
```
let candidateValue = getMeSomeValue();
const isValid = (candidateValue || "").match( /^1-[0-9]{3}-[0-9]{4}$/ );
```
Add `\s` following the `^` and before the `$` if you want to play nice and ignore leading/trailing whitespace. |
195,501 | Is it coherent to suggest that it is possible to iterate, one-by-one, through every single item in an infinite set? Some have suggested that it is possible to iterate (or count) completely through an infinite set with no start (or lower bound), making infinite regress a genuinely possible reality.
Mathematically, is this possible?
I don't know much about math proofs, so the more basic (with the least symbols) you can keep your answer, the more likely I will understand and appreciate it.
Thank you very much!
ADDENDUM
When I write an infinite loop into my computer code, the code begins to execute and will never complete it's looping (unless it crashes or I stop it). I am wondering if it is mathematically possible, adding one to another, to ever arrive at the completion of an infinite set, like the set of negative integers, or will it continue permanently? | 2012/09/14 | [
"https://math.stackexchange.com/questions/195501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/40191/"
] | We may count through the integers by listing them $0,1,-1,2,-2,\dots$. This is an infinite set without a lower bound. In general, if you have a bijection $f:\mathbb{N} \to X$ where $X$ is an infinite set, then you can "iterate" through them by listing $f(1),f(2),f(3), \dots$. | Here is a way to iterate... To me, it is like mixing math and computers. You can find the ideas described in much more detail in [Generatingfunctionology by Wilf](http://www.math.upenn.edu/~wilf/gfology2.pdf). Knowing Calculus is very helpful for this.
Let me explain. We would like to iterate through infinity and stop. To do this, we will use a function that is like a set. It is called a "generating function". You can find a description in more advanced English [here](http://en.wikipedia.org/wiki/Generating_function). The idea is that we use numbers (integers) to give order to the set. (This makes it a sequence). We start with the number 0 (like people often do with computers) and give it a value from the set. Suppose we give it the value 53. Then we say this as a generating function by saying $f(x)$, our function of $x$, is equal to $53 x^0$:
$$f(x) = 53x^0$$
It is like a power series, if you are familiar with calculus. We raise $x$ to the 0th power, and then multiply it by 53. If we want to add a second number, say 42, we use $x$ to the first power:
$$f(x) = 53 x^0 + 42 x^1$$
The idea is that the powers of $x$ let us order the numbers. This also helps us seperate the numbers. If we add the numbers 8, 71, and 32, can you guess how to write this? The answer is:
$$f(x) = 53x^0 + 42x^1 + 8x^2 + 71x^3 + 32x^4$$
I hope this idea is clear. Now we want to create an infinite series. To do this, many people study [power series](http://en.wikipedia.org/wiki/Power_series). Many Calculus books study these. For example, a common one is:
$$f(x) = 1x^0 + 1x^1 + 1x^2 + 1x^3 + \dots$$
This is an like an infinite set of ones. It can be written as:
$$\frac{1}{1-x} = 1x^0 + 1x^1 + 1x^2 + 1x^3 + \dots$$
This means that the fraction on the left side is the same as the right side of the equals sign.
They are a function. The type of function is again a generating function.
The series of ones was given as:
$$\frac{1}{1-x} = 1x^0 + 1x^1 + 1x^2 + 1x^3 + \dots$$
Set $x$ to some value, and you will have iterated through an infinite amount of values. The result may be somewhat suprising, so I'll leave it up to you to pick a value. Remember that you can't divide by zero, so you'll have to be careful to avoid that. The study of Calculus and, in particular, limits helps provide a solution to that problem. |
69,581,492 | I have string column in my `df` table, like this below:
```
d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']}
df = pd.DataFrame(data=d)
df
```
[![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png)
I would like to convert this column, so that all values contain two decimal places, but **without changing the type of this column to numeric type**.
Expected output - a string column with values:
[![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png)
I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work.
Do you have idea how to handle it? | 2021/10/15 | [
"https://Stackoverflow.com/questions/69581492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16734748/"
] | Like this:
```
df['col1'] = df['col1'].astype(float).map('{:,.2f}'.format).astype(str)
```
If you have '' in this column you better replace them before to '0'. | This one will work no matter how many columns are in your dictionary.
Try this:
```py
d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9' '', '2.3']}
for x in d:
for y in range(0,len(d[x])):
d[x][y]=d[x][y].ljust(4,"0")
print(d)
``` |
This is a processed version of the HuggingFaceH4/stack-exchange-preferences
. The following steps were applied:
markdownify
(response_j, response_k)
where j was rated better than kThis dataset is designed to be used for preference learning. The processing notebook is in the repository as well.