prompt
stringlengths 48
2.37k
| chosen
stringlengths 7
4.28k
| rejected
stringlengths 11
4.44k
|
---|---|---|
Question: 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?)
Answer: | >
> 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. |
Question: 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?)
Answer: | *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. |
Question: 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?)
Answer: | >
> 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. |
Question: 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?)
Answer: | *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. |
Question: ```
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?
Answer: | 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. |
Question: ```
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?
Answer: | 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. |
Question: ```
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?
Answer: | ```
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. |
Question: ```
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?
Answer: | ```
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. |
Question: 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.
Answer: | 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! |
Question: 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?
Answer: | 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. |
Question: **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.
Answer: | 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. |
Question: 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'
}
```
Answer: | 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. |
Question: 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'
}
```
Answer: | 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. |
Question: 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'
}
```
Answer: | 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>
``` |
Question: 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?
Answer: | 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
``` |
Question: 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?
Answer: | 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. |
Question: 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?
Answer: | 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). |
Question: 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?
Answer: | 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). |
Question: ![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"
Answer: | 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. |
Question: ![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"
Answer: | 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.) |
Question: ![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"
Answer: | 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. |
Question: ![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"
Answer: | 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`. |
Question: ![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"
Answer: | 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. |
Question: ![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"
Answer: | 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. |
Question: ![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"
Answer: | 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. |
Question: ![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"
Answer: | 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`. |
Question: ![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"
Answer: | 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. |
Question: 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?
Answer: | 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;`. |
Question: 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?
Answer: | 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. |
Question: 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?
Answer: | 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. |
Question: 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$.
Answer: | 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. |
Question: 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$.
Answer: | 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$ |
Question: 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$.
Answer: | **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$ |
Question: 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.
Answer: | **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. |
Question: 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 :)
Answer: | 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. |
Question: 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 :)
Answer: | 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. |
Question: 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 :)
Answer: | 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) |
Question: 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?
Answer: | >
> 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?*) |
Question: 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?
Answer: | 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. |
Question: 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?
Answer: | 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. |
Question: 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?
Answer: | 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)
``` |
Question: 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?
Answer: | Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html):
```
df['col1'] = df['col1'].str.ljust(4, '0')
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5 2.30
```
To leave empty rows intact:
```
df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0'))
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5
6 2.30
```
NB. to get the max string length: `df['col1'].str.len().max()` -> `4` | 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'. |
Question: 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?
Answer: | 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'. | You can easily use the `round` or `format` function. In your specific case, using `format`, you can write something like this:
```
d = ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']
for i in range(len(d)):
if d[i] == '':
d[i] = '0'
d[i] = "{:.2f}".format(float(d[i]))
print ('col1', d)
```
output:
```
'col1', ['1.20', '3.40', '1.99', '0.14', '2.90', '0.00', '2.30']
``` |
Question: 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?
Answer: | Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html):
```
df['col1'] = df['col1'].str.ljust(4, '0')
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5 2.30
```
To leave empty rows intact:
```
df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0'))
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5
6 2.30
```
NB. to get the max string length: `df['col1'].str.len().max()` -> `4` | 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)
``` |
Question: 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?
Answer: | Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html):
```
df['col1'] = df['col1'].str.ljust(4, '0')
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5 2.30
```
To leave empty rows intact:
```
df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0'))
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5
6 2.30
```
NB. to get the max string length: `df['col1'].str.len().max()` -> `4` | You can easily use the `round` or `format` function. In your specific case, using `format`, you can write something like this:
```
d = ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']
for i in range(len(d)):
if d[i] == '':
d[i] = '0'
d[i] = "{:.2f}".format(float(d[i]))
print ('col1', d)
```
output:
```
'col1', ['1.20', '3.40', '1.99', '0.14', '2.90', '0.00', '2.30']
``` |
Question: Sorry the title's so convoluted... I must've tried for ten minutes to get a good, descriptive title! Basically, here's the scenario.
Let's say a user can pick fifty different hat colors and styles to put on an avatar. The avatar can move his head around, so we'd need the same types of movements in the symbol for when that happens.
Additionally, it gets which hat should be on the 'avatar' from a database. The problem is that we can't just make 50 different frames with a different hat on each. And each hat symbol will have the same movements, it'll just be different styles, colors and sizes.
So how can I make one variable that is the HAT, that way we can just put the appropriate hat symbol into the variable and always be able to call Hat.gotoAndplay('tip\_hat') or any other generic functions.... Does that make sense?
Hope that's not too confusing. Sorry, I'm not great at the visual Flash stuff, but it's gotta be done! Thanks!
Answer: | [debu's suggestion](https://stackoverflow.com/questions/2435039/best-way-to-be-able-to-pick-multiple-colors-designs-of-symbols-dynamically-from-f/2435101#2435101) about a hat container makes sense in order to separate out control of the hat movement.
You could take this further by separating out different aspects of the appearance of each hat (not just the colours, but also style, pattern, size, orientation etc) - this would allow you produce a wide variety of different hats from just a few parameters.
So for example 6 styles x 4 patterns x 8 colours = 192 different hats (without having to draw each one!)
[![parametric hats diagram](https://i.stack.imgur.com/dHyh6.jpg)](https://i.stack.imgur.com/dHyh6.jpg)
(source: [webfactional.com](http://roi.webfactional.com/img/so/hats.jpg)) | You could do that a number of ways; firstly you could have each different hat as a different symbol in the Flash Library (if you're using the IDE), and then in their properties tick to 'Export for Actionscript', and choose some appropriate name. It'll tell you that there's no definition for the class path, and one will be created automatically (or something), but that's no problem as you don't need to create a class file for these objects - they're simply MovieClip extensions with some specific data in them.
So if you do that with each hat, let's say you name them Hat\_1, Hat\_2, etc; then you need to create a 'hat' object inside your avatar's head object. Whenever the hat is changed, you call a new instance of that specific hat object, and put it on the stage:
```
//when user chooses a hat, however this is done:
var newHat:Hat_1 = new Hat_1();
avatarBody.avatarHead.hat.addChild(newHat);
```
Then that hat symbol gets added to the hat object of your avatar, and will move with the head object as you'd expect. You can change up the hat on the fly, by simply calling a different hat type and removing the previous one.
Alternatively you could do it by loading in the hat symbols from external images, and storing them in variables for when they need to be added to the avatar object. You'd do this using XML; if you don't know how that's done, I can explain. |
Question: I am writing an application, running on a server, where multiple users access data from a database which is AES encrypted with a master secret. The master secret itself is initially randomly generated, and then AES encrypted with a user-secret to yield a 'user-hash'. The master secret is never stored, but the user-hash is stored in a database.
When a user enters his user-secret, the user-hash is decrypted to temporarily (on the fly) yield the master-secret which is used to decrypt the data. The data is then send to the user.
If a user is deleted, the user-hash is deleted. He may have saved decrypted data, but cannot decrypt further data.
The question is: How safe is the master-secret in this constellation? If the database is compromised, an attacker has access to the user-hash and the encrypted data. If the attacker was a user, he may also have decrypted data. Will he then be able to break the master-secret?
Answer: | If a user has a copy of both the encrypted and decrypted data, he is in a position to perform at least a [known-plaintext attack](http://en.wikipedia.org/wiki/Known-plaintext_attack). If users can submit arbitrary plaintexts for encryption, they can conduct a [chosen-plaintext attack](http://en.wikipedia.org/wiki/Chosen-plaintext_attack), which is stronger. In a chosen-plaintext attack, the attacker can submit any number of plaintexts and can retrieve the corresponding ciphertext.
All reasonable encryption algorithms are resistant to chosen-plaintext attacks, and AES is considered a reasonable encryption algorithm. Someone in possession of some (plaintext, ciphertext) pairs cannot encrypt or decrypt other messages (except sometimes messages derived from the known messages if a bad mode is used). In particular, no matter how many known plaintexts and ciphertexts the attacker is, he has no method to obtain the key that is better than brute force (trying all possible $2^{128}$ keys).
Do note that deleting the private secret does not delete the master secret. The master secret can still be recovered from backup copies of the private secret that weren't deleted, from other users' private secret, or from extant copies of the master secret. | Your master secret is **never** secure, at least not as you have described it. As a user, I know my private secret. When I use your application, my private secret decrypts the master secret right there in the application. With modest technical skills, I can examine the memory of the process or machine and read the master secret in plaintext any time I wish. I can retain that master secret forever, and the administrator will never know.
To solve this, I expect you are relying on the master secret being secured on a different platform than the one the users are logged into. Your problem has now expanded and shifted to securely communicating the users' secrets to the secure platform. To accomplish that, you need an authentication mechanism. Once you have solved that, there becomes less need for the double encryption as you have defined it - simply authenticate user access to the platform, and revoke it as needed. The platform can own the master secret if on-disk encryption is desired. The user never has to access it directly.
A different approach is that you can allow users to encrypt data locally (using public key cryptography to encrypt a random AES key) but they can never decrypt it themselves. That job is performed only on the server. |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | 1. Feller's first volume for Probability Theory.
2. Arnold's ODE for differential equations.
3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis | It's a bit more advanced than the topics you asked about, but Milnor's *Morse Theory* and Milnor and Stasheff's *Characteristic Classes* are astoundingly good. (There's a pattern here: Milnor's *Lectures on the h-Cobordism Theorem* is pretty good too!)
At a somewhat lower level, I find Spivak's *Calculus* (which many might argue is an introductory analysis book) pretty darned wonderful. |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples.
For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end. | It's a bit more advanced than the topics you asked about, but Milnor's *Morse Theory* and Milnor and Stasheff's *Characteristic Classes* are astoundingly good. (There's a pattern here: Milnor's *Lectures on the h-Cobordism Theorem* is pretty good too!)
At a somewhat lower level, I find Spivak's *Calculus* (which many might argue is an introductory analysis book) pretty darned wonderful. |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | 1. Feller's first volume for Probability Theory.
2. Arnold's ODE for differential equations.
3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis | The Mathematical Association of America (MAA) has got a rich collection of classic books under Doclani Mathematical Expositions. I would suggest you following:
$1$. Mathematical Gems Series ($3$ Volumes) By Ross Honsburger.
$2$. Linear Algebra problem book By Paul R Halmos.
$3$. Euler: Master of us all By William Dunham.
Some other texts:
$1$ Introduction to Commutative Algebra by Atiyah and MacDonald.
$2$ A book of abstract algebra by Pinter. |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples.
For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end. | The Mathematical Association of America (MAA) has got a rich collection of classic books under Doclani Mathematical Expositions. I would suggest you following:
$1$. Mathematical Gems Series ($3$ Volumes) By Ross Honsburger.
$2$. Linear Algebra problem book By Paul R Halmos.
$3$. Euler: Master of us all By William Dunham.
Some other texts:
$1$ Introduction to Commutative Algebra by Atiyah and MacDonald.
$2$ A book of abstract algebra by Pinter. |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | 1. Feller's first volume for Probability Theory.
2. Arnold's ODE for differential equations.
3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis | In the early '70s, I used two teaching books that I consider ''classic'':
*Foundations of modern analysis* of J. Dieudonné (at least in Europe).
*Algebra* of S. Mac Lane and G. Birkoff
At a different level, I think that an ''evergreen'' is:
*Methods of Mathematical physics* of R. Courant and D. Hilbert. |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples.
For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end. | 1. Feller's first volume for Probability Theory.
2. Arnold's ODE for differential equations.
3. Cartan's Elementary Theory of Analytic Functions of One or Several Complex Variables for Complex Analysis |
Question: In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc.
Answer: | I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples.
For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end. | In the early '70s, I used two teaching books that I consider ''classic'':
*Foundations of modern analysis* of J. Dieudonné (at least in Europe).
*Algebra* of S. Mac Lane and G. Birkoff
At a different level, I think that an ''evergreen'' is:
*Methods of Mathematical physics* of R. Courant and D. Hilbert. |
Question: I'm using the [jQuery Validate Plugin](http://jqueryvalidation.org/validate) and I want to be able to hide the error messages next to my inputs and have a main error message at the bottom, I have this working kind of but the error messages are showing next to my input fields. (Obviously I would clean up the styling if i was using it).
As you can see at the bottom it is telling me there are 4 errors see details below.. I want this to stay but not the error messages and styling above?
[![enter image description here](https://i.stack.imgur.com/taT8w.png)](https://i.stack.imgur.com/taT8w.png)
```
$( ".form-group-rules" ).validate({
rules: {
rule_name: {
required: true
},
rule_desc: {
required: false
},
rule_type: {
required: true
},
vali_type: {
required: true
},
tran_type: {
required: true
},
vali_fields: {
required: true
},
acct_sel: {
required: true
}
},
messages: {
rule_name: "Please enter a rule name",
rule_type: "Please select a rule type",
vali_fields: "Please select a validation field",
tran_type: "Please select at least 1 transaction type",
vali_type: "Please select a valiation type",
acct_sel: "Please select at least 1 account"
},
showErrors: function(errorMap, errorList) {
$(".error-container").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
```
Answer: | May be use the Validator method
```
errorPlacement: function(error,element) {
return true;
}
```
It will not append the error to the inputs. | You can hide the error messages with CSS:
```
span.error {
display: none;
}
``` |
Question: I'm using the [jQuery Validate Plugin](http://jqueryvalidation.org/validate) and I want to be able to hide the error messages next to my inputs and have a main error message at the bottom, I have this working kind of but the error messages are showing next to my input fields. (Obviously I would clean up the styling if i was using it).
As you can see at the bottom it is telling me there are 4 errors see details below.. I want this to stay but not the error messages and styling above?
[![enter image description here](https://i.stack.imgur.com/taT8w.png)](https://i.stack.imgur.com/taT8w.png)
```
$( ".form-group-rules" ).validate({
rules: {
rule_name: {
required: true
},
rule_desc: {
required: false
},
rule_type: {
required: true
},
vali_type: {
required: true
},
tran_type: {
required: true
},
vali_fields: {
required: true
},
acct_sel: {
required: true
}
},
messages: {
rule_name: "Please enter a rule name",
rule_type: "Please select a rule type",
vali_fields: "Please select a validation field",
tran_type: "Please select at least 1 transaction type",
vali_type: "Please select a valiation type",
acct_sel: "Please select at least 1 account"
},
showErrors: function(errorMap, errorList) {
$(".error-container").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
```
Answer: | May be use the Validator method
```
errorPlacement: function(error,element) {
return true;
}
```
It will not append the error to the inputs. | Normally, `showErrors` will automatically suppress the default messages next to each input element.
You're creating your own issue because **`.defaultShowErrors()` is the method for putting back the default messages**.
Simply remove `this.defaultShowErrors()`...
```
showErrors: function(errorMap, errorList) {
$(".error-container").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors(); // <- REMOVE THIS LINE
}
```
**DEMO: <http://jsfiddle.net/jmdnxedq/>** |
Question: I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
```
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
```
Answer: | If you want to use Gson, then first you declare classes for holding each element and sub elements:
```
public class MyUser {
public String id;
public String username;
}
public class MyElement {
public MyUser user;
public String item_name;
public String custom_field;
}
```
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
```
MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);
```
Then you simply access the elements of `data`.
The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item\_name" etc. | If your trying to serialize/deserialize json in Java I would recommend using Jackson. <http://jackson.codehaus.org/>
Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.
Jackson provides annotations that can be attached to your class which make deserialization pretty simple. |
Question: I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
```
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
```
Answer: | If you want to use Gson, then first you declare classes for holding each element and sub elements:
```
public class MyUser {
public String id;
public String username;
}
public class MyElement {
public MyUser user;
public String item_name;
public String custom_field;
}
```
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
```
MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);
```
Then you simply access the elements of `data`.
The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item\_name" etc. | You could try JSON Simple
<http://code.google.com/p/json-simple/>
Example:
```
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
//Access data with obj.get("item_name")
}
```
Just be careful to check for nulls/be careful with casting and such. |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | **Update:**
In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html).
**Original Workaround/fix:**
Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`:
```
MachineOptions = [
"amazonec2-access-key=xxx",
"amazonec2-secret-key=xxx",
"amazonec2-region=eu-central-1",
"amazonec2-vpc-id=vpc-xxx",
"amazonec2-subnet-id=subnet-xxx",
"amazonec2-use-private-address=true",
"amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true",
"amazonec2-security-group=ci-runners",
"amazonec2-instance-type=m5.large",
"amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1
"amazonec2-request-spot-instance=true",
"amazonec2-spot-price=0.045"
]
```
You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements).
**Explanation:**
The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run.
See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue.
[Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems. | I had the same issue since yesterday.
It could be related to GitLab releasing 15.0 with breaking changes (going `live on GitLab.com sometime between April 23 – May 22`)
* <https://about.gitlab.com/blog/2022/04/18/gitlab-releases-15-breaking-changes/>
* but there is no mention of missing `AMI` field to add to field `MachineOptions`
Adding field `AMI` solved the issue on my side. |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | **Update:**
In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html).
**Original Workaround/fix:**
Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`:
```
MachineOptions = [
"amazonec2-access-key=xxx",
"amazonec2-secret-key=xxx",
"amazonec2-region=eu-central-1",
"amazonec2-vpc-id=vpc-xxx",
"amazonec2-subnet-id=subnet-xxx",
"amazonec2-use-private-address=true",
"amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true",
"amazonec2-security-group=ci-runners",
"amazonec2-instance-type=m5.large",
"amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1
"amazonec2-request-spot-instance=true",
"amazonec2-spot-price=0.045"
]
```
You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements).
**Explanation:**
The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run.
See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue.
[Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems. | Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it
What I did
1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal)
2. select launch instance, choose the region, and copy the ami shown |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | **Update:**
In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html).
**Original Workaround/fix:**
Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`:
```
MachineOptions = [
"amazonec2-access-key=xxx",
"amazonec2-secret-key=xxx",
"amazonec2-region=eu-central-1",
"amazonec2-vpc-id=vpc-xxx",
"amazonec2-subnet-id=subnet-xxx",
"amazonec2-use-private-address=true",
"amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true",
"amazonec2-security-group=ci-runners",
"amazonec2-instance-type=m5.large",
"amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1
"amazonec2-request-spot-instance=true",
"amazonec2-spot-price=0.045"
]
```
You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements).
**Explanation:**
The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run.
See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue.
[Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems. | As Moritz pointed out:
Adding:
```
MachineOptions = [
"amazonec2-ami=ami-02584c1c9d05efa69",
]
```
solves the issue. |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | **Update:**
In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html).
**Original Workaround/fix:**
Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`:
```
MachineOptions = [
"amazonec2-access-key=xxx",
"amazonec2-secret-key=xxx",
"amazonec2-region=eu-central-1",
"amazonec2-vpc-id=vpc-xxx",
"amazonec2-subnet-id=subnet-xxx",
"amazonec2-use-private-address=true",
"amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true",
"amazonec2-security-group=ci-runners",
"amazonec2-instance-type=m5.large",
"amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1
"amazonec2-request-spot-instance=true",
"amazonec2-spot-price=0.045"
]
```
You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements).
**Explanation:**
The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run.
See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue.
[Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems. | Just wanted to add as well, go [here](https://cloud-images.ubuntu.com/locator/ec2/) for the ubuntu that corresponds with your region. Amis are region specific |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | **Update:**
In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html).
**Original Workaround/fix:**
Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`:
```
MachineOptions = [
"amazonec2-access-key=xxx",
"amazonec2-secret-key=xxx",
"amazonec2-region=eu-central-1",
"amazonec2-vpc-id=vpc-xxx",
"amazonec2-subnet-id=subnet-xxx",
"amazonec2-use-private-address=true",
"amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true",
"amazonec2-security-group=ci-runners",
"amazonec2-instance-type=m5.large",
"amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1
"amazonec2-request-spot-instance=true",
"amazonec2-spot-price=0.045"
]
```
You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements).
**Explanation:**
The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run.
See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue.
[Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems. | Using the new AMI worked for a bit but after sometime the /etc/gitlab-runner/config.toml reverted back to old configuration. All the changes made is gone and reset automatically. Anyone have any idea why the config.toml file revert back and how to prevent it ? |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it
What I did
1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal)
2. select launch instance, choose the region, and copy the ami shown | I had the same issue since yesterday.
It could be related to GitLab releasing 15.0 with breaking changes (going `live on GitLab.com sometime between April 23 – May 22`)
* <https://about.gitlab.com/blog/2022/04/18/gitlab-releases-15-breaking-changes/>
* but there is no mention of missing `AMI` field to add to field `MachineOptions`
Adding field `AMI` solved the issue on my side. |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it
What I did
1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal)
2. select launch instance, choose the region, and copy the ami shown | As Moritz pointed out:
Adding:
```
MachineOptions = [
"amazonec2-ami=ami-02584c1c9d05efa69",
]
```
solves the issue. |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it
What I did
1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal)
2. select launch instance, choose the region, and copy the ami shown | Just wanted to add as well, go [here](https://cloud-images.ubuntu.com/locator/ec2/) for the ubuntu that corresponds with your region. Amis are region specific |
Question: I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me?
Answer: | Make sure to select an ami for Ubuntu and not Debian and that your aws account is subscribed to it
What I did
1. subscribe in aws marketplace to a Ubuntu Amazon Image (Ubuntu 20.04 LTS - Focal)
2. select launch instance, choose the region, and copy the ami shown | Using the new AMI worked for a bit but after sometime the /etc/gitlab-runner/config.toml reverted back to old configuration. All the changes made is gone and reset automatically. Anyone have any idea why the config.toml file revert back and how to prevent it ? |
Question: Prestashop 1.6 has some strange functions. One of them is:
```
\themes\my_theme\js\autoload\15-jquery.uniform-modified.js
```
Which add span to radio, input button. For example:
```
<div class="checker" id="uniform-cgv">
<span class="checked">
<input name="cgv" id="cgv" value="1" type="checkbox">
</span>
</div>
```
If this span has class checked then checkbox is checked. the problem is when quest user want buy products without create a account. The user need to provide some information about his self. In the end click on "save" button
```
<button type="submit" name="submitGuestAccount" id="submitGuestAccount" class="btn btn-default button button-medium"><span>Zapisz<i class="icon-chevron-right right"></i></span></button>
```
When I click this button the html is change to:
```
<p class="checkbox">
<input name="cgv" id="cgv" value="1" checked="checked" type="checkbox">
</p>
```
the question is. How can I call function which add span to input field after click on this button. For now I have something like this:
```
$('#submitGuestAccount').click(function () {
});
```
Below I past all content from:
[view-source:https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js](https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js)
Thanks for any help.
Answer: | If you want to get the same checkbox like with uniform you just need to invoke method bindUniform() after your button was handled. I assume that you get an answer after form handling with an ajax response, so you need to add
`if (typeof bindUniform !=='undefined') {
bindUniform();
}`
after you get response and DOM was done. | @Alexander Grosul Thanks again. To fix this issues You need to add this code to any js file.
```
$("select.form-control,input[type='radio'],input[type='checkbox']").uniform();
``` |
Question: Today I noticed that new MVC projects in VS 2012 are using [WebMatrix.WebData.WebSecurity](http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity%28v=vs.99%29.aspx) to handle membership related tasks.
I went to msdn to a quick look at the documentation and was surprised. Lot's of good stuff in there and it will definitely save me a lot of time in future projects.
But one thing got my attention:
It doesn't have a function to "Remove Accounts". Is there a particular reason for that? Should I use the underlying membership provider to remove accounts (and other things such as unlock accounts)?
Answer: | Found the answer at MSDN:
<http://msdn.microsoft.com/en-us/library/webmatrix.webdata.simplemembershipprovider%28v=vs.111%29>
>
> In ASP.NET Web Pages sites, you can access the functionality of the SimpleMembershipProvider class by using the Membership property of a web page. You do not (in fact, cannot) initialize a new instance of the SimpleMembershipProvider class...
>
>
> | `((SimpleMembershipProvider)Membership.Provider).DeleteAccount("UserName");` //This will remove entry from **[webpages\_Membership]** table
`Roles.RemoveUserFromRole("UserName", "RoleName");` // This will remove from **[webpages\_UsersInRoles]** table
`((SimpleMembershipProvider)Membership.Provider).DeleteUser("UserName", true);` // This will remove from **userprofile** table |
Question: Today I noticed that new MVC projects in VS 2012 are using [WebMatrix.WebData.WebSecurity](http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity%28v=vs.99%29.aspx) to handle membership related tasks.
I went to msdn to a quick look at the documentation and was surprised. Lot's of good stuff in there and it will definitely save me a lot of time in future projects.
But one thing got my attention:
It doesn't have a function to "Remove Accounts". Is there a particular reason for that? Should I use the underlying membership provider to remove accounts (and other things such as unlock accounts)?
Answer: | ```
((SimpleMembershipProvider)Membership.Provider).DeleteAccount("username");
((SimpleMembershipProvider)Membership.Provider).DeleteUser("username", true);
``` | `((SimpleMembershipProvider)Membership.Provider).DeleteAccount("UserName");` //This will remove entry from **[webpages\_Membership]** table
`Roles.RemoveUserFromRole("UserName", "RoleName");` // This will remove from **[webpages\_UsersInRoles]** table
`((SimpleMembershipProvider)Membership.Provider).DeleteUser("UserName", true);` // This will remove from **userprofile** table |
Question: everyone!
I am trying to render the exchange rates from a server to my page.
Here is my React code:
```
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.state = {
exRates: []
};
}
getCurrencyRatesFromDB = () => {
fetch('https://api.exchangeratesapi.io/latest')
.then((response) => {
console.log('then 1', response);
return response.json();
}).then((data) => {
console.log('then 2', data);
this.setState({
exRates: data.rates
});
});
}
render() {
console.log('render started');
return (
<div>
console.log('return started'),
<button
type="button"
className="btn"
onClick={() => {
this.getCurrencyRatesFromDB();
}}
>
Load rates
</button>
<p>{this.state}</p>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
```
How do I modify the 'render' part to see the rates in a column like it is on the server?
Thank very much to you in advance!
Answer: | 1. You must not had an empty line beetween
`@app.route("/profile/<name>")` and `def profile(name):`
2. You have to set the html file in a folder called templates.
3. You have to set the templates folder and run.py in the same folder | You can try this below by adding the type string in your @app.route :
```
@app.route("/profile/<string:name>")
def profile(name):
return render_template("test.html", name=name)
``` |
Question: everyone!
I am trying to render the exchange rates from a server to my page.
Here is my React code:
```
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.state = {
exRates: []
};
}
getCurrencyRatesFromDB = () => {
fetch('https://api.exchangeratesapi.io/latest')
.then((response) => {
console.log('then 1', response);
return response.json();
}).then((data) => {
console.log('then 2', data);
this.setState({
exRates: data.rates
});
});
}
render() {
console.log('render started');
return (
<div>
console.log('return started'),
<button
type="button"
className="btn"
onClick={() => {
this.getCurrencyRatesFromDB();
}}
>
Load rates
</button>
<p>{this.state}</p>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
```
How do I modify the 'render' part to see the rates in a column like it is on the server?
Thank very much to you in advance!
Answer: | Whenever we receive 500 internal server error on a Python wsgi application we can log it using 'logging'
First import `from logging import FileHandler,WARNING`
then after `app = Flask(__name__, template_folder = 'template')`
add
```
file_handler = FileHandler('errorlog.txt')
file_handler.setLevel(WARNING)
```
Then you can run the application and when you receive a 500 Internal server error, cat/nano your errortext.txt file to read it, which will show you what the error was caused by. | You can try this below by adding the type string in your @app.route :
```
@app.route("/profile/<string:name>")
def profile(name):
return render_template("test.html", name=name)
``` |
Question: I am executing a stored procedure but it is failing at some point,
Current error code is not helping me to find where and exactly what the error is
I wanted to know where it is exactly failing so wanted to print line by line output while executing.
for eg :
```
create or replace
-- decaring required variable
PROCEDURE "PROC_DATA_TABLE_DETAILS" IS
FOR TABLEDETAILS IN (SELECT * FROM user_tables )
LOOP
dbms_output.put_line (TABLENAME);
select NUM_ROWS INTO COUNTRECORDS from all_tables where owner not like 'SYS%'and TABLE_NAME = TABLEDETAILS.TABLE_NAME;
FOR FIELDSDETAILS IN (SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME = TABLENAME)
LOOP
FIELDNAME :=FIELDSDETAILS.COLUMN_NAME;
dbms_output.put_line (FIELDNAME );
execute immediate 'SELECT NVL(count(*),0) FROM ' ||TABLENAME || ' WHERE '|| FIELDNAME || ' is not null ' into TEMPNONBLANK;
END LOOP;
INSERT INTO DATA_TABLE_DETAILS VALUES (TABLEDETAILS.TABLE_NAME,COUNTFIELDS)
END LOOP;
END PROC_DATA_TABLE_DETAILS;
```
Answer: | Your code will look like this; additionally you can write a procedure with autonomous transactions to log all error or logs. you will also get online code for this functionality.
[http://log4plsql.sourceforge.net/](http://logs)
```
create or replace procedure proc_data_table_details is
tablename varchar2(30);
countrecords number;
fieldname varchar2(30);
tempnonblank number;
begin
for tabledetails in (select * from user_tables where rownum < 3) loop
tablename := tabledetails.table_name;
dbms_output.put_line(tabledetails.table_name);
select num_rows
into countrecords
from all_tables
where owner not like 'SYS%'
and table_name = tablename;
for fieldsdetails in (select * from user_tab_columns where table_name = tablename) loop
fieldname := fieldsdetails.column_name;
dbms_output.put_line(fieldname);
execute immediate 'SELECT NVL(count(*),0) FROM ' || tablename || ' WHERE ' || fieldname || ' is not null '
into tempnonblank;
dbms_output.put_line('TABLENAME :' || tablename || ' column name :' || fieldname || ' count :' || tempnonblank);
end loop;
end loop;
end proc_data_table_details;
``` | Try to break the code to few segements. That way you will narrow down your search field. Becoz what you are trying to do is take an analytical decision about when to print.
Alternatively, if u want to print after every value assignment, you can parse the PL/SQL code as long to a variable and then loop over it until next ':=' isn't found. And then within the Loop, find the next position of ';' and substring thr. Append dbms\_output.print\_line(preceeding\_part\_of\_assignment) and then append again the remaining string.
Instead you can just use debug. |
Question: I need help with my program. I declared a one-dimensional array of 6 and I want to show random values between 1-6 in a text box
My question is how do I show values in my array in textbox1.text?
Here is my code:
```
Public Sub ClickMyFirstClassButton()
If FirstClass.Checked = True Then
'This piece of code declares an array
Dim Seats As Integer()
'This is a One Dimensional Array
ReDim Seats(6)
TextBox1.Text = (String.Format("First Class is checked. The number of seats are : ", (Seats)))
'ElseIf FirstClass.AutoCheck = True Then
'MessageBox.Show("FirstClass is Auto checked")
End If
End Sub
```
I messed around with my program and this is what I did.
Public Sub ClickMyFirstClassButton()
```
If FirstClass.Checked = True Then
'Dim Seats As Integer() = {1, 2, 3, 4, 5, 6}
Dim Seats(0 To 6) As Integer
Seats(0) = 1
Seats(1) = 2
Seats(2) = 3
Seats(3) = 4
Seats(4) = 5
Seats(5) = 6
TextBox1.Text = (String.Format("First Class is checked. Your seat is : {0}", Seats(RandomNumber(Seats))))
MessageBox.Show(String.Format("First Class is checked. Your seat is : {0}", Seats(RandomNumber(Seats))))
'ElseIf FirstClass.AutoCheck Then
'MessageBox.Show("FirstClass is Auto checked")
End If
End Sub
```
Answer: | As suggested by @eryksun, this solves the issue:
```
p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.communicate('hello \n world')
p.wait()
``` | I suspect it's because you're using `shell=True`, refactor your code to not use it.
But I would suggest abandoning this approach alltogether and use [pyperclip](https://pypi.python.org/pypi/pyperclip/) for the clipboard support. It's cross-platform and freely available. |
Question: In a C# enumeration, are there any negative side effects of using a negative number?
I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this.
```
public enum ResponseCodes
{
InvalidServerUserPasswordCombo = -1,
// etc.
}
```
Answer: | >
> negative side effects of using a negative number
>
>
>
Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly.
But using an enum as a collection of related constants can quite happily use negative values. | There's no negative side effects, however, keep in mind that an enum gets initialized to zero in this instance:
```
class YourClass {
public ResponseCodes ResponseCode { get; set; }
}
```
Providing just negative one will have an undesired impact for any users of the class (unless they initialize it. |
Question: In a C# enumeration, are there any negative side effects of using a negative number?
I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this.
```
public enum ResponseCodes
{
InvalidServerUserPasswordCombo = -1,
// etc.
}
```
Answer: | >
> negative side effects of using a negative number
>
>
>
Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly.
But using an enum as a collection of related constants can quite happily use negative values. | No, the enum is a value with an integer type and this can be any value from -2,147,483,648 to 2,147,483,647! :) |
Question: In a C# enumeration, are there any negative side effects of using a negative number?
I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this.
```
public enum ResponseCodes
{
InvalidServerUserPasswordCombo = -1,
// etc.
}
```
Answer: | >
> negative side effects of using a negative number
>
>
>
Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly.
But using an enum as a collection of related constants can quite happily use negative values. | This answer is 7 years late but I haven't seen the point made anywhere else.
There is a minor negative side effect when using negative numbers for enums. If you want to cast a negative number to an enum you'll need to ensure the number is in brackets to avoid a compile error, e.g.:
```
class YourClass {
ResponseCodes rc = (ResponseCodes)(-1);
}
``` |
Question: In a C# enumeration, are there any negative side effects of using a negative number?
I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this.
```
public enum ResponseCodes
{
InvalidServerUserPasswordCombo = -1,
// etc.
}
```
Answer: | There's no negative side effects, however, keep in mind that an enum gets initialized to zero in this instance:
```
class YourClass {
public ResponseCodes ResponseCode { get; set; }
}
```
Providing just negative one will have an undesired impact for any users of the class (unless they initialize it. | No, the enum is a value with an integer type and this can be any value from -2,147,483,648 to 2,147,483,647! :) |
Question: In a C# enumeration, are there any negative side effects of using a negative number?
I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this.
```
public enum ResponseCodes
{
InvalidServerUserPasswordCombo = -1,
// etc.
}
```
Answer: | There's no negative side effects, however, keep in mind that an enum gets initialized to zero in this instance:
```
class YourClass {
public ResponseCodes ResponseCode { get; set; }
}
```
Providing just negative one will have an undesired impact for any users of the class (unless they initialize it. | This answer is 7 years late but I haven't seen the point made anywhere else.
There is a minor negative side effect when using negative numbers for enums. If you want to cast a negative number to an enum you'll need to ensure the number is in brackets to avoid a compile error, e.g.:
```
class YourClass {
ResponseCodes rc = (ResponseCodes)(-1);
}
``` |
Question: I am trying to install additional drivers on Ubuntu 12.04. The application is returning an error. In the log file I can see various NVIDIA module failed to load. However, my PC do not have NVIDIA graphics card. Its Intel card, then why is Ubuntu searching for NVIDIA card?
I have installed Ubuntu 12.04 and additional drivers before without any error.
Though this is the first time I am using Windows installer version. I don't know if its related to that.
Answer: | **Yes**, but you will need Ubuntu 12.10.
1. Download Steam from Ubuntu Software Center
2. Start it up, you will be asked to log in with your Steam account. If you don't have one you can choose the create account option.
3. Go to the Store tab
4. Enter Don't Starve in the search bar in the top-right and click Don't Starve
5. Scroll a bit down and click the green button to buy the game
6. Pay with credit card or PayPal. It costs €14
7. The game will be downloaded and installed
8. **Play :-D** | **Install from Chrome Webstore and play via Google Chrome**
Yes you can, altough Linux isn't officially supported according to the game's website ([system requirements](http://www.dontstarvegame.com/blog/system-requirements)), but the game is available in the *Chrome Webstore* for all platforms:
[Chrome Web Store - Don't Starve](https://chrome.google.com/webstore/detail/dont-starve/hiledapehlkhdehbhppgmekfalnlfajc)
**Note**: does not work on the Ubuntu builds of Chromium, because Native Client (NaCl) is disabled ([bug](https://bugs.launchpad.net/ubuntu/+source/chromium-browser/+bug/882942)).
1. Open the above Chrome Webstore link in `Google Chrome`.
2. Click ***Add to Chrome***.
3. You will be prompted to log in with a Google account - log in or create one and log in.
4. Answer ***Add*** to the confirmation question when asked.
Once installed, you can launch it from Chrome's *new tab page*. If it does not work, there might be an issue with your graphics card, its drivers and the WebGL support in Chrome.
Tested on: Chrome 30.0.1599.66, Ubuntu 12.10 64-bit, Intel HD4000 Graphics (xserver-xorg-video-intel: 2:2.21.9-0ubuntu0~raring). |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents. | Javascript in browsers doesn't allow you to write local files, for **security reasons**. This **may change with time**, but as for now you have to **deal with it**. |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents. | Only with a server side javascript interpreter, but that isn't the typical environment you run javascript in. |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents. | What about cookies? It is accessible via javascript, it is on your client and it is a plain text file. Only issue is the size of it (4k max if I remember well).
What you can do as well is use your browser localStorage / userData / globalStorage (depending on your browser version). It acts like cookies (new webStorage / HTML5 specs) but can handle bigger amounts of data. Then, using some add ons (firebug on firefox for instance) you can easily read / copy / past the value and do whatever you have to do with it! |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | **It *is* possible to read/write to a local file via JavaScript**: take a look at [TiddlyWIki](http://www.tiddlywiki.com/). *(Caveat: only works for local documents.)*
I have actually written a [Single Page Application](http://softwareas.com/towards-a-single-page-application-framework) (SPA) using [twFile](http://jquery.tiddlywiki.org/twFile.html), a part of the TiddlyWiki codebase:
1. Works in different browsers: (IE, Firefox, Chrome)
2. This code is a little old now. TiddlyWiki abandoned the jQuery plugin design a while ago. (Look at the [current TiddlyWiki filesystem.js](http://dev.tiddlywiki.org/browser/Trunk/core/js/FileSystem.js) for more a more recent implementation. It's not isolated for you like the twFile plug-in, though).
3. Although written as a jQuery plug-in, I've studied the code and it is almost completely decoupled from jQuery.
**Update:**
I have uploaded a [proof-of-concept](http://coolcases.com/jeopardy/) that accesses a local file via JavaScript.
* Modifying this application to write to a file is trivial.
* I have not tried to get this to work as a file served from a web server, but it should be possible since there are [server-side implementations of TiddlyWiki](http://tiddlywiki.org/wiki/Can_I_use_TiddlyWiki_as_a_multi-user/collaborative/server_based_wiki%3F)<>.
**Update:**
So it looks like the server side implementations of TiddlyWiki use a server "adapter" to modify a file stored on the server, similar to [Peter's description](https://stackoverflow.com/questions/3195720/write-a-file-with-prototype-or-plain-javascript/3195752#3195752). The pure JavaScript method will probably not work if the page is served from a web server due to cross-domain security limitations. | Javascript in browsers doesn't allow you to write local files, for **security reasons**. This **may change with time**, but as for now you have to **deal with it**. |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | Javascript in browsers doesn't allow you to write local files, for **security reasons**. This **may change with time**, but as for now you have to **deal with it**. | What about cookies? It is accessible via javascript, it is on your client and it is a plain text file. Only issue is the size of it (4k max if I remember well).
What you can do as well is use your browser localStorage / userData / globalStorage (depending on your browser version). It acts like cookies (new webStorage / HTML5 specs) but can handle bigger amounts of data. Then, using some add ons (firebug on firefox for instance) you can easily read / copy / past the value and do whatever you have to do with it! |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | **It *is* possible to read/write to a local file via JavaScript**: take a look at [TiddlyWIki](http://www.tiddlywiki.com/). *(Caveat: only works for local documents.)*
I have actually written a [Single Page Application](http://softwareas.com/towards-a-single-page-application-framework) (SPA) using [twFile](http://jquery.tiddlywiki.org/twFile.html), a part of the TiddlyWiki codebase:
1. Works in different browsers: (IE, Firefox, Chrome)
2. This code is a little old now. TiddlyWiki abandoned the jQuery plugin design a while ago. (Look at the [current TiddlyWiki filesystem.js](http://dev.tiddlywiki.org/browser/Trunk/core/js/FileSystem.js) for more a more recent implementation. It's not isolated for you like the twFile plug-in, though).
3. Although written as a jQuery plug-in, I've studied the code and it is almost completely decoupled from jQuery.
**Update:**
I have uploaded a [proof-of-concept](http://coolcases.com/jeopardy/) that accesses a local file via JavaScript.
* Modifying this application to write to a file is trivial.
* I have not tried to get this to work as a file served from a web server, but it should be possible since there are [server-side implementations of TiddlyWiki](http://tiddlywiki.org/wiki/Can_I_use_TiddlyWiki_as_a_multi-user/collaborative/server_based_wiki%3F)<>.
**Update:**
So it looks like the server side implementations of TiddlyWiki use a server "adapter" to modify a file stored on the server, similar to [Peter's description](https://stackoverflow.com/questions/3195720/write-a-file-with-prototype-or-plain-javascript/3195752#3195752). The pure JavaScript method will probably not work if the page is served from a web server due to cross-domain security limitations. | Only with a server side javascript interpreter, but that isn't the typical environment you run javascript in. |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | Only with a server side javascript interpreter, but that isn't the typical environment you run javascript in. | What about cookies? It is accessible via javascript, it is on your client and it is a plain text file. Only issue is the size of it (4k max if I remember well).
What you can do as well is use your browser localStorage / userData / globalStorage (depending on your browser version). It acts like cookies (new webStorage / HTML5 specs) but can handle bigger amounts of data. Then, using some add ons (firebug on firefox for instance) you can easily read / copy / past the value and do whatever you have to do with it! |
Question: I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance !
Answer: | **It *is* possible to read/write to a local file via JavaScript**: take a look at [TiddlyWIki](http://www.tiddlywiki.com/). *(Caveat: only works for local documents.)*
I have actually written a [Single Page Application](http://softwareas.com/towards-a-single-page-application-framework) (SPA) using [twFile](http://jquery.tiddlywiki.org/twFile.html), a part of the TiddlyWiki codebase:
1. Works in different browsers: (IE, Firefox, Chrome)
2. This code is a little old now. TiddlyWiki abandoned the jQuery plugin design a while ago. (Look at the [current TiddlyWiki filesystem.js](http://dev.tiddlywiki.org/browser/Trunk/core/js/FileSystem.js) for more a more recent implementation. It's not isolated for you like the twFile plug-in, though).
3. Although written as a jQuery plug-in, I've studied the code and it is almost completely decoupled from jQuery.
**Update:**
I have uploaded a [proof-of-concept](http://coolcases.com/jeopardy/) that accesses a local file via JavaScript.
* Modifying this application to write to a file is trivial.
* I have not tried to get this to work as a file served from a web server, but it should be possible since there are [server-side implementations of TiddlyWiki](http://tiddlywiki.org/wiki/Can_I_use_TiddlyWiki_as_a_multi-user/collaborative/server_based_wiki%3F)<>.
**Update:**
So it looks like the server side implementations of TiddlyWiki use a server "adapter" to modify a file stored on the server, similar to [Peter's description](https://stackoverflow.com/questions/3195720/write-a-file-with-prototype-or-plain-javascript/3195752#3195752). The pure JavaScript method will probably not work if the page is served from a web server due to cross-domain security limitations. | What about cookies? It is accessible via javascript, it is on your client and it is a plain text file. Only issue is the size of it (4k max if I remember well).
What you can do as well is use your browser localStorage / userData / globalStorage (depending on your browser version). It acts like cookies (new webStorage / HTML5 specs) but can handle bigger amounts of data. Then, using some add ons (firebug on firefox for instance) you can easily read / copy / past the value and do whatever you have to do with it! |
Question: Isn't that nicely recursive?
I've got a portable command prompt on my external drive, and it has a nice .bat file to configure some initial settings, but I'd like more!
Here's what I know how to set from .bat:
* Colors = (color XY) where x and y are hex digits for the predefined colors
* Prompt = (prompt $p$g) sets the prompt to "C:\etc\etc >" the default prompt
* Title = (title "text") sets the window title to "text"
* Screen Size = (mode con: cols=XX lines=YY) sets the columns and lines size of the window
* Path = (SET PATH=%~d0\bin;%PATH%) sets up local path to my tools and appends the computer's path
So that's all great. But there are a few settings I can't seem to set from the bat. Like, how would I set these up wihtout using the Properties dialogue:
* Buffer = not screen size, but the buffer
* Options like quick edit mode and autocomplete
* Popup colors
* Font. And can you use a font on the portable drive, or must it be installed to work?
* Command history options
Answer: | Regarding setting the buffer size:
Using `mode con: cols=XX lines=YY` sets not only the window (screen) size, but the buffer size too.
If you specify a size allowed by your system, based on available screen size, you'll see that both window and buffer dimension are set to the same value; .e.g:
```
mode con: cols=100 lines=30
```
results in the following (values are the same):
* window size: Width=**160**, Height=**78**
* buffer size: Width=**160**, Height=**78**
By contrast, if you specify values that are too large based on the available screen size, you'll see that the window size changes to its maximum, but the buffer size is changed to the values as specified.
```
mode con: cols=1600 lines=900
```
With a screen resolution of 1280x1024, you'll get:
* window size: Width=**160**, Height=**78**
* buffer size: Width=**1600**, Height=**900** | Regarding auto-completion:
>
> File and Directory name completion is
> NOT enabled by default. You can
> enable or disable file name completion
> for a particular invocation of CMD.EXE
> with the /F:ON or /F:OFF switch. You
> can enable or disable completion for
> all invocations of CMD.EXE on a
> machine and/or user logon session by
> setting either or both of the
> following REG\_DWORD values in the
> registry using REGEDT32.EXE:
>
>
>
> ```
> HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
> HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar
>
> and/or
>
> HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
> HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
>
> ```
>
> with the hex value of a control
> character to use for a particular
> function (e.g. 0x4 is Ctrl-D and 0x6
> is Ctrl-F). The user specific
> settings take precedence over the
> machine settings. The command line
> switches take precedence over the
> registry settings.
>
>
> If completion is enabled with the
> /F:ON switch, the two control
> characters used are Ctrl-D for
> directory name completion and Ctrl-F
> for file name completion. To disable
> a particular completion character in
> the registry, use the value for space
> (0x20) as it is not a valid control
> character.
>
>
>
Couldn't find any command history options in there ( cmd /? ), and it looks like the other options you asked about are set exclusively through registry settings. |
Question: Isn't that nicely recursive?
I've got a portable command prompt on my external drive, and it has a nice .bat file to configure some initial settings, but I'd like more!
Here's what I know how to set from .bat:
* Colors = (color XY) where x and y are hex digits for the predefined colors
* Prompt = (prompt $p$g) sets the prompt to "C:\etc\etc >" the default prompt
* Title = (title "text") sets the window title to "text"
* Screen Size = (mode con: cols=XX lines=YY) sets the columns and lines size of the window
* Path = (SET PATH=%~d0\bin;%PATH%) sets up local path to my tools and appends the computer's path
So that's all great. But there are a few settings I can't seem to set from the bat. Like, how would I set these up wihtout using the Properties dialogue:
* Buffer = not screen size, but the buffer
* Options like quick edit mode and autocomplete
* Popup colors
* Font. And can you use a font on the portable drive, or must it be installed to work?
* Command history options
Answer: | Regarding auto-completion:
>
> File and Directory name completion is
> NOT enabled by default. You can
> enable or disable file name completion
> for a particular invocation of CMD.EXE
> with the /F:ON or /F:OFF switch. You
> can enable or disable completion for
> all invocations of CMD.EXE on a
> machine and/or user logon session by
> setting either or both of the
> following REG\_DWORD values in the
> registry using REGEDT32.EXE:
>
>
>
> ```
> HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
> HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar
>
> and/or
>
> HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
> HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
>
> ```
>
> with the hex value of a control
> character to use for a particular
> function (e.g. 0x4 is Ctrl-D and 0x6
> is Ctrl-F). The user specific
> settings take precedence over the
> machine settings. The command line
> switches take precedence over the
> registry settings.
>
>
> If completion is enabled with the
> /F:ON switch, the two control
> characters used are Ctrl-D for
> directory name completion and Ctrl-F
> for file name completion. To disable
> a particular completion character in
> the registry, use the value for space
> (0x20) as it is not a valid control
> character.
>
>
>
Couldn't find any command history options in there ( cmd /? ), and it looks like the other options you asked about are set exclusively through registry settings. | For true Buffer Size adjustment use DOSKEY /LISTSIZE=size
You can't change colors within the shell anymore since Microsoft took ANSI ESC control out of the command/cmd prompts. |
Question: Isn't that nicely recursive?
I've got a portable command prompt on my external drive, and it has a nice .bat file to configure some initial settings, but I'd like more!
Here's what I know how to set from .bat:
* Colors = (color XY) where x and y are hex digits for the predefined colors
* Prompt = (prompt $p$g) sets the prompt to "C:\etc\etc >" the default prompt
* Title = (title "text") sets the window title to "text"
* Screen Size = (mode con: cols=XX lines=YY) sets the columns and lines size of the window
* Path = (SET PATH=%~d0\bin;%PATH%) sets up local path to my tools and appends the computer's path
So that's all great. But there are a few settings I can't seem to set from the bat. Like, how would I set these up wihtout using the Properties dialogue:
* Buffer = not screen size, but the buffer
* Options like quick edit mode and autocomplete
* Popup colors
* Font. And can you use a font on the portable drive, or must it be installed to work?
* Command history options
Answer: | Regarding setting the buffer size:
Using `mode con: cols=XX lines=YY` sets not only the window (screen) size, but the buffer size too.
If you specify a size allowed by your system, based on available screen size, you'll see that both window and buffer dimension are set to the same value; .e.g:
```
mode con: cols=100 lines=30
```
results in the following (values are the same):
* window size: Width=**160**, Height=**78**
* buffer size: Width=**160**, Height=**78**
By contrast, if you specify values that are too large based on the available screen size, you'll see that the window size changes to its maximum, but the buffer size is changed to the values as specified.
```
mode con: cols=1600 lines=900
```
With a screen resolution of 1280x1024, you'll get:
* window size: Width=**160**, Height=**78**
* buffer size: Width=**1600**, Height=**900** | For true Buffer Size adjustment use DOSKEY /LISTSIZE=size
You can't change colors within the shell anymore since Microsoft took ANSI ESC control out of the command/cmd prompts. |
Question: Isn't that nicely recursive?
I've got a portable command prompt on my external drive, and it has a nice .bat file to configure some initial settings, but I'd like more!
Here's what I know how to set from .bat:
* Colors = (color XY) where x and y are hex digits for the predefined colors
* Prompt = (prompt $p$g) sets the prompt to "C:\etc\etc >" the default prompt
* Title = (title "text") sets the window title to "text"
* Screen Size = (mode con: cols=XX lines=YY) sets the columns and lines size of the window
* Path = (SET PATH=%~d0\bin;%PATH%) sets up local path to my tools and appends the computer's path
So that's all great. But there are a few settings I can't seem to set from the bat. Like, how would I set these up wihtout using the Properties dialogue:
* Buffer = not screen size, but the buffer
* Options like quick edit mode and autocomplete
* Popup colors
* Font. And can you use a font on the portable drive, or must it be installed to work?
* Command history options
Answer: | Regarding setting the buffer size:
Using `mode con: cols=XX lines=YY` sets not only the window (screen) size, but the buffer size too.
If you specify a size allowed by your system, based on available screen size, you'll see that both window and buffer dimension are set to the same value; .e.g:
```
mode con: cols=100 lines=30
```
results in the following (values are the same):
* window size: Width=**160**, Height=**78**
* buffer size: Width=**160**, Height=**78**
By contrast, if you specify values that are too large based on the available screen size, you'll see that the window size changes to its maximum, but the buffer size is changed to the values as specified.
```
mode con: cols=1600 lines=900
```
With a screen resolution of 1280x1024, you'll get:
* window size: Width=**160**, Height=**78**
* buffer size: Width=**1600**, Height=**900** | You can set these values through a shortcut (.INK file).
I have a shortcut on my desktop with this as the target:
%windir%\system32\cmd.exe /K %userprofile%\STARTUP.CMD
The /K switch tells CMD.exe to run the batch file (which sets some variables, the prompt, etc.) and then stay open.
If you right-click on the shortcut and view its properties, you can set the window and buffer size, popup colors, starting position (x,y axis), etc. The settings will be saved in the shortcut itself and will be applied every time you open CMD.exe using that shortcut. |
Question: Isn't that nicely recursive?
I've got a portable command prompt on my external drive, and it has a nice .bat file to configure some initial settings, but I'd like more!
Here's what I know how to set from .bat:
* Colors = (color XY) where x and y are hex digits for the predefined colors
* Prompt = (prompt $p$g) sets the prompt to "C:\etc\etc >" the default prompt
* Title = (title "text") sets the window title to "text"
* Screen Size = (mode con: cols=XX lines=YY) sets the columns and lines size of the window
* Path = (SET PATH=%~d0\bin;%PATH%) sets up local path to my tools and appends the computer's path
So that's all great. But there are a few settings I can't seem to set from the bat. Like, how would I set these up wihtout using the Properties dialogue:
* Buffer = not screen size, but the buffer
* Options like quick edit mode and autocomplete
* Popup colors
* Font. And can you use a font on the portable drive, or must it be installed to work?
* Command history options
Answer: | You can set these values through a shortcut (.INK file).
I have a shortcut on my desktop with this as the target:
%windir%\system32\cmd.exe /K %userprofile%\STARTUP.CMD
The /K switch tells CMD.exe to run the batch file (which sets some variables, the prompt, etc.) and then stay open.
If you right-click on the shortcut and view its properties, you can set the window and buffer size, popup colors, starting position (x,y axis), etc. The settings will be saved in the shortcut itself and will be applied every time you open CMD.exe using that shortcut. | For true Buffer Size adjustment use DOSKEY /LISTSIZE=size
You can't change colors within the shell anymore since Microsoft took ANSI ESC control out of the command/cmd prompts. |
Question: I am curious as to why Start-Job increments in twos. My worry is that I am doing something wrong that makes the ID of a new job jump by 2.
```
Start-Job -ScriptBlock {Get-WinEvent -LogName system -MaxEvents 1000}
```
Results as shown by Get-Job
```
Id Name State HasMoreData Command
-- ---- ----- ----------- -------
2 Job2 Completed False Get-WinEvent -LogName system -MaxEvents 1000
4 Job4 Completed False Get-WinEvent -LogName system -MaxEvents 1000
6 Job6 Completed True Get-WinEvent -LogName system -MaxEvents 1000
```
Question: Can you control the Start-Job Id increments, or force them to be just 1?
Answer: | Each time you start a job, it consists of a parent job and one or more child jobs. If you run `get-job | fl` you'll see the child jobs, and you'll see that their names are the "missing" odd numbered names. | @1.618 give the right answer, here are some more details :
```
Start-Job -ScriptBlock {Get-Process}
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
2 Job2 BackgroundJob Running True localhost Get-Process
Get-Job | fl *
State : Completed
HasMoreData : True
StatusMessage :
Location : localhost
Command : Get-Process
JobStateInfo : Completed
Finished : System.Threading.ManualResetEvent
InstanceId : 49a67ca4-840b-49ec-b293-efa9303e38bb
Id : 2
Name : Job2
ChildJobs : {Job3}
PSBeginTime : 03/03/2014 20:43:54
PSEndTime : 03/03/2014 20:44:00
PSJobTypeName : BackgroundJob
Output : {}
Error : {}
Progress : {}
Verbose : {}
Debug : {}
Warning : {}
get-job -IncludeChildJob
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
2 Job2 BackgroundJob Completed True localhost Get-Process
3 Job3 Completed True localhost Get-Process
```
Here is why, when you start a job, powershell create two jobs ?
Windows PowerShell jobs created through `Start-Job` always consist of a parent job and a child job. The child job does the actual work. If you were running the job against a number of remote machines by using `Invoke-Command` and its `–AsJob` parameter, you would get one child job per remote machine.
When you manage jobs, anything you do to the parent job is automatically applied to any child jobs. Removing or stopping the parent job performs the same action on the child jobs. Getting the results of the parent job means you get the results of all the child jobs.
You can access the child jobs directly to retrieve their data, n a simple job, as in the example, you can access the data through the parent or child jobs :
```
Receive-Job -Id 2 -Keep
Receive-Job -Id 3 -Keep
```
When you have multiple child jobs, its usually easier to access the child jobs in turn:
```
$jobs = Get-Job -Name Job2 | select -ExpandProperty ChildJobs
foreach ($job in $jobs){Receive-Job -Job $job -Keep}
``` |
Question: I am creating a Chart (DataVisualization.Charting.Chart) programmatically, which is a Stacked Bar chart.
I am also adding Legend entries programmatically to it. I want to show the Legend at the bottom of the chart.
But, while doing so, the Legend overlapps with the X-axis of the chart.
Here is the code I am using:
```
Private Function GetLegend(ByVal legendName As String, ByVal s As Single) As System.Windows.Forms.DataVisualization.Charting.Legend
Dim objLegend As System.Windows.Forms.DataVisualization.Charting.Legend = New System.Windows.Forms.DataVisualization.Charting.Legend()
objLegend.Name = legendName
objLegend.Font = New System.Drawing.Font("Verdana", s)
objLegend.IsDockedInsideChartArea = False
objLegend.Docking = Docking.Bottom
Return objLegend
End Function
```
Below statement adds that Legend to the chart
```
_msChart.Legends.Add(GetLegend("SomeValue1", 10.0F))
```
Any idea, what is missing? I want to show the legend at the bottom only, but it should not overlapp with the X-axis.
Answer: | I had the same problem today. Try adding:
```
objLegend.Position.Auto = true
objLegend.DockedToChartArea = "yourChartAreaName"
```
That did not help me but I found on the net that this might be helpful (and clean solution).
What actually worked for me was moving chart area to make space for legend so it no longer overlaps. My legend was on top so this code worked for me:
```
chart.ChartAreas[0].Position.Y = 15
```
You can try resizing it instead, forcing it to be for example 20 pixels shorter than `chart.Size`.
Hope this helps. | I had an overlapping legend/chart area problem as well but none of the other suggestions here seemed to make any difference. I think the problem stems from legend text wrapping to two lines and the sizing algorithms not taking account of this.
The ideas here got me thinking more clearly about the problem though, and I was able control the size and position of the chart area using the following.
```
Chart1.ChartAreas[0].InnerPlotPosition = new ElementPosition(15, 5, 90, 75);
```
There's not much intellisense on those parameters, but as well as I could deduce, the parameters are all percentages of the total chart area (I initially thought they might be pixel values and got some *very* odd results). So what I've written above would set the plot area to start at 15% in from the left edge of the chart image and 5% down from the top, and have a width of 90% and a height of 75%. |
Question: We will be developing a new web site for a client who already has a Kentico 8.2 license. I am trying to make a case for developing the site using Kentico 9. Some key features I have found so far include:
* faster performance (how much in real-world terms?)
* better integration with .Net MVC
* content staging tasks can be synchronized per user account
* better rollback functionality: previously we had to make full database backups, content staging in Kentico 8.2 causes issues for restoring previous versions of a page.
* built in source control support for GIT
It looks like Kentico integration with the client's existing database may be possible. Has anyone done this? What are the limitations or caveats?
Is there a discount for upgrading the license from 8.2 to 9?
Thanks in advance for your feedback!
Answer: | ### Preserving and Restoring State
Feature you are looking for is called State Restoration. From the [docs](http://State%20preservation%20records%20the%20configuration%20of%20your%20app%20before%20it%20is%20suspended%20so%20that%20the%20configuration%20can%20be%20restored%20on%20a%20subsequent%20app%20launch.):
>
> State preservation records the configuration of your app before it is
> suspended so that the configuration can be restored on a subsequent
> app launch.
>
>
>
How to tackle it:
1. Tag your view controllers for preservation. Assign restoration identifiers.
2. Restore view controllers at launch time. Encode and decode their state.
Topic is very broad but the [docs](https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/PreservingandRestoringState.html) explain it very well. | What you're trying to do is keep persistent data between launches of your application, right?
For that you should use core data, there are many useful recourses on the web to help you with that, heres a few helpful ones.
<https://developer.apple.com/library/watchos/documentation/Cocoa/Conceptual/CoreData/index.html>
<https://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started> |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 36