qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
976,665
How can I prove that, for $a,b \in \mathbb{Z}$ we have $$ 0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor - 2 \left \lfloor{\frac{a}{b}}\right \rfloor \leq 1 \, ? $$ Here, $\left \lfloor\,\right \rfloor$ is the [floor](http://mathworld.wolfram.com/FloorFunction.html) function. I tried the following: say that $\frac{2a}{b} = x$, and $ \left \lfloor{\frac{2a}{b}}\right \rfloor = m$, with $0 \leq x - m \leq 1$. I tried the same for $ 2 \left \lfloor{\frac{2a}{b}}\right \rfloor $, and then combining the two inequalities. It did not seem to help, though.
2014/10/16
[ "https://math.stackexchange.com/questions/976665", "https://math.stackexchange.com", "https://math.stackexchange.com/users/53283/" ]
In general $$ 0\le \lfloor 2x\rfloor -2\lfloor x\rfloor\le 1. $$ Proof. Either $x\in [k,k+1/2)$ or $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$. If $x\in [k,k+1/2)$, then $$ \lfloor 2x\rfloor=2k\quad\text{and}\quad 2\lfloor x\rfloor=2k, $$ while $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$, then $$ \lfloor 2x\rfloor=2k+1\quad\text{and}\quad 2\lfloor x\rfloor=2k. $$ So the inequalities hold in both cases.
Just for fun, here is an alternative proof, using the same induction approach as [another math.se answer of mine](https://math.stackexchange.com/a/1678830/11994).$ \newcommand{\calc}{\begin{align} \quad &} \newcommand{\op}[1]{\\ #1 \quad & \quad \unicode{x201c}} \newcommand{\hints}[1]{\mbox{#1} \\ \quad & \quad \phantom{\unicode{x201c}} } \newcommand{\hint}[1]{\mbox{#1} \unicode{x201d} \\ \quad & } \newcommand{\endcalc}{\end{align}} \newcommand{\Ref}[1]{\text{(#1)}} \newcommand{\floor}[1]{\lfloor#1\rfloor} \newcommand{\then}{\Rightarrow} \newcommand{\when}{\Leftarrow} \newcommand{\true}{\text{true}} \newcommand{\false}{\text{false}} $ We are asked to prove $$ \tag{0} 0 \le \floor{2x} - 2 \floor{x} \le 1 $$ for all rational $\;x\;$. Our first observation is that the fact that $\;x\;$ is rational, so that it can be written as $\;\tfrac a b\;$ for integers $\;a,b\;$, seems not to help us in any way, so we instead will attempt to prove this for all *real* $\;x\;$. A quick graph of $\;\floor{2x} - 2 \floor{x}\;$ shows that it has a period of $1$. Abbreviating $\Ref 0$ by $\;P(x)\;$, this suggests we investigate $\;P(x+1)\;$: $$\calc P(x + 1) \op=\hint{expand abbreviation $\;P\;$; simplify} 0 \le \floor{2x+2} - 2 \floor{x+1} \le 1 \op=\hint{move integer $2$ out of left floor, and $1$ out of right floor} 0 \le \floor{2x} + 2 - 2 (\floor{x}+1) \le 1 \op=\hint{simplify; abbreviation $\;P\;$} P(x) \endcalc$$ So we've proven $$ \tag 1 \langle \forall x :: P(x) \;\equiv\; P(x + 1) \rangle $$ which is a kind of 'induction step'. If we can additionally prove the 'base case' $$ \tag 2 \langle \forall x : 0 \le x \lt 1 : P(x) \rangle $$ then by induction our goal $\;\langle \forall x :: P(x) \rangle\;$ follows. We can prove $\Ref 2$ as follows: assuming $\;0 \le x \lt 1\;$, we have $$\calc P(x) \op=\hint{abbreviation $\;P\;$} 0 \le \floor{2x} - 2 \floor{x} \le 1 \op=\hints{by our assumption and the definition of $\;\floor{\cdot}\;$} \hints{we have $\;0 \le \floor{x} \lt 1\;$, and $\;\floor{\cdot}\;$ is integer,} \hint{so $\;\floor{x} = 0\;$} 0 \le \floor{2x} \le 1 \op=\hints{by our assumption and the definition of $\;\floor{\cdot}\;$} \hint{we have $\;0 \le \floor{2x} \lt 2\;$; $\;\floor{\cdot}\;$ is integer} \true \endcalc$$ This completes the proof.
976,665
How can I prove that, for $a,b \in \mathbb{Z}$ we have $$ 0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor - 2 \left \lfloor{\frac{a}{b}}\right \rfloor \leq 1 \, ? $$ Here, $\left \lfloor\,\right \rfloor$ is the [floor](http://mathworld.wolfram.com/FloorFunction.html) function. I tried the following: say that $\frac{2a}{b} = x$, and $ \left \lfloor{\frac{2a}{b}}\right \rfloor = m$, with $0 \leq x - m \leq 1$. I tried the same for $ 2 \left \lfloor{\frac{2a}{b}}\right \rfloor $, and then combining the two inequalities. It did not seem to help, though.
2014/10/16
[ "https://math.stackexchange.com/questions/976665", "https://math.stackexchange.com", "https://math.stackexchange.com/users/53283/" ]
$0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor \leq \frac{2\*a}{b} < 2\*(\left \lfloor{\frac{a}{b}}\right \rfloor + 1)$ = $2\*\left \lfloor{\frac{a}{b}}\right \rfloor$ + 2 $\left \lfloor{\frac{2a}{b}}\right \rfloor$ is an integer, so being < than an other integer means being $\leq$ than this integer -1 => $\left \lfloor{\frac{2a}{b}}\right \rfloor$ $\leq $ $2\*\left \lfloor{\frac{a}{b}}\right \rfloor$ + 1 **Edit:** As for the other part of the inequality: $$\frac{2a}{b}= 2\left \lfloor{\frac{a}{b}}\right \rfloor + 2(\frac{a}{b}) $$ with $(x)$ being the fractional part of $x$. All that's left to consider is whether $2(\frac{a}{b})$ is smaller or greater than $1$ to conclude.
Just for fun, here is an alternative proof, using the same induction approach as [another math.se answer of mine](https://math.stackexchange.com/a/1678830/11994).$ \newcommand{\calc}{\begin{align} \quad &} \newcommand{\op}[1]{\\ #1 \quad & \quad \unicode{x201c}} \newcommand{\hints}[1]{\mbox{#1} \\ \quad & \quad \phantom{\unicode{x201c}} } \newcommand{\hint}[1]{\mbox{#1} \unicode{x201d} \\ \quad & } \newcommand{\endcalc}{\end{align}} \newcommand{\Ref}[1]{\text{(#1)}} \newcommand{\floor}[1]{\lfloor#1\rfloor} \newcommand{\then}{\Rightarrow} \newcommand{\when}{\Leftarrow} \newcommand{\true}{\text{true}} \newcommand{\false}{\text{false}} $ We are asked to prove $$ \tag{0} 0 \le \floor{2x} - 2 \floor{x} \le 1 $$ for all rational $\;x\;$. Our first observation is that the fact that $\;x\;$ is rational, so that it can be written as $\;\tfrac a b\;$ for integers $\;a,b\;$, seems not to help us in any way, so we instead will attempt to prove this for all *real* $\;x\;$. A quick graph of $\;\floor{2x} - 2 \floor{x}\;$ shows that it has a period of $1$. Abbreviating $\Ref 0$ by $\;P(x)\;$, this suggests we investigate $\;P(x+1)\;$: $$\calc P(x + 1) \op=\hint{expand abbreviation $\;P\;$; simplify} 0 \le \floor{2x+2} - 2 \floor{x+1} \le 1 \op=\hint{move integer $2$ out of left floor, and $1$ out of right floor} 0 \le \floor{2x} + 2 - 2 (\floor{x}+1) \le 1 \op=\hint{simplify; abbreviation $\;P\;$} P(x) \endcalc$$ So we've proven $$ \tag 1 \langle \forall x :: P(x) \;\equiv\; P(x + 1) \rangle $$ which is a kind of 'induction step'. If we can additionally prove the 'base case' $$ \tag 2 \langle \forall x : 0 \le x \lt 1 : P(x) \rangle $$ then by induction our goal $\;\langle \forall x :: P(x) \rangle\;$ follows. We can prove $\Ref 2$ as follows: assuming $\;0 \le x \lt 1\;$, we have $$\calc P(x) \op=\hint{abbreviation $\;P\;$} 0 \le \floor{2x} - 2 \floor{x} \le 1 \op=\hints{by our assumption and the definition of $\;\floor{\cdot}\;$} \hints{we have $\;0 \le \floor{x} \lt 1\;$, and $\;\floor{\cdot}\;$ is integer,} \hint{so $\;\floor{x} = 0\;$} 0 \le \floor{2x} \le 1 \op=\hints{by our assumption and the definition of $\;\floor{\cdot}\;$} \hint{we have $\;0 \le \floor{2x} \lt 2\;$; $\;\floor{\cdot}\;$ is integer} \true \endcalc$$ This completes the proof.
976,665
How can I prove that, for $a,b \in \mathbb{Z}$ we have $$ 0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor - 2 \left \lfloor{\frac{a}{b}}\right \rfloor \leq 1 \, ? $$ Here, $\left \lfloor\,\right \rfloor$ is the [floor](http://mathworld.wolfram.com/FloorFunction.html) function. I tried the following: say that $\frac{2a}{b} = x$, and $ \left \lfloor{\frac{2a}{b}}\right \rfloor = m$, with $0 \leq x - m \leq 1$. I tried the same for $ 2 \left \lfloor{\frac{2a}{b}}\right \rfloor $, and then combining the two inequalities. It did not seem to help, though.
2014/10/16
[ "https://math.stackexchange.com/questions/976665", "https://math.stackexchange.com", "https://math.stackexchange.com/users/53283/" ]
Hint: let $a=pb+q$ where $p, q \in \mathbb Z$ and $0\le q<b$.
Just for fun, here is an alternative proof, using the same induction approach as [another math.se answer of mine](https://math.stackexchange.com/a/1678830/11994).$ \newcommand{\calc}{\begin{align} \quad &} \newcommand{\op}[1]{\\ #1 \quad & \quad \unicode{x201c}} \newcommand{\hints}[1]{\mbox{#1} \\ \quad & \quad \phantom{\unicode{x201c}} } \newcommand{\hint}[1]{\mbox{#1} \unicode{x201d} \\ \quad & } \newcommand{\endcalc}{\end{align}} \newcommand{\Ref}[1]{\text{(#1)}} \newcommand{\floor}[1]{\lfloor#1\rfloor} \newcommand{\then}{\Rightarrow} \newcommand{\when}{\Leftarrow} \newcommand{\true}{\text{true}} \newcommand{\false}{\text{false}} $ We are asked to prove $$ \tag{0} 0 \le \floor{2x} - 2 \floor{x} \le 1 $$ for all rational $\;x\;$. Our first observation is that the fact that $\;x\;$ is rational, so that it can be written as $\;\tfrac a b\;$ for integers $\;a,b\;$, seems not to help us in any way, so we instead will attempt to prove this for all *real* $\;x\;$. A quick graph of $\;\floor{2x} - 2 \floor{x}\;$ shows that it has a period of $1$. Abbreviating $\Ref 0$ by $\;P(x)\;$, this suggests we investigate $\;P(x+1)\;$: $$\calc P(x + 1) \op=\hint{expand abbreviation $\;P\;$; simplify} 0 \le \floor{2x+2} - 2 \floor{x+1} \le 1 \op=\hint{move integer $2$ out of left floor, and $1$ out of right floor} 0 \le \floor{2x} + 2 - 2 (\floor{x}+1) \le 1 \op=\hint{simplify; abbreviation $\;P\;$} P(x) \endcalc$$ So we've proven $$ \tag 1 \langle \forall x :: P(x) \;\equiv\; P(x + 1) \rangle $$ which is a kind of 'induction step'. If we can additionally prove the 'base case' $$ \tag 2 \langle \forall x : 0 \le x \lt 1 : P(x) \rangle $$ then by induction our goal $\;\langle \forall x :: P(x) \rangle\;$ follows. We can prove $\Ref 2$ as follows: assuming $\;0 \le x \lt 1\;$, we have $$\calc P(x) \op=\hint{abbreviation $\;P\;$} 0 \le \floor{2x} - 2 \floor{x} \le 1 \op=\hints{by our assumption and the definition of $\;\floor{\cdot}\;$} \hints{we have $\;0 \le \floor{x} \lt 1\;$, and $\;\floor{\cdot}\;$ is integer,} \hint{so $\;\floor{x} = 0\;$} 0 \le \floor{2x} \le 1 \op=\hints{by our assumption and the definition of $\;\floor{\cdot}\;$} \hint{we have $\;0 \le \floor{2x} \lt 2\;$; $\;\floor{\cdot}\;$ is integer} \true \endcalc$$ This completes the proof.
50,248,178
I am trying to scan for beacons using [startScan(filters, settings, callbackIntent)](https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.app.PendingIntent)). I have an implementation that works fine for Sony Xperia XZ, and Nexus 5X. The only other device with Android O I have available is a Samsung Galaxy S8, and what works for the other devices produce nothing on the Samsung. (The bluetooth scan is really imbedded in a library module, but even when creating a dummy app the samsung fails, so I'll use that in this example). I have removed the filter and the settings used for `startScan` since the scan doesn't work without them anyway and these are optional. ``` MainActivity - checks and asks for permissions (ACCESS_COARSE_LOCATION) - simplified onStart override fun onStart() { super.onStart() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val startScan = bleScanner.startScan(null, null, getPendingIntent()) Log.d("testApp", "Start scan! ${startScan == 0}") } } ``` PendingIntent: ``` private fun getPendingIntent(): PendingIntent { return PendingIntent.getBroadcast( this, REQ_CODE, Intent(this.applicationContext, BleReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT) } ``` **Manifest** Permissions: ``` <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ``` Receiver: ``` <receiver android:name="com.testapp.samsungoscan.BleReceiver" > <intent-filter> <action android:name="BluetoothDevice.ACTION_FOUND" /> <action android:name="BluetoothDevice.EXTRA_UUID" /> <action android:name="BluetoothDevice.EXTRA_RSSI" /> </intent-filter> </receiver> ``` Receiver implementation: ``` class BleReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.e("testApp", "On Receive!") } } ``` So! Why is this not working for Samsung, while it works for Sony and Nexus? Note: If I change the receivers `android:name` to a relative path `.BleReceiver` instead of `com.testapp.samsungoscan.BleReceiver`, then the Nexus stops working, but Sony still works! By work I mean all classes gets used and the logs are triggered. What is wrong?
2018/05/09
[ "https://Stackoverflow.com/questions/50248178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570640/" ]
You have registered the broadcast receiver in the AndroidManifest.xml with an Intent Filter name `<action android:name="BluetoothDevice.ACTION_FOUND" />` First of all, you may provide there any String. Above suggest that you are using [this constant](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_FOUND), but in fact you are just using the String as is (`BluetoothDevice.ACTION_FOUND`). I would recommend changing it to some `com.testapp.samsungoscan.ACTION_FOUND`. The Extras are not needed and they suggest they are in fact extras, but they are just another action names with name "extra". I recommend changing to: ``` <receiver android:name="com.testapp.samsungoscan.BleReceiver"> <intent-filter> <action android:name="com.testapp.samsungoscan.ACTION_FOUND" /> </intent-filter> </receiver> ``` Secondly, you have to create the PendingIntent with this action name: ``` private fun getPendingIntent(): PendingIntent { return PendingIntent.getBroadcast( this, REQ_CODE, Intent(this.applicationContext, BleReceiver::class.java).setAction("com.testapp.samsungoscan.ACTION_FOUND"), PendingIntent.FLAG_UPDATE_CURRENT) } ``` Creating an intent with providing Component name is required since Oreo to be able to get any broadcasts. I'm not sure, however, will it work after your app has been killed by the system. Lastly, I recommend requesting FINE\_LOCATION, as this: <https://android-review.googlesource.com/c/platform/packages/apps/Bluetooth/+/848935> change may in the future require fine location permission to scan for Bluetooth devices.
You need to pass an empty filters list to the startScan() call instead of null ``` List<ScanFilter> listOfFiters = new ArrayList<>(); ScanFilter.Builder builder = new ScanFilter.Builder(); ScanFilter filter = builder.build(); listOfFiters.add(filter); bleScanner.startScan(listOfFilters, null, getPendingIntent()) ```
50,248,178
I am trying to scan for beacons using [startScan(filters, settings, callbackIntent)](https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.app.PendingIntent)). I have an implementation that works fine for Sony Xperia XZ, and Nexus 5X. The only other device with Android O I have available is a Samsung Galaxy S8, and what works for the other devices produce nothing on the Samsung. (The bluetooth scan is really imbedded in a library module, but even when creating a dummy app the samsung fails, so I'll use that in this example). I have removed the filter and the settings used for `startScan` since the scan doesn't work without them anyway and these are optional. ``` MainActivity - checks and asks for permissions (ACCESS_COARSE_LOCATION) - simplified onStart override fun onStart() { super.onStart() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val startScan = bleScanner.startScan(null, null, getPendingIntent()) Log.d("testApp", "Start scan! ${startScan == 0}") } } ``` PendingIntent: ``` private fun getPendingIntent(): PendingIntent { return PendingIntent.getBroadcast( this, REQ_CODE, Intent(this.applicationContext, BleReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT) } ``` **Manifest** Permissions: ``` <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ``` Receiver: ``` <receiver android:name="com.testapp.samsungoscan.BleReceiver" > <intent-filter> <action android:name="BluetoothDevice.ACTION_FOUND" /> <action android:name="BluetoothDevice.EXTRA_UUID" /> <action android:name="BluetoothDevice.EXTRA_RSSI" /> </intent-filter> </receiver> ``` Receiver implementation: ``` class BleReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.e("testApp", "On Receive!") } } ``` So! Why is this not working for Samsung, while it works for Sony and Nexus? Note: If I change the receivers `android:name` to a relative path `.BleReceiver` instead of `com.testapp.samsungoscan.BleReceiver`, then the Nexus stops working, but Sony still works! By work I mean all classes gets used and the logs are triggered. What is wrong?
2018/05/09
[ "https://Stackoverflow.com/questions/50248178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570640/" ]
You have registered the broadcast receiver in the AndroidManifest.xml with an Intent Filter name `<action android:name="BluetoothDevice.ACTION_FOUND" />` First of all, you may provide there any String. Above suggest that you are using [this constant](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_FOUND), but in fact you are just using the String as is (`BluetoothDevice.ACTION_FOUND`). I would recommend changing it to some `com.testapp.samsungoscan.ACTION_FOUND`. The Extras are not needed and they suggest they are in fact extras, but they are just another action names with name "extra". I recommend changing to: ``` <receiver android:name="com.testapp.samsungoscan.BleReceiver"> <intent-filter> <action android:name="com.testapp.samsungoscan.ACTION_FOUND" /> </intent-filter> </receiver> ``` Secondly, you have to create the PendingIntent with this action name: ``` private fun getPendingIntent(): PendingIntent { return PendingIntent.getBroadcast( this, REQ_CODE, Intent(this.applicationContext, BleReceiver::class.java).setAction("com.testapp.samsungoscan.ACTION_FOUND"), PendingIntent.FLAG_UPDATE_CURRENT) } ``` Creating an intent with providing Component name is required since Oreo to be able to get any broadcasts. I'm not sure, however, will it work after your app has been killed by the system. Lastly, I recommend requesting FINE\_LOCATION, as this: <https://android-review.googlesource.com/c/platform/packages/apps/Bluetooth/+/848935> change may in the future require fine location permission to scan for Bluetooth devices.
Ah, and in addition to passing empty filter to the startScan you will also need ACCESS\_FINE\_LOCATION permission on latest Android versions.
186,283
Now I am using the pull-down menus to set `:TTarget`, `:TCTarget`, and `:TVTarget` to `pdf`. I also tried setting `g:Tex_DefaultTargetFormat='pdf'` and `g:tex_flavor='pdflatex'`, but neither worked. Thanks!
2010/09/08
[ "https://superuser.com/questions/186283", "https://superuser.com", "https://superuser.com/users/45020/" ]
Set ``` let g:Tex_DefaultTargetFormat = 'pdf' let g:Tex_MultipleCompileFormats='pdf, aux' ``` in your config file for vim (e.g. `~/.vimrc`). That works well for me here, using vim 7.3.3 on Arch Linux.
Add the following lines to ~/.vim/ftplugin/tex.vim (create the file if it doesn't already exist). ``` let g:Tex_DefaultTargetFormat = 'pdf' let g:Tex_MultipleCompileFormats='pdf, aux' ``` This is the same as [evnu's solution](https://superuser.com/a/186288/184674), but without cluttering up your vimrc.
322,594
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out? ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ; awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2 ``` Changing ";" to "&&" doesn't work either. Both file1 and file2 is created, but only file1 contains data. So basically what I want to do is using the same variables for two commands
2011/10/18
[ "https://serverfault.com/questions/322594", "https://serverfault.com", "https://serverfault.com/users/97188/" ]
When you want to run two different commands on the same incoming pipe data, you need to use an intermediate file: ``` TMPFILE="$(mktemp)" /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' >"$TMPFILE" awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' <"$TMPFILE" >>/tmp/file1 awk '{print $1":"$5":13753:0:99999:7:::"}' <"$TMPFILE" >>/tmp/file2 rm -f "$TMPFILE" ``` But as [quanta writes](https://serverfault.com/questions/322594/double-awk-commands-in-same-pipe/322613#322613), you can ask a single `awk` instance to do both operations.
You've made quite a mess, starting with the formatting of your question (see what I've done above which should make things below more clear). ***First problem:*** If you have a semicolon (`;`) or a "continue-on-success (`&&`) you are running two separate sets of commands. Completely separate. It's like you ran one, hit enter and then ran the other. This means your second `awk` is looking on stdin for input, and not finding anything it's giving you no output (which is why `file2` is empty) ***Second Problem:*** Separate instances of `awk` can't share variables. Either you want the second `awk` to chew on the output of the MySQL query, or you want it to chew on the output of the first `awk`. Since you've got 5 variables in your second `awk` I'm assuming the latter. ***Solution*** Run the first half of the command list (everything up to the semicolon). Now run the second awk, and specify an input file (`awk '{print $1":"$5":13753:0:99999:7:::"}' /tmp/file1 >> /tmp/file2`).
322,594
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out? ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ; awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2 ``` Changing ";" to "&&" doesn't work either. Both file1 and file2 is created, but only file1 contains data. So basically what I want to do is using the same variables for two commands
2011/10/18
[ "https://serverfault.com/questions/322594", "https://serverfault.com", "https://serverfault.com/users/97188/" ]
When you want to run two different commands on the same incoming pipe data, you need to use an intermediate file: ``` TMPFILE="$(mktemp)" /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' >"$TMPFILE" awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' <"$TMPFILE" >>/tmp/file1 awk '{print $1":"$5":13753:0:99999:7:::"}' <"$TMPFILE" >>/tmp/file2 rm -f "$TMPFILE" ``` But as [quanta writes](https://serverfault.com/questions/322594/double-awk-commands-in-same-pipe/322613#322613), you can ask a single `awk` instance to do both operations.
Your command as shown will never work, as processing is entirely sequential, and the output of mysql is already used up by the first awk statement. I would simply move all that to a tiny bash script: ``` #!/bin/bash mycmd="SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`" while read -r username, uid, gid, homedir; do printf "%s:x:%s:%s::%s:/usr/sbin/nologin" "$username" "$uid" "$gid" "$homedir" >> /tmp/file1 printf "%s:%s:13753:0:99999:7:::" "$username" "missing variable" >>/tmp/file2 done <(/usr/bin/mysql -B -r -h * -u* -p* -D* -e "$mycmd") ``` UNtested, visit the [Wooledge Wiki](http://mywiki.wooledge.org/BashGuide) for more bash magic than you knew existed :)
322,594
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out? ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ; awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2 ``` Changing ";" to "&&" doesn't work either. Both file1 and file2 is created, but only file1 contains data. So basically what I want to do is using the same variables for two commands
2011/10/18
[ "https://serverfault.com/questions/322594", "https://serverfault.com", "https://serverfault.com/users/97188/" ]
Try this: ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{ print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin" >> "/tmp/file1"; print $1":"$5":13753:0:99999:7:::" >> "/tmp/file2" }' ```
When you want to run two different commands on the same incoming pipe data, you need to use an intermediate file: ``` TMPFILE="$(mktemp)" /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' >"$TMPFILE" awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' <"$TMPFILE" >>/tmp/file1 awk '{print $1":"$5":13753:0:99999:7:::"}' <"$TMPFILE" >>/tmp/file2 rm -f "$TMPFILE" ``` But as [quanta writes](https://serverfault.com/questions/322594/double-awk-commands-in-same-pipe/322613#322613), you can ask a single `awk` instance to do both operations.
322,594
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out? ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ; awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2 ``` Changing ";" to "&&" doesn't work either. Both file1 and file2 is created, but only file1 contains data. So basically what I want to do is using the same variables for two commands
2011/10/18
[ "https://serverfault.com/questions/322594", "https://serverfault.com", "https://serverfault.com/users/97188/" ]
You've made quite a mess, starting with the formatting of your question (see what I've done above which should make things below more clear). ***First problem:*** If you have a semicolon (`;`) or a "continue-on-success (`&&`) you are running two separate sets of commands. Completely separate. It's like you ran one, hit enter and then ran the other. This means your second `awk` is looking on stdin for input, and not finding anything it's giving you no output (which is why `file2` is empty) ***Second Problem:*** Separate instances of `awk` can't share variables. Either you want the second `awk` to chew on the output of the MySQL query, or you want it to chew on the output of the first `awk`. Since you've got 5 variables in your second `awk` I'm assuming the latter. ***Solution*** Run the first half of the command list (everything up to the semicolon). Now run the second awk, and specify an input file (`awk '{print $1":"$5":13753:0:99999:7:::"}' /tmp/file1 >> /tmp/file2`).
Your command as shown will never work, as processing is entirely sequential, and the output of mysql is already used up by the first awk statement. I would simply move all that to a tiny bash script: ``` #!/bin/bash mycmd="SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`" while read -r username, uid, gid, homedir; do printf "%s:x:%s:%s::%s:/usr/sbin/nologin" "$username" "$uid" "$gid" "$homedir" >> /tmp/file1 printf "%s:%s:13753:0:99999:7:::" "$username" "missing variable" >>/tmp/file2 done <(/usr/bin/mysql -B -r -h * -u* -p* -D* -e "$mycmd") ``` UNtested, visit the [Wooledge Wiki](http://mywiki.wooledge.org/BashGuide) for more bash magic than you knew existed :)
322,594
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out? ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ; awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2 ``` Changing ";" to "&&" doesn't work either. Both file1 and file2 is created, but only file1 contains data. So basically what I want to do is using the same variables for two commands
2011/10/18
[ "https://serverfault.com/questions/322594", "https://serverfault.com", "https://serverfault.com/users/97188/" ]
Try this: ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{ print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin" >> "/tmp/file1"; print $1":"$5":13753:0:99999:7:::" >> "/tmp/file2" }' ```
You've made quite a mess, starting with the formatting of your question (see what I've done above which should make things below more clear). ***First problem:*** If you have a semicolon (`;`) or a "continue-on-success (`&&`) you are running two separate sets of commands. Completely separate. It's like you ran one, hit enter and then ran the other. This means your second `awk` is looking on stdin for input, and not finding anything it's giving you no output (which is why `file2` is empty) ***Second Problem:*** Separate instances of `awk` can't share variables. Either you want the second `awk` to chew on the output of the MySQL query, or you want it to chew on the output of the first `awk`. Since you've got 5 variables in your second `awk` I'm assuming the latter. ***Solution*** Run the first half of the command list (everything up to the semicolon). Now run the second awk, and specify an input file (`awk '{print $1":"$5":13753:0:99999:7:::"}' /tmp/file1 >> /tmp/file2`).
322,594
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out? ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ; awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2 ``` Changing ";" to "&&" doesn't work either. Both file1 and file2 is created, but only file1 contains data. So basically what I want to do is using the same variables for two commands
2011/10/18
[ "https://serverfault.com/questions/322594", "https://serverfault.com", "https://serverfault.com/users/97188/" ]
Try this: ``` /usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \ -e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \ awk '{ print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin" >> "/tmp/file1"; print $1":"$5":13753:0:99999:7:::" >> "/tmp/file2" }' ```
Your command as shown will never work, as processing is entirely sequential, and the output of mysql is already used up by the first awk statement. I would simply move all that to a tiny bash script: ``` #!/bin/bash mycmd="SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`" while read -r username, uid, gid, homedir; do printf "%s:x:%s:%s::%s:/usr/sbin/nologin" "$username" "$uid" "$gid" "$homedir" >> /tmp/file1 printf "%s:%s:13753:0:99999:7:::" "$username" "missing variable" >>/tmp/file2 done <(/usr/bin/mysql -B -r -h * -u* -p* -D* -e "$mycmd") ``` UNtested, visit the [Wooledge Wiki](http://mywiki.wooledge.org/BashGuide) for more bash magic than you knew existed :)
973,548
![enter image description here](https://i.stack.imgur.com/ZSOJc.jpg)In Fig.$9.17$ $PQRS$ and $ABRS$ are parallelograms and $X$ is any point on side $BR$. Show that i) $[PQRS]=[ABRS]$ ii)$[AXS]=1/2\cdot [PQRS]$ I have no clue.
2014/10/14
[ "https://math.stackexchange.com/questions/973548", "https://math.stackexchange.com", "https://math.stackexchange.com/users/162079/" ]
I can already see one mistake in that $$\ln|y-1|=\int(y-1)^{-1}\;dy\neq-\ln(y-1).$$ Also, you ought to note in the derivation of this technique in solving separable ODE (i.e. an application of the chain rule) that you can incorporate the initial conditions in the integration, avoiding arbitrary constants and making more concrete that you are solving an IVP. In particular we have for this IVP, $$\int\_{-3}^{y}(z-1)^{-1}\;dz=\int\_{2}^{t}-3\;du$$ $$\ln|y-1|-\ln|-4|=-3t+6$$ $$y-1=e^{-3t+6+\ln 4}.$$ Therefore (after factoring the exponential and noting $e^{\ln 4}=4$), $$y=y(t)=1+4e^{6-3t}.$$
There is an error in the fourth equation. $$ \int\frac{dy}{y-1}=\ln(y-1). $$
973,548
![enter image description here](https://i.stack.imgur.com/ZSOJc.jpg)In Fig.$9.17$ $PQRS$ and $ABRS$ are parallelograms and $X$ is any point on side $BR$. Show that i) $[PQRS]=[ABRS]$ ii)$[AXS]=1/2\cdot [PQRS]$ I have no clue.
2014/10/14
[ "https://math.stackexchange.com/questions/973548", "https://math.stackexchange.com", "https://math.stackexchange.com/users/162079/" ]
I can already see one mistake in that $$\ln|y-1|=\int(y-1)^{-1}\;dy\neq-\ln(y-1).$$ Also, you ought to note in the derivation of this technique in solving separable ODE (i.e. an application of the chain rule) that you can incorporate the initial conditions in the integration, avoiding arbitrary constants and making more concrete that you are solving an IVP. In particular we have for this IVP, $$\int\_{-3}^{y}(z-1)^{-1}\;dz=\int\_{2}^{t}-3\;du$$ $$\ln|y-1|-\ln|-4|=-3t+6$$ $$y-1=e^{-3t+6+\ln 4}.$$ Therefore (after factoring the exponential and noting $e^{\ln 4}=4$), $$y=y(t)=1+4e^{6-3t}.$$
~ SPOILER ALERT: Here's the solution. ~ $\frac{dy}{dt}=-3(y-1)$ with $y(2)=-3$ $$\frac{dy}{dt}=-3(y-1)$$ $$\frac{1}{y-1}dy=-3dt, where \space y≠1$$ $$\int\frac{1}{y-1}dy=\int-3dt$$ $$ln|y-1|=-3t+C$$ $$e^{ln|y-1|}=e^{-3t+C}$$ $$|y-1|=C\*e^{-3t}$$ $$y-1=C\*e^{-3t}$$ Note: I removed the absolute value sign because either case (i.e., |y-1| = y-1 and |y-1| = 1-y) will get us the same end result; you could verify this yourself. $$y=C\*e^{-3t}+1$$ Now use your initial value: $y=C\*e^{-3t}+1$, where $y(2)=-3$ $$-3=C\*e^{-3(2)}+1$$ $$-3=C\*e^{-6}+1$$ $$-4=C\*e^{-6}$$ Thus, $C = -4e^6$. Plug that into your initial $y(t)$ and you should get: $$y=-4e^{6-3t}+1.$$
14,348,930
We recently upgraded all of our projects to Visual Studio 2012 and .Net 4.5. Most of our projects have custom MMC snapins that handle product configuration. I've now learned that MMC 3.0 doesn't natively handle the .Net 4.0 runtime, since the runtime shipped long after MMC 3.0 was released. I'm looking for a way to fix our snapins so that MMC doesn't crash when they are loaded and I've come across a lot of pages that mention adding an mmc.exe.config file. I've tried this, and I can't get it to work. I've created a file with this as its contents: ``` <configuration> <startup> <supportedRuntime version='v4.0.20506' /> <requiredRuntime version='v4.0.20506' safemode='true' /> </startup> </configuration> ``` I have saved this as mmc.exe.config in both the windows\system32 and windows\sysWOW64 directories, however the presence of this file makes no difference. My snapins still crash with the same error message: ``` Could not load file or assembly 'xxxx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d62dabb4275ffafc' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. ``` What do I need to do to get MMC to load .Net 4.0 runtime assemblies properly?
2013/01/15
[ "https://Stackoverflow.com/questions/14348930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125882/" ]
For me it works to tell MMC to use the v4 Framework, I've got v4.0.30319 ``` set COMPLUS_version=v4.0.30319 start SomeConsole.msc ``` Check the workarounds: <http://connect.microsoft.com/VisualStudio/feedback/details/474039/can-not-use-net-4-0-to-create-mmc-snapin> And this are my debug settings:![enter image description here](https://i.stack.imgur.com/vYdFd.png) I use the 32 bit version of the console, and also had to add the into the "c\Windows\SysWOW64\mmc.exe.config" the following: ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version='v4.0' /> </startup> </configuration> ``` Hope it helps you. GL
Take a look at comments on this page (<http://msdn.microsoft.com/en-us/library/ms692759%28VS.85%29.aspx>). It looks like managed MMC snap-ins can target at most framework 3.5.
17,947,251
I have 2 class, classA and classB. ObjectA have a property which is ObjectB. Now the scenario is- 1. ObjectA call ObjectB method- [ObjectB methodB1]. 2. after executing method [ObjectB methodB1], objectB send callback to objectA. 3. getting callback ObjectA release ObjectB. did it following way- [ObjectB release]; ObjectB = nil; 4. ObjectB has another method ->methodB2, which starts executing [ObjectB methodB2] just after sending callback to objectA and it crashes because ObjectA released ObjectB when it's executing, so there is no object then ObjectB. So if how to solve this problem? Thanks for your answer.
2013/07/30
[ "https://Stackoverflow.com/questions/17947251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168394/" ]
move your callback to ObjectA just after the execution of [ObjectB methodB2]. Or create two callbacks : one after [ObjectB methodB1] and another after [ObjectB methodB2] and release ObjectB after the second callback
``` ObjectB.ObjectA = nil; [ObjectB release]; ObjectB = nil; ```
17,947,251
I have 2 class, classA and classB. ObjectA have a property which is ObjectB. Now the scenario is- 1. ObjectA call ObjectB method- [ObjectB methodB1]. 2. after executing method [ObjectB methodB1], objectB send callback to objectA. 3. getting callback ObjectA release ObjectB. did it following way- [ObjectB release]; ObjectB = nil; 4. ObjectB has another method ->methodB2, which starts executing [ObjectB methodB2] just after sending callback to objectA and it crashes because ObjectA released ObjectB when it's executing, so there is no object then ObjectB. So if how to solve this problem? Thanks for your answer.
2013/07/30
[ "https://Stackoverflow.com/questions/17947251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168394/" ]
move your callback to ObjectA just after the execution of [ObjectB methodB2]. Or create two callbacks : one after [ObjectB methodB1] and another after [ObjectB methodB2] and release ObjectB after the second callback
`methodB1` should retain `self` when it starts and release it when it finishes.
17,947,251
I have 2 class, classA and classB. ObjectA have a property which is ObjectB. Now the scenario is- 1. ObjectA call ObjectB method- [ObjectB methodB1]. 2. after executing method [ObjectB methodB1], objectB send callback to objectA. 3. getting callback ObjectA release ObjectB. did it following way- [ObjectB release]; ObjectB = nil; 4. ObjectB has another method ->methodB2, which starts executing [ObjectB methodB2] just after sending callback to objectA and it crashes because ObjectA released ObjectB when it's executing, so there is no object then ObjectB. So if how to solve this problem? Thanks for your answer.
2013/07/30
[ "https://Stackoverflow.com/questions/17947251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168394/" ]
move your callback to ObjectA just after the execution of [ObjectB methodB2]. Or create two callbacks : one after [ObjectB methodB1] and another after [ObjectB methodB2] and release ObjectB after the second callback
two scenario's here: 1) ObjectB could have different properties passed to it when called by ObjectA the two times 2) Object B is only ever passed one set of properties and Object A needs Bethod B1 and B2 to run while ObjectB retains the same properties. 3) Use getters and setters if object B needs new parameters passed to it? Scenario 1: ObjectA.m: ``` ... ObjectB *objectB = [[ObjectB alloc] initWithSomeParameter:@"the parameter"]; NSString *callback1 = [objectB methodB1]; // why release when you can repoint? ObjectB *objectB = [[ObjectB alloc] initWithSomeParameter:@"another parameter"]; NSString *callback2 = [objectB methodB2]; [objectB release]; ``` Scenario 2: ObjectA.m: ``` ... ObjectB *objectB = [[ObjectB alloc] initWithSomeParameter:@"the parameter"]; NSString *callback1 = [objectB methodB1]; NSString *callback2 = [objectB methodB2]; [objectB release]; ``` Scenario 3: ObjectA.m: ``` ... ObjectB *objectB = [[ObjectB alloc] initWithSomeParameter:@"the parameter"]; NSString *callback1 = [objectB methodB1]; [objectB setSomeParameter:@"another parameter"]; NSString *callback2 = [objectB methodB2]; [objectB release]; ``` When you say ObjectB calls back? I hope you don't mean: ObjectA.m: ``` ObjectB *objectB = [[ObjectB alloc] initWithSomeParameter:@"the parameter"]; NSString *callback1 = [objectB methodB1]; ... ``` ObjectB.m: ``` ... //DO some work in method B1 ObjectA *objectA [[ObjectA alloc] init]; [objectA callback]; ``` That's a memory lead looming over you right there and then... If this IS what you mean, then I'd advise reading my above scenario's or looking at NSNotificationCentre Notifications for cross object notifications i.e. callbacks.
51,897,851
Lets say I have a method which I decorate with `@property`. Is there a way to get the underlying name of the decorated method? How could I for instance print the name of the property when it does not have a `__name__` attribute? I'm trying to do a RPC call and everything works for methods and static functions but not this.
2018/08/17
[ "https://Stackoverflow.com/questions/51897851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7917697/" ]
A property has the following attributes: *fget*, *fset* and *fdel*, which are references to the getter/setter/deleter functions. So, you can get the `__name__` of each of this functions (if not `None`) Demo: ``` class Thing(object): @property def foo(self): return "foo" def get_baz(self): return "baz" bar = property(get_baz) >>> Thing.foo.fget.__name__ 'foo' >>> Thing.bar.fget.__name__ 'get_baz' ```
i think if use decorator @property you can access your function with name of function and you can give return value. ``` class Foo: value = 'Foo' def setName(self, name): self.value = name @property def name(self): return "You name is: {}".format(self.value) foo = Foo() print(foo.name) foo.setName('Bar') print(foo.name) ```
51,897,851
Lets say I have a method which I decorate with `@property`. Is there a way to get the underlying name of the decorated method? How could I for instance print the name of the property when it does not have a `__name__` attribute? I'm trying to do a RPC call and everything works for methods and static functions but not this.
2018/08/17
[ "https://Stackoverflow.com/questions/51897851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7917697/" ]
A property has the following attributes: *fget*, *fset* and *fdel*, which are references to the getter/setter/deleter functions. So, you can get the `__name__` of each of this functions (if not `None`) Demo: ``` class Thing(object): @property def foo(self): return "foo" def get_baz(self): return "baz" bar = property(get_baz) >>> Thing.foo.fget.__name__ 'foo' >>> Thing.bar.fget.__name__ 'get_baz' ```
If you use [`functools.wraps()`](https://docs.python.org/3/library/functools.html#functools.wraps) in your decorator, the decorated function *will* have the `__name__` of the wrapped function. IF you had some sample code for the decorator in your question, I could show more precisely how to do this...
8,450,027
I have a C app (VStudio 2010, win7 64bit) running on a machine with dual xeon chips, meaning 12 physical and 24 logical cores, and 192 gig of ram. EDIT: THE OS is win7 (ie, Windows 7, 64 bit). The app has 24 threads (each thread has its own logical core) doing calculations and filling up a different part of a massive C structure. The structure, when all the threads are finished (and the threads are all perfectly balanced so they complete at the same time), is about 60 gigabytes. (I have control over the hardware setup, so I am going to be using 6 2tb drives running RAID 0, which means the physical limits on writing will be approximately 6x the average sequential write speed, or about 2 gig/second.) What is the most efficient way to get this to disk? Obviously, the i/o time will dwarf the compute time. From my research on this topic, it seems like write() (as opposed to fwrite()) is the way to go. But what other optimizations can I do on the software side, in terms of setting buffer sizes, etc. Would mmap be more efficient?
2011/12/09
[ "https://Stackoverflow.com/questions/8450027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/994179/" ]
It is hard to judge the best thing for your situation. The first optimization to make is to preallocate the file. That way your file system does not need to keep extending its size. That should optimize some disk operations. However, avoid writing actual zeros to disk. Just set the length. Then you have choices between mmap and write. This also depends on the operating system you use. On a Unix I would try both mmap and pwrite. pwrite is useful because each of your threads can write into the file at the desired file position without fighting over file offsets. mmap could be good because instead of making copies into file cache, your threads would be writing directly into file cache. 60 GB is probably too large to mmap the entire file, so each thread will likely need its own mmap window onto the file which it can move around. In Windows you would probably want to try using overlapped, asynchronous IO. That can only be done with Win32 API calls.
mmap(), or [boost mmap](http://www.boost.org/doc/libs/1_41_0/libs/iostreams/doc/classes/mapped_file.html) is almost always the best approach. The OS is smarter than you, let it worry about what to cache! You didn't say what OS, but on Linux the [madvise](http://www.gnu.org/s/hello/manual/libc/Memory_002dmapped-I_002fO.html), or equivalent boost hints can really boost performance.
2,532,008
I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for) Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.
2010/03/28
[ "https://Stackoverflow.com/questions/2532008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
`\W` is a shorthand for `[^\w]`. So: ``` [^\w-]+ ``` A bit of background: * `[…]` defines a set * `[^…]` negates a set * Generally, every `\v` (smallcase) set is negated by a `\V` (uppercase) where V is any letter that defines a set. * for international characters, you may want to look into `[[:alpha:]]` and `[[:alnum:]]`
``` [^\w-]+ ``` will do just that. Match any characters not in the `\w` set except hyphen.
2,532,008
I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for) Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.
2010/03/28
[ "https://Stackoverflow.com/questions/2532008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
``` [^\w-]+ ``` will do just that. Match any characters not in the `\w` set except hyphen.
In Java7 or above, you need to prepend the `(?U)` to match all locale specific characters. e.g. ``` (?U)[^\w-] ``` In a Java string (you need to escape `\` character with another one): ``` (?U)[^\\w-] ```
2,532,008
I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for) Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.
2010/03/28
[ "https://Stackoverflow.com/questions/2532008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
`\W` is a shorthand for `[^\w]`. So: ``` [^\w-]+ ``` A bit of background: * `[…]` defines a set * `[^…]` negates a set * Generally, every `\v` (smallcase) set is negated by a `\V` (uppercase) where V is any letter that defines a set. * for international characters, you may want to look into `[[:alpha:]]` and `[[:alnum:]]`
You can use: ``` [^a-zA-Z0-9_-] ``` or ``` [^\w-] ``` to match a single non-hyphen, non-alphanumeric. To match one or more of then prefix with a `+`
2,532,008
I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for) Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.
2010/03/28
[ "https://Stackoverflow.com/questions/2532008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
`\W` is a shorthand for `[^\w]`. So: ``` [^\w-]+ ``` A bit of background: * `[…]` defines a set * `[^…]` negates a set * Generally, every `\v` (smallcase) set is negated by a `\V` (uppercase) where V is any letter that defines a set. * for international characters, you may want to look into `[[:alpha:]]` and `[[:alnum:]]`
In Java7 or above, you need to prepend the `(?U)` to match all locale specific characters. e.g. ``` (?U)[^\w-] ``` In a Java string (you need to escape `\` character with another one): ``` (?U)[^\\w-] ```
2,532,008
I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for) Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.
2010/03/28
[ "https://Stackoverflow.com/questions/2532008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
You can use: ``` [^a-zA-Z0-9_-] ``` or ``` [^\w-] ``` to match a single non-hyphen, non-alphanumeric. To match one or more of then prefix with a `+`
In Java7 or above, you need to prepend the `(?U)` to match all locale specific characters. e.g. ``` (?U)[^\w-] ``` In a Java string (you need to escape `\` character with another one): ``` (?U)[^\\w-] ```
51,114,273
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML here's a screenshot [![enter image description here](https://i.stack.imgur.com/VHUup.png)](https://i.stack.imgur.com/VHUup.png) The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part. Here's my CSS. [![enter image description here](https://i.stack.imgur.com/MPlxQ.png)](https://i.stack.imgur.com/MPlxQ.png) ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="index.css"> </head> ```
2018/06/30
[ "https://Stackoverflow.com/questions/51114273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014388/" ]
Try this `<link rel="stylesheet" type="text/css" href="./index.css">`
I think you did not save your project(blue Dot on the tab). First save your project by Ctrl+S and the review the page.
51,114,273
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML here's a screenshot [![enter image description here](https://i.stack.imgur.com/VHUup.png)](https://i.stack.imgur.com/VHUup.png) The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part. Here's my CSS. [![enter image description here](https://i.stack.imgur.com/MPlxQ.png)](https://i.stack.imgur.com/MPlxQ.png) ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="index.css"> </head> ```
2018/06/30
[ "https://Stackoverflow.com/questions/51114273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014388/" ]
Try this `<link rel="stylesheet" type="text/css" href="./index.css">`
Close the html tag at the end & be sure to save both the files in same folder
51,114,273
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML here's a screenshot [![enter image description here](https://i.stack.imgur.com/VHUup.png)](https://i.stack.imgur.com/VHUup.png) The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part. Here's my CSS. [![enter image description here](https://i.stack.imgur.com/MPlxQ.png)](https://i.stack.imgur.com/MPlxQ.png) ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="index.css"> </head> ```
2018/06/30
[ "https://Stackoverflow.com/questions/51114273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014388/" ]
This is how you troubleshoot HTML and CSS: 1. Open your index.html in a browser. E.g.: Chrome 2. Open Developer Tools. In the case of Chrome, right click and click Inspect in the menu. 3. You will be shown something like the image below. [![Developer tools in Elements tab](https://i.stack.imgur.com/Ad9t8.png)](https://i.stack.imgur.com/Ad9t8.png) 4. In the elements tab, check in the `<head>` and check that your stylesheet is included. 5. If it is included, click on the link to see if it opens up a new page with the styles in it as raw text. e.g.: <https://cdn.sstatic.net/Sites/stackoverflow/primary-unified.css?v=7f46f0b7e1bb> 6. If it is not, you should be playing around with above answers regarding paths. 7. As an alternative, try including the styles directly into the `<head>` like this: ```css ``` ```html <head> <style type="text/css"> body { background-color: blue; } </style> </head> <body> <h1>Test</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> </body> ```
I think you did not save your project(blue Dot on the tab). First save your project by Ctrl+S and the review the page.
51,114,273
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML here's a screenshot [![enter image description here](https://i.stack.imgur.com/VHUup.png)](https://i.stack.imgur.com/VHUup.png) The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part. Here's my CSS. [![enter image description here](https://i.stack.imgur.com/MPlxQ.png)](https://i.stack.imgur.com/MPlxQ.png) ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="index.css"> </head> ```
2018/06/30
[ "https://Stackoverflow.com/questions/51114273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014388/" ]
Without more accurate specification, we can try to solve generally all troubles. These are my advices. 1 Be careful saving your files before uploading. 2 Link stylesheet with relative paths like the posts before. 3 add ‘file version’ of your css script. In this way your browser will reload all css styles. (Very important for you and all your user in future when editing templates) Simply add this in link stylesheet html tag ``` version=1.3 ``` And change values every time you edit css and upload files 4 *testing css* you could test your css working with `element inspector` of your browser. Hope it will be useful!
I think you did not save your project(blue Dot on the tab). First save your project by Ctrl+S and the review the page.
51,114,273
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML here's a screenshot [![enter image description here](https://i.stack.imgur.com/VHUup.png)](https://i.stack.imgur.com/VHUup.png) The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part. Here's my CSS. [![enter image description here](https://i.stack.imgur.com/MPlxQ.png)](https://i.stack.imgur.com/MPlxQ.png) ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="index.css"> </head> ```
2018/06/30
[ "https://Stackoverflow.com/questions/51114273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014388/" ]
This is how you troubleshoot HTML and CSS: 1. Open your index.html in a browser. E.g.: Chrome 2. Open Developer Tools. In the case of Chrome, right click and click Inspect in the menu. 3. You will be shown something like the image below. [![Developer tools in Elements tab](https://i.stack.imgur.com/Ad9t8.png)](https://i.stack.imgur.com/Ad9t8.png) 4. In the elements tab, check in the `<head>` and check that your stylesheet is included. 5. If it is included, click on the link to see if it opens up a new page with the styles in it as raw text. e.g.: <https://cdn.sstatic.net/Sites/stackoverflow/primary-unified.css?v=7f46f0b7e1bb> 6. If it is not, you should be playing around with above answers regarding paths. 7. As an alternative, try including the styles directly into the `<head>` like this: ```css ``` ```html <head> <style type="text/css"> body { background-color: blue; } </style> </head> <body> <h1>Test</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> </body> ```
Close the html tag at the end & be sure to save both the files in same folder
51,114,273
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML here's a screenshot [![enter image description here](https://i.stack.imgur.com/VHUup.png)](https://i.stack.imgur.com/VHUup.png) The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part. Here's my CSS. [![enter image description here](https://i.stack.imgur.com/MPlxQ.png)](https://i.stack.imgur.com/MPlxQ.png) ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="index.css"> </head> ```
2018/06/30
[ "https://Stackoverflow.com/questions/51114273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014388/" ]
Without more accurate specification, we can try to solve generally all troubles. These are my advices. 1 Be careful saving your files before uploading. 2 Link stylesheet with relative paths like the posts before. 3 add ‘file version’ of your css script. In this way your browser will reload all css styles. (Very important for you and all your user in future when editing templates) Simply add this in link stylesheet html tag ``` version=1.3 ``` And change values every time you edit css and upload files 4 *testing css* you could test your css working with `element inspector` of your browser. Hope it will be useful!
Close the html tag at the end & be sure to save both the files in same folder
331,235
I can pair my bluetooth headset with my laptop once. But when I disconnect my headset, I cannot reconnect it again. The only way it works is to restart the bluetooth daemon: ``` service bluetooth restart ``` When I do that, I see following in my log: ``` bluetoothd: Terminating bluetoothd: Stopping hci0 event socket bluetoothd: Stopping SDP server bluetoothd: Exit bluetoothd: Bluetooth daemon 4.99 bluetoothd: Starting SDP server bluetoothd: Excluding (conf) network bluetoothd: Excluding (conf) gatt_example bluetoothd: Excluding (conf) time bluetoothd: Excluding (conf) alert bluetoothd: Failed to open RFKILL control device bluetoothd: Listening for HCI events on hci0 bluetoothd: HCI dev 0 up bluetoothd: Proximity GATT Reporter Driver: Operation not permitted (1) bluetoothd: Could not get the contents of DMI chassis type bluetoothd: Unable to load keys to adapter_ops: Function not implemented (38) bluetoothd: Adapter /org/bluez/8237/hci0 has been enabled ``` then I can successfully connect my headphones: ``` bluetoothd: Can't open input device: No such file or directory (2) bluetoothd: AVRCP: failed to init uinput for 44:66:a7:81:3C:84 bluetoothd: Badly formated or unrecognized command: AT+XEVENT=Bose SoundLink,158 bluetoothd: Badly formated or unrecognized command: AT+BIA=0,0,0,1,1,1,0 ``` But when I disconnect them and try connecting again, it does not work, and I see nothing in the logs. **Why can't I reconnect my headphones after disconnecting? Why do I have to restart bluetooth daemon? How can I fix this ?** I am using `bluez 4.99` on Debian. I am using custom kernel 4.4. I am using alsa (no pulseaudio).
2016/12/18
[ "https://unix.stackexchange.com/questions/331235", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/43007/" ]
It's buggy with certain brands of headsets. I suffer the same problems and this python script to reconnect my bluetooth headset works for me. Make sure to have at least python 3.5 installed. Directions on how to use the script is self explanatory in the header: <https://gist.github.com/pylover/d68be364adac5f946887b85e6ed6e7ae> Edit: I've included the latest code for this script in this answer as a request but I'd recommend getting the latest iteration from the link provided, as the author is always updating the script. ``` #! /usr/bin/env python3.5 """ Fixing bluetooth stereo headphone/headset problem in ubuntu 16.04 and also debian jessie, with bluez5. Workaround for bug: https://bugs.launchpad.net/ubuntu/+source/indicator-sound/+bug/1577197 Run it with python3.5 or higher after pairing/connecting the bluetooth stereo headphone. This will be only fixes the bluez5 problem mentioned above . Licence: Freeware See ``python3.5 a2dp.py -h``. Shorthands: $ alias speakers="a2dp.py 10:08:C1:44:AE:BC" $ alias headphones="a2dp.py 00:22:37:3D:DA:50" $ alias headset="a2dp.py 00:22:37:F8:A0:77 -p hsp" $ speakers Check here for the latest updates: https://gist.github.com/pylover/d68be364adac5f946887b85e6ed6e7ae Thanks to: * https://github.com/DominicWatson, for adding the ``-p/--profile`` argument. * https://github.com/IzzySoft, for mentioning wait before connecting again. * https://github.com/AmploDev, for v0.4.0 * https://github.com/Mihara, for autodetect & autorun service * https://github.com/dabrovnijk, for systemd service Change Log ---------- - 0.5.0 * Autodetect & autorun service - 0.4.1 * Sorting device list - 0.4.0 * Adding ignore_fail argument by @AmploDev. * Sending all available streams into selected sink, after successfull connection by @AmploDev. - 0.3.3 * Updating default sink before turning to ``off`` profile. - 0.3.2 * Waiting a bit: ``-w/--wait`` before connecting again. - 0.3.0 * Adding -p / --profile option for using the same script to switch between headset and A2DP audio profiles - 0.2.5 * Mentioning [mac] argument. - 0.2.4 * Removing duplicated devices in select device list. - 0.2.3 * Matching ANSI escape characters. Tested on 16.10 & 16.04 - 0.2.2 * Some sort of code enhancements. - 0.2.0 * Adding `-V/--version`, `-w/--wait` and `-t/--tries` CLI arguments. - 0.1.1 * Supporting the `[NEW]` prefix for devices & controllers as advised by @wdullaer * Drying the code. """ import sys import re import asyncio import subprocess as sb import argparse __version__ = '0.4.0' HEX_DIGIT_PATTERN = '[0-9A-F]' HEX_BYTE_PATTERN = '%s{2}' % HEX_DIGIT_PATTERN MAC_ADDRESS_PATTERN = ':'.join((HEX_BYTE_PATTERN, ) * 6) DEVICE_PATTERN = re.compile('^(?:.*\s)?Device\s(?P<mac>%s)\s(?P<name>.*)' % MAC_ADDRESS_PATTERN) CONTROLLER_PATTERN = re.compile('^(?:.*\s)?Controller\s(?P<mac>%s)\s(?P<name>.*)' % MAC_ADDRESS_PATTERN) WAIT_TIME = .75 TRIES = 4 PROFILE = 'a2dp' _profiles = { 'a2dp': 'a2dp_sink', 'hsp': 'headset_head_unit', 'off': 'off' } # CLI Arguments parser = argparse.ArgumentParser(prog=sys.argv[0]) parser.add_argument('-e', '--echo', action='store_true', default=False, help='If given, the subprocess stdout will be also printed on stdout.') parser.add_argument('-w', '--wait', default=WAIT_TIME, type=float, help='The seconds to wait for subprocess output, default is: %s' % WAIT_TIME) parser.add_argument('-t', '--tries', default=TRIES, type=int, help='The number of tries if subprocess is failed. default is: %s' % TRIES) parser.add_argument('-p', '--profile', default=PROFILE, help='The profile to switch to. available options are: hsp, a2dp. default is: %s' % PROFILE) parser.add_argument('-V', '--version', action='store_true', help='Show the version.') parser.add_argument('mac', nargs='?', default=None) # Exceptions class SubprocessError(Exception): pass class RetryExceededError(Exception): pass class BluetoothctlProtocol(asyncio.SubprocessProtocol): def __init__(self, exit_future, echo=True): self.exit_future = exit_future self.transport = None self.output = None self.echo = echo def listen_output(self): self.output = '' def not_listen_output(self): self.output = None def pipe_data_received(self, fd, raw): d = raw.decode() if self.echo: print(d, end='') if self.output is not None: self.output += d def process_exited(self): self.exit_future.set_result(True) def connection_made(self, transport): self.transport = transport print('Connection MADE') async def send_command(self, c): stdin_transport = self.transport.get_pipe_transport(0) # noinspection PyProtectedMember stdin_transport._pipe.write(('%s\n' % c).encode()) async def search_in_output(self, expression, fail_expression=None): if self.output is None: return None for l in self.output.splitlines(): if fail_expression and re.search(fail_expression, l, re.IGNORECASE): raise SubprocessError('Expression "%s" failed with fail pattern: "%s"' % (l, fail_expression)) if re.search(expression, l, re.IGNORECASE): return True async def send_and_wait(self, cmd, wait_expression, fail_expression='fail'): try: self.listen_output() await self.send_command(cmd) while not await self.search_in_output(wait_expression.lower(), fail_expression=fail_expression): await wait() finally: self.not_listen_output() async def disconnect(self, mac): print('Disconnecting the device.') await self.send_and_wait('disconnect %s' % ':'.join(mac), 'Successful disconnected') async def connect(self, mac): print('Connecting again.') await self.send_and_wait('connect %s' % ':'.join(mac), 'Connection successful') async def trust(self, mac): await self.send_and_wait('trust %s' % ':'.join(mac), 'trust succeeded') async def quit(self): await self.send_command('quit') async def get_list(self, command, pattern): result = set() try: self.listen_output() await self.send_command(command) await wait() for l in self.output.splitlines(): m = pattern.match(l) if m: result.add(m.groups()) return sorted(list(result), key=lambda i: i[1]) finally: self.not_listen_output() async def list_devices(self): return await self.get_list('devices', DEVICE_PATTERN) async def list_paired_devices(self): return await self.get_list('paired-devices', DEVICE_PATTERN) async def list_controllers(self): return await self.get_list('list', CONTROLLER_PATTERN) async def select_paired_device(self): print('Selecting device:') devices = await self.list_paired_devices() count = len(devices) if count < 1: raise SubprocessError('There is no connected device.') elif count == 1: return devices[0] for i, d in enumerate(devices): print('%d. %s %s' % (i+1, d[0], d[1])) print('Select device[1]:') selected = input() return devices[0 if not selected.strip() else (int(selected) - 1)] async def wait(): return await asyncio.sleep(WAIT_TIME) async def execute_command(cmd, ignore_fail=False): p = await asyncio.create_subprocess_shell(cmd, stdout=sb.PIPE, stderr=sb.PIPE) stdout, stderr = await p.communicate() stdout, stderr = \ stdout.decode() if stdout is not None else '', \ stderr.decode() if stderr is not None else '' if p.returncode != 0 or stderr.strip() != '': message = 'Command: %s failed with status: %s\nstderr: %s' % (cmd, p.returncode, stderr) if ignore_fail: print('Ignoring: %s' % message) else: raise SubprocessError(message) return stdout async def execute_find(cmd, pattern, tries=0, fail_safe=False): tries = tries or TRIES message = 'Cannot find `%s` using `%s`.' % (pattern, cmd) retry_message = message + ' Retrying %d more times' while True: stdout = await execute_command(cmd) match = re.search(pattern, stdout) if match: return match.group() elif tries > 0: await wait() print(retry_message % tries) tries -= 1 continue if fail_safe: return None raise RetryExceededError('Retry times exceeded: %s' % message) async def find_dev_id(mac, **kw): return await execute_find('pactl list cards short', 'bluez_card.%s' % '_'.join(mac), **kw) async def find_sink(mac, **kw): return await execute_find('pacmd list-sinks', 'bluez_sink.%s' % '_'.join(mac), **kw) async def set_profile(device_id, profile): print('Setting the %s profile' % profile) try: return await execute_command('pactl set-card-profile %s %s' % (device_id, _profiles[profile])) except KeyError: print('Invalid profile: %s, please select one one of a2dp or hsp.' % profile, file=sys.stderr) raise SystemExit(1) async def set_default_sink(sink): print('Updating default sink to %s' % sink) return await execute_command('pacmd set-default-sink %s' % sink) async def move_streams_to_sink(sink): streams = await execute_command('pacmd list-sink-inputs | grep "index:"', True) for i in streams.split(): i = ''.join(n for n in i if n.isdigit()) if i != '': print('Moving stream %s to sink' % i) await execute_command('pacmd move-sink-input %s %s' % (i, sink)) return sink async def main(args): global WAIT_TIME, TRIES if args.version: print(__version__) return 0 mac = args.mac # Hacking, Changing the constants! WAIT_TIME = args.wait TRIES = args.tries exit_future = asyncio.Future() transport, protocol = await asyncio.get_event_loop().subprocess_exec( lambda: BluetoothctlProtocol(exit_future, echo=args.echo), 'bluetoothctl' ) try: if mac is None: mac, _ = await protocol.select_paired_device() mac = mac.split(':' if ':' in mac else '_') print('Device MAC: %s' % ':'.join(mac)) device_id = await find_dev_id(mac, fail_safe=True) if device_id is None: print('It seems device: %s is not connected yet, trying to connect.' % ':'.join(mac)) await protocol.trust(mac) await protocol.connect(mac) device_id = await find_dev_id(mac) sink = await find_sink(mac, fail_safe=True) if sink is None: await set_profile(device_id, args.profile) sink = await find_sink(mac) print('Device ID: %s' % device_id) print('Sink: %s' % sink) await set_default_sink(sink) await wait() await set_profile(device_id, 'off') if args.profile is 'a2dp': await protocol.disconnect(mac) await wait() await protocol.connect(mac) device_id = await find_dev_id(mac) print('Device ID: %s' % device_id) await set_profile(device_id, args.profile) await set_default_sink(sink) await move_streams_to_sink(sink) except (SubprocessError, RetryExceededError) as ex: print(str(ex), file=sys.stderr) return 1 finally: print('Exiting bluetoothctl') await protocol.quit() await exit_future # Close the stdout pipe transport.close() if args.profile == 'a2dp': print('"Enjoy" the HiFi stereo music :)') else: print('"Enjoy" your headset audio :)') if __name__ == '__main__': sys.exit(asyncio.get_event_loop().run_until_complete(main(parser.parse_args()))) ```
I can say you a couple of things: a) my (little) experience with bluetooth under linux tells me is usually broken; there or here I always have some kind of issue. b) `bluez 4.99` was issued in March 2012, thus you are using a really, really old version; I suggest you (if you can) to, at least test, a newer version. These should explain your problems.
297,466
I am creating my CV in LaTeX with classicthesis-styled CV. Instead of adding publications individually, I would like to add a bibliography file. I tried it with the following code, but couldn't get it working. **MWE** ``` \documentclass{scrartcl} \reversemarginpar % Move the margin to the left of the page \newcommand{\MarginText}[1]{\marginpar{\raggedleft\itshape\small#1}} % New command defining the margin text style \usepackage[nochapters]{classicthesis} % Use the classicthesis style for the style of the document \usepackage[LabelsAligned]{currvita} % Use the currvita style for the layout of the document \renewcommand{\cvheadingfont}{\LARGE\color{Maroon}} % Font color of your name at the top \usepackage{hyperref} % Required for adding links and customizing them \hypersetup{colorlinks, breaklinks, urlcolor=Maroon, linkcolor=Maroon} % Set link colors \newlength{\datebox}\settowidth{\datebox}{Spring 2011} % Set the width of the date box in each block \newcommand{\NewEntry}[3]{\noindent\hangindent=2em\hangafter=0 \parbox{\datebox}{\small \textit{#1}}\hspace{1.5em} #2 #3 % Define a command for each new block - change spacing and font sizes here: #1 is the left margin, #2 is the italic date field and #3 is the position/employer/location field \vspace{0.5em}} % Add some white space after each new entry \newcommand{\Description}[1]{\hangindent=2em\hangafter=0\noindent\raggedright\footnotesize{#1}\par\normalsize\vspace{1em}} % Define a command for descriptions of each entry - change spacing and font sizes here \addbibresource{bibliography.bib} %---------------------------------------------------------------------------------------- \begin{document} \thispagestyle{empty} % Stop the page count at the bottom of the first page %---------------------------------------------------------------------------------------- % NAME AND CONTACT INFORMATION SECTION %---------------------------------------------------------------------------------------- \begin{cv} %---------------------------------------------------------------------------------------- % WORK EXPERIENCE %---------------------------------------------------------------------------------------- \noindent\spacedlowsmallcaps{Publications}\vspace{1em} % \section{publications} \printbibsection{article}{article in peer-reviewed journal} % Print all articles from the bibliography \printbibsection{book}{books} % Print all books from the bibliography \begin{refsection} % This is a custom heading for those references marked as "inproceedings" but not containing "keyword=france" \nocite{*} \printbibliography[sorting=chronological, type=inproceedings, title={international peer-reviewed conferences/proceedings}, notkeyword={france}, heading=bibheading] \end{refsection} \begin{refsection} % This is a custom heading for those references marked as "inproceedings" and containing "keyword=france" \nocite{*} \printbibliography[sorting=chronological, type=inproceedings, title={local peer-reviewed conferences/proceedings}, keyword={france}, heading=bibheading] \end{refsection} \printbibsection{misc}{other publications} % Print all miscellaneous entries from the bibliography \printbibsection{report}{research reports} % Print all research reports from the bibliography \end{cv} \end{document} ``` How to add bibliography file to classicthesis-styled CV?
2016/03/05
[ "https://tex.stackexchange.com/questions/297466", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/72911/" ]
You neglected to load `biblatex` in your MWE. Furthermore, `\printbibsection` is not a standard `biblatex` command, it is defined in the `friggeri-cv` as ``` \newcommand{\printbibsection}[2]{ \begin{refsection} \nocite{*} \printbibliography[sorting=chronological, type={#1}, title={#2}, heading=subbibliography] \end{refsection} } ``` But normally you wouldn't need `\printbibsection` and all the `refsections`, you could just go with ``` \documentclass{scrartcl} \usepackage[sorting=ydnt, tyle=authortitle, backend=biber]{biblatex} \addbibresource{biblatex-examples.bib} \nocite{*} \begin{document} \printbibliography[type=article, title={Articles}] \printbibliography[type=book, title={Books}] \printbibliography[nottype=article,nottype=book, title={Others}] \end{document} ```
From this work provided by Friggeri template and using [Tabular bibliography with 2 cols for @inbook, @article etc](https://tex.stackexchange.com/questions/157359) I can provide you my template that permit to distinguish the same type of publications using `keywords={france}`. This following MWE can be another start for your CV. ``` \documentclass[a4paper]{article} \usepackage{inputenc} \usepackage[english,french]{babel} \usepackage[T1]{fontenc} \usepackage{textcomp} \usepackage{csquotes} \usepackage[backend=biber, maxnames=99, sorting=ydnt, hyperref=true]{biblatex} \usepackage[left=3cm,top=2.5cm,right=3cm,bottom=2.5cm]{geometry} \begin{filecontents}{\jobname.bib} @ARTICLE{mwe2012, author = {Smith, A. and Johnson, B. and Willians, C.}, title = {The three most common surnames in the United States of America}, journal = {Review of Useless Knowledge}, year = {2012}, volume = {8}, number = {1}, pages = {290--290}, keywords={france} } @INPROCEEDINGS{mwe2011, author = {Miller, J. and Brown, D.}, title = {Most used surnames in fake passports}, booktitle = {Journal of Nosense Ranks}, year = {2011}, volume = {5}, number = {3}, pages = {1--130}, pmid = {1234567} } @INPROCEEDINGS{mwe2015, author = {Miller, J. and Brown, D.}, title = {Most used surnames in fake passports}, booktitle = {Journal of Nosense Ranks}, year = {2011}, volume = {5}, number = {3}, pages = {1--130}, pmid = {1234567}, keywords = {france} } \end{filecontents} \addbibresource{\jobname.bib} \defbibenvironment{bibliography} {\list %{\printtext[labelnumberwidth]{\printfield{labelnumber}}}% {\printtext{\addtocounter{publi}{1}[\thepubli]}} {\setlength{\labelwidth}{\labelnumberwidth}% \setlength{\leftmargin}{\labelwidth}% \setlength{\labelsep}{\biblabelsep}% \addtolength{\leftmargin}{\labelsep}% \setlength{\itemsep}{\bibitemsep}% \setlength{\parsep}{\bibparsep}}% \renewcommand*{\makelabel}[1]{\hss##1}} {\endlist} {\item} \DeclareFieldFormat[article]{title}{#1} \DeclareFieldFormat[book]{title}{#1} \DeclareFieldFormat[inproceedings]{title}{#1} \DeclareFieldFormat[inproceedings_fr]{title}{#1} \DeclareFieldFormat[misc]{title}{#1} \DeclareFieldFormat[report]{title}{#1} \DeclareFieldFormat{pages}{#1} \DeclareFieldFormat[article]{volume}{\textbf{#1}} \DeclareFieldFormat[unpublished]{title}{#1} \DeclareBibliographyDriver{article}{% \usebibmacro{bibindex}% \usebibmacro{begentry}% \begin{tabular}{p{0.9\textwidth}} \printfield{title}\\ \printnames{author}\\ \printfield{journaltitle}% \addcomma\space% \printfield{volume}% \iffieldundef{number}{}{\space(\printfield{number})}% \addcomma\space% \printfield{pages}% \addcomma\space% \printfield{year}. \end{tabular} \vspace{.5em} \hrule \usebibmacro{finentry}} \DeclareBibliographyDriver{inproceedings}{% \usebibmacro{bibindex}% \usebibmacro{begentry}% \begin{tabular}{p{0.9\textwidth}} \printfield{title}\\ \printnames{author}\\ \printfield{booktitle}% \addcomma\space% \printfield{volume}% \iffieldundef{number}{}{\space(\printfield{number})}% \addcomma\space% \printfield{pages}% \addcomma\space% \printlist{location} \addcomma\space% \printfield{year}. \end{tabular} \vspace{.5em} \hrule \usebibmacro{finentry}} \begin{document} \selectlanguage{french} \section{Liste de publications (extrait)} \newcounter{publi} \nocite{*} \selectlanguage{english} \setcounter{publi}{0} \printbibliography[type=article, title={Revues internationales avec comité de lecture}, heading=subbibliography] \setcounter{publi}{0} \printbibliography[type=inproceedings, title={Conférences internationales avec comité de lecture}, notkeyword={france}, heading=subbibliography] \selectlanguage{french} \setcounter{publi}{0} \printbibliography[type=inproceedings, title={Conférences nationales avec comité de lecture}, keyword={france}, heading=subbibliography] \end{document} ```
553,404
I use [Lucene.net](http://incubator.apache.org/lucene.net/) for indexing content & documents etc.. on websites. The index is very simple and has this format: ``` LuceneId - unique id for Lucene (TypeId + ItemId) TypeId - the type of text (eg. page content, product, public doc etc..) ItemId - the web page id, document id etc.. Text - the text indexed Title - web page title, document name etc.. to display with the search results ``` I've got these options to adapt it to serve multi-lingual content: 1. Create a separate index for each language. E.g. Lucene-enGB, Lucene-frFR etc.. 2. Keep the one index and add an additional 'language' field to it to filter the results. Which is the best option - or is there another? I've not used multiple indexes before so I'm leaning toward the second.
2009/02/16
[ "https://Stackoverflow.com/questions/553404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I do [2], but one problem I have is that I cannot use different analyzers depending on the language. I've combined the stopwords of the languages I want, but I lose the capability of more advanced stuff that the analyzer will offer such as stemming etc.
You can eliminate option 1 and 2. You can use one index and the fields that contains arabic words create two fileds for each: If you have field "**Text**" might contain arabic or english contents ==> * Create 2 fields for "**Text**" : 1 field, "**Text**", indexed/searched with your standard analyzer and another one, "**Text\_AR**" , with the arabicAnalyzer. In order to achieve that you can use [PreFieldAnalyzerWrapper](http://lucenenet.apache.org/docs/3.0.3/dc/df9/class_lucene_1_1_net_1_1_analysis_1_1_per_field_analyzer_wrapper.html#details)
359,448
I need to place a Wifi surveillance camera near the entrance of my house where no power outlet is in that area. I pulled a wire wrapping wire (awg 30) to the target location without thinking about wire resistance. And as you all expected, it didn't able to power the webcam. The power the camera uses is 5V @ 1A. I measured the wire resistance of my awg 30 wire to the location is 11 ohms (to and from) which is 6 ohms one way which is around 50 ft. So my question is what is the minimum gauge I need to use to be able to power my webcam placed 50ft away from the USB power adapter? Or how many awg30 wires I need to pull to lower the resistance to allow enough power to pass through? I assume the common practice is that the voltage drop is less than 5% of the required voltage. So 5% of 5V is 0.25V R=V/I so to allow 1A to pass through the resistance should be 0.25V/1A = 0.25ohms. From the chart: <https://www.cirris.com/learning-center/calculators/133-wire-resistance-calculator-table>? Therefore I need a minimum of one 14 Gauge wire (or a bundle of fifty awg 30 wires LOL) to power the webcam 50ft way?
2018/03/03
[ "https://electronics.stackexchange.com/questions/359448", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/179935/" ]
The short answer is that I'd argue that a spacing change near the start or end point of a differential signal is not that bad. I'd also argue that 6 layers is not that many. But at high speeds, definitely keep all noise sources away from the clock. For the longer answer, let's look at the reasons given. The Toradex source you cite mentioned an impedance discontinuity, and EMC compliance. The impedance discontinuity comes from the fact that, if there is a via between traces, the traces are at first have a capacitive coupling with each other, then that coupling is removed and replaced with the via, then they couple together again. Any impedance change will cause a reflection (see [Impedance Mismatch](https://en.wikipedia.org/wiki/Impedance_matching)). The ratio of reflection is: $$ \Gamma=\frac{Z\_1-Z\_2}{Z\_1+Z\_2} $$ Where Z is the impedance change. Note that the real impedance is different for different frequencies. So, we get signals reflecting back to the driver, potentially damaging the driver by forcing an over or under voltage condition (not very likely, particularly not with an FPGA's LVDS, which was relatively rugged when I used it, but reliability is important), and then it can reflect back again from the impedance change at the driver, and hit the receiver. Worst case, it destructively interferes with an edge and makes it non-monotonic. What needs to happen for this worst case scenario? I believe the rule of thumb is that you are in trouble if the reflection distance is over 1/6 the fundamental wavelength. So, if your edge rate (not switching frequency, but the rise time of your edges) is 1 ns, we know electricity travels about 6 inches per ns in copper, so if the reflection distance is over 1 inch, you are on thin ice, and should look at how much the impedance is changing. Similarly, if the via is near the receiving side of the signal, I would argue that the impedance mismatch is going to get lost in the impedance mismatch inherent in reaching the receiver. The second issue Toradex points to is EMC compliance, which is a bit of a fuzzy term. They could be worried about coupling or trace length mismatch. I don't think coupling is necessarily an issue; these are differential lines so the net coupling should cancel out, unless you are really pushing your voltage margins. Trace length mismatch could be more common if there is an obstruction in your traces, but it is not a necessary outcome. To go a bit more into coupling, in the ideal case, if you couple the same signal into a differential pair, you would prefer to couple into both. Doing that would bump them both by a few mV, and the differential signal (Vp - Vn) would be unaffected. As long as the absolute voltages of each signal are within spec, you should be fine. At very high speeds you may run into an issue where the signal couples into one line slightly before it would couple into the other. This would be an issue, but I'd argue even here having the noise couple into both lines is better than having it couple into one, because either the noise is reduced by the differential nature, or you have two problems instead of one. If you are dealing with something very high speed, with edge rates under 1 ns, then you should be explaining the answer to me, and you should probably use a board with more than 4 layers. If you're just trying to drive an 80 MSPS ADC, this advice should be solid. Keep in mind that edge sensitive lines, like clocks, are by far the most important signals to treat correctly. One final tip: If the going gets tough, look into microvias which may be placed in the BGA pads.
If you really need to know, you should look into simulation. You should also edit your question to include the signaling speed or edge rate of the signals. But I think there is a good chance you will get away with it. Diff pairs primarily couple to the adjacent plane. They don't couple edge-wise to each other very much. So the deviation in spacing will have minimal effect on the differential impedance. The critical thing for differential pairs is to match length. A few times I have done boards where I violated spacing rules in one or two places to help escape from a BGA. This did not incur major cost increase for the board. This was in high volume production. So you possibly can route most of the board using 5/5 rules, and use 3 mil spacing only in the area where you escape from the BGA. This may not be a problem for the board vendor. You could investigate that.
359,448
I need to place a Wifi surveillance camera near the entrance of my house where no power outlet is in that area. I pulled a wire wrapping wire (awg 30) to the target location without thinking about wire resistance. And as you all expected, it didn't able to power the webcam. The power the camera uses is 5V @ 1A. I measured the wire resistance of my awg 30 wire to the location is 11 ohms (to and from) which is 6 ohms one way which is around 50 ft. So my question is what is the minimum gauge I need to use to be able to power my webcam placed 50ft away from the USB power adapter? Or how many awg30 wires I need to pull to lower the resistance to allow enough power to pass through? I assume the common practice is that the voltage drop is less than 5% of the required voltage. So 5% of 5V is 0.25V R=V/I so to allow 1A to pass through the resistance should be 0.25V/1A = 0.25ohms. From the chart: <https://www.cirris.com/learning-center/calculators/133-wire-resistance-calculator-table>? Therefore I need a minimum of one 14 Gauge wire (or a bundle of fifty awg 30 wires LOL) to power the webcam 50ft way?
2018/03/03
[ "https://electronics.stackexchange.com/questions/359448", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/179935/" ]
The short answer is that I'd argue that a spacing change near the start or end point of a differential signal is not that bad. I'd also argue that 6 layers is not that many. But at high speeds, definitely keep all noise sources away from the clock. For the longer answer, let's look at the reasons given. The Toradex source you cite mentioned an impedance discontinuity, and EMC compliance. The impedance discontinuity comes from the fact that, if there is a via between traces, the traces are at first have a capacitive coupling with each other, then that coupling is removed and replaced with the via, then they couple together again. Any impedance change will cause a reflection (see [Impedance Mismatch](https://en.wikipedia.org/wiki/Impedance_matching)). The ratio of reflection is: $$ \Gamma=\frac{Z\_1-Z\_2}{Z\_1+Z\_2} $$ Where Z is the impedance change. Note that the real impedance is different for different frequencies. So, we get signals reflecting back to the driver, potentially damaging the driver by forcing an over or under voltage condition (not very likely, particularly not with an FPGA's LVDS, which was relatively rugged when I used it, but reliability is important), and then it can reflect back again from the impedance change at the driver, and hit the receiver. Worst case, it destructively interferes with an edge and makes it non-monotonic. What needs to happen for this worst case scenario? I believe the rule of thumb is that you are in trouble if the reflection distance is over 1/6 the fundamental wavelength. So, if your edge rate (not switching frequency, but the rise time of your edges) is 1 ns, we know electricity travels about 6 inches per ns in copper, so if the reflection distance is over 1 inch, you are on thin ice, and should look at how much the impedance is changing. Similarly, if the via is near the receiving side of the signal, I would argue that the impedance mismatch is going to get lost in the impedance mismatch inherent in reaching the receiver. The second issue Toradex points to is EMC compliance, which is a bit of a fuzzy term. They could be worried about coupling or trace length mismatch. I don't think coupling is necessarily an issue; these are differential lines so the net coupling should cancel out, unless you are really pushing your voltage margins. Trace length mismatch could be more common if there is an obstruction in your traces, but it is not a necessary outcome. To go a bit more into coupling, in the ideal case, if you couple the same signal into a differential pair, you would prefer to couple into both. Doing that would bump them both by a few mV, and the differential signal (Vp - Vn) would be unaffected. As long as the absolute voltages of each signal are within spec, you should be fine. At very high speeds you may run into an issue where the signal couples into one line slightly before it would couple into the other. This would be an issue, but I'd argue even here having the noise couple into both lines is better than having it couple into one, because either the noise is reduced by the differential nature, or you have two problems instead of one. If you are dealing with something very high speed, with edge rates under 1 ns, then you should be explaining the answer to me, and you should probably use a board with more than 4 layers. If you're just trying to drive an 80 MSPS ADC, this advice should be solid. Keep in mind that edge sensitive lines, like clocks, are by far the most important signals to treat correctly. One final tip: If the going gets tough, look into microvias which may be placed in the BGA pads.
If that region of discontinuityis << wavelength, then you are OK. If your edges are 1nanosecond Trise, Tfall, and that region of bad Z\_diff is 50 picoseconds ( < 5% of the edge time) you will be OK. And even the edge gets upset, the DATA EYE is what is important. 100pS upset in a 5nanosecond-long data-eye will be fine; the reflections will have long faded away before the receiver-clock strobes the receiver FlipFlop to make a decision. ===================================== And if the reflections should occur in such a way as to increase the data-eye, like would be even better. Beware of the signal energy stored in the ESD structures and the leadframe inductance of the package. Its is ISI -- inter Symbol Interference --- and may improve or may degrade the data-eye.
359,448
I need to place a Wifi surveillance camera near the entrance of my house where no power outlet is in that area. I pulled a wire wrapping wire (awg 30) to the target location without thinking about wire resistance. And as you all expected, it didn't able to power the webcam. The power the camera uses is 5V @ 1A. I measured the wire resistance of my awg 30 wire to the location is 11 ohms (to and from) which is 6 ohms one way which is around 50 ft. So my question is what is the minimum gauge I need to use to be able to power my webcam placed 50ft away from the USB power adapter? Or how many awg30 wires I need to pull to lower the resistance to allow enough power to pass through? I assume the common practice is that the voltage drop is less than 5% of the required voltage. So 5% of 5V is 0.25V R=V/I so to allow 1A to pass through the resistance should be 0.25V/1A = 0.25ohms. From the chart: <https://www.cirris.com/learning-center/calculators/133-wire-resistance-calculator-table>? Therefore I need a minimum of one 14 Gauge wire (or a bundle of fifty awg 30 wires LOL) to power the webcam 50ft way?
2018/03/03
[ "https://electronics.stackexchange.com/questions/359448", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/179935/" ]
If you really need to know, you should look into simulation. You should also edit your question to include the signaling speed or edge rate of the signals. But I think there is a good chance you will get away with it. Diff pairs primarily couple to the adjacent plane. They don't couple edge-wise to each other very much. So the deviation in spacing will have minimal effect on the differential impedance. The critical thing for differential pairs is to match length. A few times I have done boards where I violated spacing rules in one or two places to help escape from a BGA. This did not incur major cost increase for the board. This was in high volume production. So you possibly can route most of the board using 5/5 rules, and use 3 mil spacing only in the area where you escape from the BGA. This may not be a problem for the board vendor. You could investigate that.
If that region of discontinuityis << wavelength, then you are OK. If your edges are 1nanosecond Trise, Tfall, and that region of bad Z\_diff is 50 picoseconds ( < 5% of the edge time) you will be OK. And even the edge gets upset, the DATA EYE is what is important. 100pS upset in a 5nanosecond-long data-eye will be fine; the reflections will have long faded away before the receiver-clock strobes the receiver FlipFlop to make a decision. ===================================== And if the reflections should occur in such a way as to increase the data-eye, like would be even better. Beware of the signal energy stored in the ESD structures and the leadframe inductance of the package. Its is ISI -- inter Symbol Interference --- and may improve or may degrade the data-eye.
6,303,163
I've built an interface formed by a ListView and a panel with a few textboxes. In order to make change the context in those textboxes when another ListViewItem is selected, I've captured the SelectionChange event, to change accordingly DataContexts of the textboxes. Something like this: ``` void customersList_SelectItem(object sender, SelectionChangedEventArgs e) { Customer customer = (Customer)customersList.Selected; if (customer != null) { addressField.DataContext = customer; phoneField.DataContext = customer; mobileField.DataContext = customer; webField.DataContext = customer; emailField.DataContext = customer; faxField.DataContext = customer; ... } } ``` Now, I wonder, is this the best the way to do it? Looks like a bit forced, but I can't devise any better.
2011/06/10
[ "https://Stackoverflow.com/questions/6303163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/667175/" ]
If the textboxes were all contained in a containing element (e.g. a Grid), then you could just set the DataContext of the Grid element instead. This would be cleaner. Even better yet would be to use XAML binding and [MVVM](http://www.wintellect.com/cs/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx), and this code could be implemented declaratively in XAML.
Bind the dependent controls DataContext property to the ListBox's SelectedItem property. Or better yet if they are within a container control - Set its data context once and have the children inherit it. Something like... ``` <StackPanel DataContext="{Binding ElementName=ListBoxName, Path=SelectedItem}"> <!--- dependent controls --> </StackPanel> ```
6,303,163
I've built an interface formed by a ListView and a panel with a few textboxes. In order to make change the context in those textboxes when another ListViewItem is selected, I've captured the SelectionChange event, to change accordingly DataContexts of the textboxes. Something like this: ``` void customersList_SelectItem(object sender, SelectionChangedEventArgs e) { Customer customer = (Customer)customersList.Selected; if (customer != null) { addressField.DataContext = customer; phoneField.DataContext = customer; mobileField.DataContext = customer; webField.DataContext = customer; emailField.DataContext = customer; faxField.DataContext = customer; ... } } ``` Now, I wonder, is this the best the way to do it? Looks like a bit forced, but I can't devise any better.
2011/06/10
[ "https://Stackoverflow.com/questions/6303163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/667175/" ]
If the textboxes were all contained in a containing element (e.g. a Grid), then you could just set the DataContext of the Grid element instead. This would be cleaner. Even better yet would be to use XAML binding and [MVVM](http://www.wintellect.com/cs/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx), and this code could be implemented declaratively in XAML.
You can also use the ["/" binding path syntax](http://msdn.microsoft.com/en-us/library/ms752300.aspx#Path_Syntax) in WPF in combination with a CollectionView: ``` <Window ... xmlns:local="..."> <Window.DataContext> <local:MyViewModel ... /> </Window.DataContext> <Window.Resources> <CollectionViewSource x:Key="ItemsView" Source="{Binding Path=Items}" /> <Window.Resources> <ListView ItemsSource="{Binding Source={StaticResource ItemsView}}"> ... </ListView> <Grid DataContext="{Binding Source={StaticResource ItemsView}, Path=/}"> ... </Grid> </Window> ``` To quickly explain this setup: * The window's datacontext is set to an instance of a view model * A CollectionViewSource is created as a resource and uses a collection exposed by the view model as its source * The listview's ItemsSource is bound directly to the CollectionView (exposed by CollectionViewSource) * The Grid (which would contain your form elements) is bound to the CurrentItem of the CollectionView via the ["/" binding path syntax](http://msdn.microsoft.com/en-us/library/ms752300.aspx#Path_Syntax); each time an item is selected in the list view, the Grid's datacontext is automatically set to the currently selected item I prefer this type of binding over having to reference specific elemetns and properties and relying on the built in power of WPF's binding and CollectionView classes.
6,303,163
I've built an interface formed by a ListView and a panel with a few textboxes. In order to make change the context in those textboxes when another ListViewItem is selected, I've captured the SelectionChange event, to change accordingly DataContexts of the textboxes. Something like this: ``` void customersList_SelectItem(object sender, SelectionChangedEventArgs e) { Customer customer = (Customer)customersList.Selected; if (customer != null) { addressField.DataContext = customer; phoneField.DataContext = customer; mobileField.DataContext = customer; webField.DataContext = customer; emailField.DataContext = customer; faxField.DataContext = customer; ... } } ``` Now, I wonder, is this the best the way to do it? Looks like a bit forced, but I can't devise any better.
2011/06/10
[ "https://Stackoverflow.com/questions/6303163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/667175/" ]
Bind the dependent controls DataContext property to the ListBox's SelectedItem property. Or better yet if they are within a container control - Set its data context once and have the children inherit it. Something like... ``` <StackPanel DataContext="{Binding ElementName=ListBoxName, Path=SelectedItem}"> <!--- dependent controls --> </StackPanel> ```
You can also use the ["/" binding path syntax](http://msdn.microsoft.com/en-us/library/ms752300.aspx#Path_Syntax) in WPF in combination with a CollectionView: ``` <Window ... xmlns:local="..."> <Window.DataContext> <local:MyViewModel ... /> </Window.DataContext> <Window.Resources> <CollectionViewSource x:Key="ItemsView" Source="{Binding Path=Items}" /> <Window.Resources> <ListView ItemsSource="{Binding Source={StaticResource ItemsView}}"> ... </ListView> <Grid DataContext="{Binding Source={StaticResource ItemsView}, Path=/}"> ... </Grid> </Window> ``` To quickly explain this setup: * The window's datacontext is set to an instance of a view model * A CollectionViewSource is created as a resource and uses a collection exposed by the view model as its source * The listview's ItemsSource is bound directly to the CollectionView (exposed by CollectionViewSource) * The Grid (which would contain your form elements) is bound to the CurrentItem of the CollectionView via the ["/" binding path syntax](http://msdn.microsoft.com/en-us/library/ms752300.aspx#Path_Syntax); each time an item is selected in the list view, the Grid's datacontext is automatically set to the currently selected item I prefer this type of binding over having to reference specific elemetns and properties and relying on the built in power of WPF's binding and CollectionView classes.
2,749,785
Let $\mathcal{B}$ be an orthonormal basis for a finite dimensional complex vector space $V$. Let $U$ be an operator on that space. Show that $U$ is a unitary operator if and only if $[U]\_{\mathcal{B}}$ is a unitary matrix. I'm stuck on how to even approach this problem.
2018/04/23
[ "https://math.stackexchange.com/questions/2749785", "https://math.stackexchange.com", "https://math.stackexchange.com/users/157069/" ]
There are a couple of things going on here. You have some abstract $\mathbb{C}$-vector space, equipped with an inner product $(-, -)\_V: V \times V \to \mathbb{C}$, which I will consider to be conjugate-linear in the first argument, and $\mathbb{C}$-linear in the second: $(\lambda v, \mu w)\_V = \overline{\lambda} \mu (v, w)\_V$. A *unitary operator* $U: V \to V$ is one which preserves the inner product, in that $(Uv, Uw)\_V = (v, w)\_V$ for all $u, w \in V$. Note that it makes no sense to define the conjugate-transpose of $U$, since it is not a matrix: let's forget about $V$ and $U$ for the moment. There is another well-known inner product space, which is $\mathbb{C}^n$, the space of length-$n$ column vectors over $\mathbb{C}$, with inner product given by $(x, y)\_{\mathbb{C}^n} := x^\* y$, where $x^\*$ is the conjugate-transpose of $x$. The nice thing about $\mathbb{C}^n$ is that it comes with a distinguished basis, so that every linear transformation $\mathbb{C}^n \to \mathbb{C}^n$ is exactly some $n \times n$ complex matrix. In $\mathbb{C}^n$, we have the same notion of a unitary map $T: \mathbb{C}^n \to \mathbb{C}^n$ (it must satisfy $(Tx, Ty)\_{\mathbb{C}^n} = (x, y)\_{\mathbb{C}^n}$ for all $x, y \in \mathbb{C}^n$), but we may now characterise such matrices: **Show:** $T \in \operatorname{Mat}\_n(\mathbb{C})$ is unitary if and only if $T T^\* = I$, where $T^\*$ is the conjugate-transpose of the matrix $T$. It will also be handy to have the following facts: 1. (Definition) An *isomorphism of inner product spaces* $S: V \to W$ is a linear map such that $(Sv\_1, S v\_2)\_U = (v\_1, v\_2)\_V$ for all $v\_1, v\_2 \in V$. 2. (Prove:) If $S$ is an isomorphism of inner product spaces, so is $S^{-1}$. 3. Note that a unitary operator on $V$ is an isomorphism of inner product spaces $V \to V$. Returning to the original inner product space $V$, a choice of basis $\mathcal{B} = (b\_1, \ldots, b\_n)$ on $V$ amounts to a linear isomorphism $B: \mathbb{C}^n \to V$ (where $n = \dim V$), given by $B e\_i = b\_i$, where by $e\_i$ I mean the column vector in $\mathbb{C}^n$ having a $1$ in the $i$th position and zeros elsewhere. **Show:** If the basis $\mathcal{B}$ is orthonormal, then $B$ is an isomorphism of inner product spaces. After all the pieces are in place, the result is easy: the matrix of the operator $U: V \to V$ in the basis $\mathcal{B}$ is $B^{-1} U B \in \operatorname{Mat}\_n(\mathbb{C})$, and all we have to do is verify that this is a unitary operator: for any $x, y \in \mathbb{C}^n$, we have $$ (B^{-1}UBx, B^{-1}UBy)\_V = (UBx, UBy)\_{\mathbb{C}^n} = (Bx, By)\_V = (x, y)\_{\mathbb{C}^n}$$ where the equalities follow from repeatedly applying the facts that $B$, $U$, and $B^{-1}$ are isomorphisms of inner product spaces. Now the result follows from the characterisation of unitary matrices.
$$U=R^{-1}[U]\_{B}R$$ where R is the change-of-base matrix from B to K (B is orthonormal so R is unitary!), now if $$U^{\*}U=I$$ then an operator is unitary. $$U=R^{\*}[U]\_{B}R$$ $$U^{\*}U=R^{\*}[U]\_{B}^{\*}RR^{\*}[U]\_{B}R$$ which definitely equals I. (you multiply matrices from the middle) It’s the same for the other implication. Hope it helped, it’s always hard to prove “obvious” things.
2,749,785
Let $\mathcal{B}$ be an orthonormal basis for a finite dimensional complex vector space $V$. Let $U$ be an operator on that space. Show that $U$ is a unitary operator if and only if $[U]\_{\mathcal{B}}$ is a unitary matrix. I'm stuck on how to even approach this problem.
2018/04/23
[ "https://math.stackexchange.com/questions/2749785", "https://math.stackexchange.com", "https://math.stackexchange.com/users/157069/" ]
There are a couple of things going on here. You have some abstract $\mathbb{C}$-vector space, equipped with an inner product $(-, -)\_V: V \times V \to \mathbb{C}$, which I will consider to be conjugate-linear in the first argument, and $\mathbb{C}$-linear in the second: $(\lambda v, \mu w)\_V = \overline{\lambda} \mu (v, w)\_V$. A *unitary operator* $U: V \to V$ is one which preserves the inner product, in that $(Uv, Uw)\_V = (v, w)\_V$ for all $u, w \in V$. Note that it makes no sense to define the conjugate-transpose of $U$, since it is not a matrix: let's forget about $V$ and $U$ for the moment. There is another well-known inner product space, which is $\mathbb{C}^n$, the space of length-$n$ column vectors over $\mathbb{C}$, with inner product given by $(x, y)\_{\mathbb{C}^n} := x^\* y$, where $x^\*$ is the conjugate-transpose of $x$. The nice thing about $\mathbb{C}^n$ is that it comes with a distinguished basis, so that every linear transformation $\mathbb{C}^n \to \mathbb{C}^n$ is exactly some $n \times n$ complex matrix. In $\mathbb{C}^n$, we have the same notion of a unitary map $T: \mathbb{C}^n \to \mathbb{C}^n$ (it must satisfy $(Tx, Ty)\_{\mathbb{C}^n} = (x, y)\_{\mathbb{C}^n}$ for all $x, y \in \mathbb{C}^n$), but we may now characterise such matrices: **Show:** $T \in \operatorname{Mat}\_n(\mathbb{C})$ is unitary if and only if $T T^\* = I$, where $T^\*$ is the conjugate-transpose of the matrix $T$. It will also be handy to have the following facts: 1. (Definition) An *isomorphism of inner product spaces* $S: V \to W$ is a linear map such that $(Sv\_1, S v\_2)\_U = (v\_1, v\_2)\_V$ for all $v\_1, v\_2 \in V$. 2. (Prove:) If $S$ is an isomorphism of inner product spaces, so is $S^{-1}$. 3. Note that a unitary operator on $V$ is an isomorphism of inner product spaces $V \to V$. Returning to the original inner product space $V$, a choice of basis $\mathcal{B} = (b\_1, \ldots, b\_n)$ on $V$ amounts to a linear isomorphism $B: \mathbb{C}^n \to V$ (where $n = \dim V$), given by $B e\_i = b\_i$, where by $e\_i$ I mean the column vector in $\mathbb{C}^n$ having a $1$ in the $i$th position and zeros elsewhere. **Show:** If the basis $\mathcal{B}$ is orthonormal, then $B$ is an isomorphism of inner product spaces. After all the pieces are in place, the result is easy: the matrix of the operator $U: V \to V$ in the basis $\mathcal{B}$ is $B^{-1} U B \in \operatorname{Mat}\_n(\mathbb{C})$, and all we have to do is verify that this is a unitary operator: for any $x, y \in \mathbb{C}^n$, we have $$ (B^{-1}UBx, B^{-1}UBy)\_V = (UBx, UBy)\_{\mathbb{C}^n} = (Bx, By)\_V = (x, y)\_{\mathbb{C}^n}$$ where the equalities follow from repeatedly applying the facts that $B$, $U$, and $B^{-1}$ are isomorphisms of inner product spaces. Now the result follows from the characterisation of unitary matrices.
Given $\mathcal B$ an orthonormal basis of $V$ $$\begin{align}&[UU^\*]\_\mathcal{B}=[U^\*U]\_\mathcal{B}=[I]\_\mathcal{B}=I\_n\\ \iff &[U]\_\mathcal{B}[U^\*]\_\mathcal{B}=[U^\*]\_\mathcal{B}[U]\_\mathcal{B}=I\_n\\ \iff &[U]\_\mathcal{B}[U]\_\mathcal{B}^\*=[U]\_\mathcal{B}^\*[U]\_\mathcal{B}=I\_n .\end{align}$$ notice that it works for both direction so this complete the proof.
66,233,085
I have a dataframe values like this: ``` name foreign_name acronym alias United States États-Unis USA USA ``` I want to merge all those four columns in a row into one single columns 'names', so I do: ``` merge = lambda x: '|'.join([a for a in x.unique() if a]) df['names'] = df[['name', 'foreign_name', 'acronym', 'alias',]].apply(merge, axis=1) ``` The problem with this code is that, it doesn't remove the duplicate 'USA', instead it gets: ``` names = 'United States|États-Unis|USA|USA' ``` Where am I wrong?
2021/02/16
[ "https://Stackoverflow.com/questions/66233085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3943868/" ]
MCVE: ``` import pandas as pd import numpy as np d= {'name': {0: 'United States'}, 'foreign_name': {0: 'États-Unis'}, 'acronym': {0: 'USA'}, 'alias': {0: 'USA'}} df = pd.DataFrame(d) merge = lambda x: '|'.join([a for a in x.unique() if a]) df['names'] = df[['name', 'foreign_name', 'acronym', 'alias',]].apply(merge, axis=1) print(df) ``` Output: ``` name foreign_name acronym alias names 0 United States États-Unis USA USA United States|États-Unis|USA ```
You just need to tell is to operate along row axis. `axis=1` ``` df.apply(lambda r: "|".join(r.unique()), axis=1) ``` ### output ``` United States|États-Unis|USA dtype: object ```
66,233,085
I have a dataframe values like this: ``` name foreign_name acronym alias United States États-Unis USA USA ``` I want to merge all those four columns in a row into one single columns 'names', so I do: ``` merge = lambda x: '|'.join([a for a in x.unique() if a]) df['names'] = df[['name', 'foreign_name', 'acronym', 'alias',]].apply(merge, axis=1) ``` The problem with this code is that, it doesn't remove the duplicate 'USA', instead it gets: ``` names = 'United States|États-Unis|USA|USA' ``` Where am I wrong?
2021/02/16
[ "https://Stackoverflow.com/questions/66233085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3943868/" ]
aggregate to set to eliminate duplicates Turn the set to list apply `str.join('|')` to concat the strings with a `|` separator ``` df['name']=df.agg(set,1).map(list).str.join('|') ```
You just need to tell is to operate along row axis. `axis=1` ``` df.apply(lambda r: "|".join(r.unique()), axis=1) ``` ### output ``` United States|États-Unis|USA dtype: object ```
5,479,106
OK, so I thought I was solving a problem and I created an even bigger one. I was trying to get rid of a lingering reference to `MySql` and deleted a bunch of files from the Temporary ASP.NET files directory. Now, when I try to run the ASP.NET configuration tool I get this, reprinted in its full glory: > > System.InvalidCastException: [A]System.Web.Administration.WebAdminRemotingManager cannot be cast to [B]System.Web.Administration.WebAdminRemotingManager. Type A originates from 'App\_Code.eyfytrpm, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\asp.netwebadminfiles\1f61ecce\354a2473\App\_Code.eyfytrpm.dll'. Type B originates from 'App\_Code.y-perhho, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\asp.netwebadminfiles\1f61ecce\354a2473\App\_Code.y-perhho.dll'. at System.Web.Administration.WebAdminPage.get\_RemotingManager() at System.Web.Administration.WebAdminPage.SaveConfig(Configuration config) at System.Web.Administration.WebAdminPage.VerifyAppValid() > > > Apparently those temporary files weren't as temporary as I thought they were. Is there any way to regenerate those files, or any other way to work around this. I really shot myself in the foot this time.. :(
2011/03/29
[ "https://Stackoverflow.com/questions/5479106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83678/" ]
To answer my own question... I wound up changing the Apache file /etc/apache/sites-available/default from AllowOverRide = None to AllowOverRide = All.
have you also tried RewriteBase / or RewriteBase /simple/ or along those lines? in my dealings on servers i've used, i've never had to put the domain into the rewrite base. Just the folders
54,695,113
I'm trying to create a filter based that is triggered by checkboxes, which shows and hides options from a list. I have tried to use resources online to put the script together but nothing seems to work. In order to hide or show list items I am editing a - class= "marker" parent element based on wether - class= "condtx" of its child element is matching the array of checked boxes "value" or not. I have included comments on how I am proceeding. Can anyone point me in the right direction please? ```js function filterCondtn1() { var i, z; //"chekedVal" array Keeps returning "undefined" I have no idea why var chekedVal = document.getElementById("InputOpts").getElementsByTagName("input").checked.value; //Gathered all <h3> tag options into array to be tested against "chekedVal" for match var condt1 = document.getElementsByClassName("condtn1").innerHTML; //Parrent class that will be edited to show <div> or not if True or false. var parrentClss = document.getElementsByClassName("marker"); //From here it's a blur. I've trying everything I can. I think I should be something of that sort. for { (var i = 0; i < condt1.length; i++) && (var z = 0; z < parrentClss.length; z++) RemoveClass(parrentClss[z], "show"); if (condt1[i].indexOf(chekedVal) > -1) AddClass(parrentClss[z], "show"); } } //Currently using these two functions in my script and they work function RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } function AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } ``` ```css .markerA { display: none; } .show { display: block; } ``` ```html <div id="InputOpts"> <input type="checkbox" value="option 1" oninput="filterCondtn1();">Option 1 <input type="checkbox" value="option 2" oninput="filterCondtn1();">Option 2 <input type="checkbox" value="option 3" oninput="filterCondtn1();">Option 3 <input type="checkbox" value="option 4" oninput="filterCondtn1();">Option 4 </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 1</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 3</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 2</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 4</h3> </div> </div> ```
2019/02/14
[ "https://Stackoverflow.com/questions/54695113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206451/" ]
Due to the docs: <https://developers.google.com/recaptcha/docs/verify> invalid-input-secret: **The secret parameter is invalid or malformed.** Maybe you have mixed the site\_key and the secret\_key.
You need to add the user remote IP address. ``` var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; request({ url: 'https://www.google.com/recaptcha/api/siteverify', method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: `secret=${secret}&response=${response}&remoteip=${user_ip}`}... ``` Another thing I see that you are not using template literal, you should change the quotes to ` instead of '. OR, You should use a ready-made module for reCaptcha, like this one: <https://www.npmjs.com/package/recaptcha>
54,695,113
I'm trying to create a filter based that is triggered by checkboxes, which shows and hides options from a list. I have tried to use resources online to put the script together but nothing seems to work. In order to hide or show list items I am editing a - class= "marker" parent element based on wether - class= "condtx" of its child element is matching the array of checked boxes "value" or not. I have included comments on how I am proceeding. Can anyone point me in the right direction please? ```js function filterCondtn1() { var i, z; //"chekedVal" array Keeps returning "undefined" I have no idea why var chekedVal = document.getElementById("InputOpts").getElementsByTagName("input").checked.value; //Gathered all <h3> tag options into array to be tested against "chekedVal" for match var condt1 = document.getElementsByClassName("condtn1").innerHTML; //Parrent class that will be edited to show <div> or not if True or false. var parrentClss = document.getElementsByClassName("marker"); //From here it's a blur. I've trying everything I can. I think I should be something of that sort. for { (var i = 0; i < condt1.length; i++) && (var z = 0; z < parrentClss.length; z++) RemoveClass(parrentClss[z], "show"); if (condt1[i].indexOf(chekedVal) > -1) AddClass(parrentClss[z], "show"); } } //Currently using these two functions in my script and they work function RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } function AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } ``` ```css .markerA { display: none; } .show { display: block; } ``` ```html <div id="InputOpts"> <input type="checkbox" value="option 1" oninput="filterCondtn1();">Option 1 <input type="checkbox" value="option 2" oninput="filterCondtn1();">Option 2 <input type="checkbox" value="option 3" oninput="filterCondtn1();">Option 3 <input type="checkbox" value="option 4" oninput="filterCondtn1();">Option 4 </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 1</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 3</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 2</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 4</h3> </div> </div> ```
2019/02/14
[ "https://Stackoverflow.com/questions/54695113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206451/" ]
You need to add the user remote IP address. ``` var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; request({ url: 'https://www.google.com/recaptcha/api/siteverify', method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: `secret=${secret}&response=${response}&remoteip=${user_ip}`}... ``` Another thing I see that you are not using template literal, you should change the quotes to ` instead of '. OR, You should use a ready-made module for reCaptcha, like this one: <https://www.npmjs.com/package/recaptcha>
For reCAPTCHA Enterprise, check the official docs: <https://cloud.google.com/recaptcha-enterprise/docs/create-assessment>. In short, you need to use the library that Google provides: ``` const { RecaptchaEnterpriseServiceClient } = require('@google-cloud/recaptcha-enterprise'); const client = new RecaptchaEnterpriseServiceClient(); const [ response ] = await client.createAssessment({...}); ``` `RecaptchaEnterpriseServiceClient` requires a service account to be created beforehand as described [here](https://cloud.google.com/docs/authentication/getting-started). The key for that account with the right roles set can then be read by the app. Check the arguments of the constructor to see the available options to pass the data if the file cannot be retrieved automatically.
54,695,113
I'm trying to create a filter based that is triggered by checkboxes, which shows and hides options from a list. I have tried to use resources online to put the script together but nothing seems to work. In order to hide or show list items I am editing a - class= "marker" parent element based on wether - class= "condtx" of its child element is matching the array of checked boxes "value" or not. I have included comments on how I am proceeding. Can anyone point me in the right direction please? ```js function filterCondtn1() { var i, z; //"chekedVal" array Keeps returning "undefined" I have no idea why var chekedVal = document.getElementById("InputOpts").getElementsByTagName("input").checked.value; //Gathered all <h3> tag options into array to be tested against "chekedVal" for match var condt1 = document.getElementsByClassName("condtn1").innerHTML; //Parrent class that will be edited to show <div> or not if True or false. var parrentClss = document.getElementsByClassName("marker"); //From here it's a blur. I've trying everything I can. I think I should be something of that sort. for { (var i = 0; i < condt1.length; i++) && (var z = 0; z < parrentClss.length; z++) RemoveClass(parrentClss[z], "show"); if (condt1[i].indexOf(chekedVal) > -1) AddClass(parrentClss[z], "show"); } } //Currently using these two functions in my script and they work function RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } function AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } ``` ```css .markerA { display: none; } .show { display: block; } ``` ```html <div id="InputOpts"> <input type="checkbox" value="option 1" oninput="filterCondtn1();">Option 1 <input type="checkbox" value="option 2" oninput="filterCondtn1();">Option 2 <input type="checkbox" value="option 3" oninput="filterCondtn1();">Option 3 <input type="checkbox" value="option 4" oninput="filterCondtn1();">Option 4 </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 1</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 3</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 2</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 4</h3> </div> </div> ```
2019/02/14
[ "https://Stackoverflow.com/questions/54695113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206451/" ]
You need to add the user remote IP address. ``` var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; request({ url: 'https://www.google.com/recaptcha/api/siteverify', method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: `secret=${secret}&response=${response}&remoteip=${user_ip}`}... ``` Another thing I see that you are not using template literal, you should change the quotes to ` instead of '. OR, You should use a ready-made module for reCaptcha, like this one: <https://www.npmjs.com/package/recaptcha>
``` var response = JSON.stringify(req.body.response); ``` The stringifying here is probably the cause of the invalid-input-response error. If your body is something like `{"g-recaptcha-response": "..."}`, you need to pull out the response value and pass that directly in your post. Regarding invalid-input-secret, if you have set up your key and secret through the classic interface at <https://www.google.com/u/1/recaptcha/admin/create>, then you shouldn't have a problem. However if you set up a key with recaptcha Enterprise on Google Cloud, then it requires that you do Oauth authentication to the Google Cloud API and then use the create.assessment endpoint to get back information on the validity of the user. As Yuuhn implied, the Google provided library makes interaction with recaptcha Enterprise easier, without a lot of documentation digging to find where your REST API calls need to go.
54,695,113
I'm trying to create a filter based that is triggered by checkboxes, which shows and hides options from a list. I have tried to use resources online to put the script together but nothing seems to work. In order to hide or show list items I am editing a - class= "marker" parent element based on wether - class= "condtx" of its child element is matching the array of checked boxes "value" or not. I have included comments on how I am proceeding. Can anyone point me in the right direction please? ```js function filterCondtn1() { var i, z; //"chekedVal" array Keeps returning "undefined" I have no idea why var chekedVal = document.getElementById("InputOpts").getElementsByTagName("input").checked.value; //Gathered all <h3> tag options into array to be tested against "chekedVal" for match var condt1 = document.getElementsByClassName("condtn1").innerHTML; //Parrent class that will be edited to show <div> or not if True or false. var parrentClss = document.getElementsByClassName("marker"); //From here it's a blur. I've trying everything I can. I think I should be something of that sort. for { (var i = 0; i < condt1.length; i++) && (var z = 0; z < parrentClss.length; z++) RemoveClass(parrentClss[z], "show"); if (condt1[i].indexOf(chekedVal) > -1) AddClass(parrentClss[z], "show"); } } //Currently using these two functions in my script and they work function RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } function AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } ``` ```css .markerA { display: none; } .show { display: block; } ``` ```html <div id="InputOpts"> <input type="checkbox" value="option 1" oninput="filterCondtn1();">Option 1 <input type="checkbox" value="option 2" oninput="filterCondtn1();">Option 2 <input type="checkbox" value="option 3" oninput="filterCondtn1();">Option 3 <input type="checkbox" value="option 4" oninput="filterCondtn1();">Option 4 </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 1</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 3</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 2</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 4</h3> </div> </div> ```
2019/02/14
[ "https://Stackoverflow.com/questions/54695113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206451/" ]
Due to the docs: <https://developers.google.com/recaptcha/docs/verify> invalid-input-secret: **The secret parameter is invalid or malformed.** Maybe you have mixed the site\_key and the secret\_key.
For reCAPTCHA Enterprise, check the official docs: <https://cloud.google.com/recaptcha-enterprise/docs/create-assessment>. In short, you need to use the library that Google provides: ``` const { RecaptchaEnterpriseServiceClient } = require('@google-cloud/recaptcha-enterprise'); const client = new RecaptchaEnterpriseServiceClient(); const [ response ] = await client.createAssessment({...}); ``` `RecaptchaEnterpriseServiceClient` requires a service account to be created beforehand as described [here](https://cloud.google.com/docs/authentication/getting-started). The key for that account with the right roles set can then be read by the app. Check the arguments of the constructor to see the available options to pass the data if the file cannot be retrieved automatically.
54,695,113
I'm trying to create a filter based that is triggered by checkboxes, which shows and hides options from a list. I have tried to use resources online to put the script together but nothing seems to work. In order to hide or show list items I am editing a - class= "marker" parent element based on wether - class= "condtx" of its child element is matching the array of checked boxes "value" or not. I have included comments on how I am proceeding. Can anyone point me in the right direction please? ```js function filterCondtn1() { var i, z; //"chekedVal" array Keeps returning "undefined" I have no idea why var chekedVal = document.getElementById("InputOpts").getElementsByTagName("input").checked.value; //Gathered all <h3> tag options into array to be tested against "chekedVal" for match var condt1 = document.getElementsByClassName("condtn1").innerHTML; //Parrent class that will be edited to show <div> or not if True or false. var parrentClss = document.getElementsByClassName("marker"); //From here it's a blur. I've trying everything I can. I think I should be something of that sort. for { (var i = 0; i < condt1.length; i++) && (var z = 0; z < parrentClss.length; z++) RemoveClass(parrentClss[z], "show"); if (condt1[i].indexOf(chekedVal) > -1) AddClass(parrentClss[z], "show"); } } //Currently using these two functions in my script and they work function RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } function AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } ``` ```css .markerA { display: none; } .show { display: block; } ``` ```html <div id="InputOpts"> <input type="checkbox" value="option 1" oninput="filterCondtn1();">Option 1 <input type="checkbox" value="option 2" oninput="filterCondtn1();">Option 2 <input type="checkbox" value="option 3" oninput="filterCondtn1();">Option 3 <input type="checkbox" value="option 4" oninput="filterCondtn1();">Option 4 </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 1</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 3</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn1">Option 2</h3> </div> </div> <div class="marker"> <div class="necessary"> <h3 class="condtn2">Option 4</h3> </div> </div> ```
2019/02/14
[ "https://Stackoverflow.com/questions/54695113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206451/" ]
Due to the docs: <https://developers.google.com/recaptcha/docs/verify> invalid-input-secret: **The secret parameter is invalid or malformed.** Maybe you have mixed the site\_key and the secret\_key.
``` var response = JSON.stringify(req.body.response); ``` The stringifying here is probably the cause of the invalid-input-response error. If your body is something like `{"g-recaptcha-response": "..."}`, you need to pull out the response value and pass that directly in your post. Regarding invalid-input-secret, if you have set up your key and secret through the classic interface at <https://www.google.com/u/1/recaptcha/admin/create>, then you shouldn't have a problem. However if you set up a key with recaptcha Enterprise on Google Cloud, then it requires that you do Oauth authentication to the Google Cloud API and then use the create.assessment endpoint to get back information on the validity of the user. As Yuuhn implied, the Google provided library makes interaction with recaptcha Enterprise easier, without a lot of documentation digging to find where your REST API calls need to go.
70,369,847
In the case of CPUs, the (linux specific) sys calls `getcpu()` or `sched_getcpu()` can be used inside a program to obtain the ID of the core executing them. For example, in the case of a 4 processors system, the logical index returned by the mentionned calls makes it possible to deduce which one of the 4 CPUs is being used (let's say every CPU contains 10 cores, therefore if `sched_getcpu()` returns 20, that means the CPU #2 is being used since the core number 20 is in the 3rd CPU). How can I achieve a similar thing in the case of GPUs? Is there a way to find which one is being used in real time from inside an application?
2021/12/15
[ "https://Stackoverflow.com/questions/70369847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9653244/" ]
Ignoring all of the irrelevant code in the question, the problem is this: ``` class base {}; class derived : base {}; base *ptr = new derived; ``` `derived` inherits **privately** from `base`, so, as the error message says, converting that `derived*` created by `new derived` to a `base*` is not legal. The fix is simply to publicly inherit: ``` class derived : public base {}; ```
You need to publicly inherit it (with `class` it default to `private`) ``` class silver : public card { //... }; ``` you cannot access private base outside because, well, it's private (like private member)
17,358,226
I want to fix width of gridview. I am filling gridview as following; ``` sorgu = "select urun.urunId as \"İş No\",urun.modelNo as \"Model No\",modelAd as \"Model Adı\",bedenAd as \"Beden\", adet as \"Adet\"" + ",aciklama as \"Açıklama\", kesmeTalimat as \"Kesim Talimatı\", atolyeTalimat as \"Atölye Talimatı\", yikamaTalimat as \"Yıkama Talimatı\", utuTalimat as \"Ütü Talimatı\", (k4.ad+' '+k4.soyad) as \"Kesim\", (k1.ad+' '+k1.soyad) as \"Atölye\"" + ",(k2.ad+' '+k2.soyad) as \"Yıkama\",(k3.ad+' '+k3.soyad) as \"Ütü\", (k5.ad+' '+k5.soyad) as \"Kontrol\" from kullanici k1,kullanici k4,kullanici k5,kullanici k2,kullanici k3,model,beden,urun,fason,isTalimat,durum" + " where urun.urunId= fason.urunId and urun.urunId=isTalimat.urunId and urun.urunId=durum.urunId and model.modelNo=urun.modelNo and beden.bedenNo=urun.bedenNo and" + " fason.atolye=k1.id and fason.yikama=k2.id and fason.kesimci=k4.id and fason.kontrol=k5.id and fason.utu=k3.id"; connection.Open(); command.Connection = connection; command.CommandText = sorgu; dr = command.ExecuteReader(); DataTable dtTumISler = new DataTable(); dtTumISler.Load(dr); dgvTumIsler.DataSource = dtTumISler; dgvTumIsler.DataBind(); dr.Close(); connection.Close(); dtTumISler.Dispose(); ``` Here dgvTumİsler is my gridview. I have tried the following code to make fixed length. But it does not work; ``` for (int i = 0; i < dgvTumIsler.Columns.Count; i++) { dgvTumIsler.Columns[i].ItemStyle.Width = 100; } ``` Here dgvTumİsler.Columns.Count value is 1. So it does not work. Is there a way to solve this problem or is there another way to make a gridview fixed width. HTML code: ``` <asp:GridView ID="dgvTumIsler" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnSelectedIndexChanged="dgvTumIsler_SelectedIndexChanged"> <Columns> <asp:CommandField ButtonType="Button" SelectText="Seç" ShowCancelButton="False" ShowSelectButton="True" /> </Columns> <FooterStyle BackColor="White" ForeColor="#000066" /> <HeaderStyle BackColor="#006699" Font-Bold="false" ForeColor="White" /> <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> <RowStyle ForeColor="#000066" /> <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> <SortedAscendingCellStyle BackColor="#F1F1F1" /> <SortedAscendingHeaderStyle BackColor="#007DBB" /> <SortedDescendingCellStyle BackColor="#CAC9C9" /> <SortedDescendingHeaderStyle BackColor="#00547E" /> </asp:GridView> ```
2013/06/28
[ "https://Stackoverflow.com/questions/17358226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2511352/" ]
Instead of using "change" event, the "key" event does fire on the source view. Thanks for Kicker's hint
[The CKEditor 4 documentation](https://docs.ckeditor.com/ckeditor4/docs/#!/api/CKEDITOR.editor-event-change) tells that the change event won't be fired in source mode. The example from the documentation worked for me. It binds a listener to the mode event. That's fired when the mode changes. When it changes to source, attach a listener to the editor. ``` editor.on('mode', function() { if (this.mode === 'source') { var editable = editor.editable(); editable.attachListener(editable, 'input', function() { // Handle changes made in the source mode. }); } }); ```
391,144
Why does macOS need to verify LibreOffice each time after a restart? I haven't updated the app in a while, and after the first verification it opens normally the next time. This is annoying and it takes a long time (about a minute). This should happen once, after installing (in the /Applications folder), not repeatedly. This doesn't happen for other apps. [![Verifying Libreoffice App](https://i.stack.imgur.com/mLnnj.png)](https://i.stack.imgur.com/mLnnj.png) **How can I make macOS stop verifying LO after a restart?** NB: Saw the same happening to Firefox, but not Thunderbird and Evernote. --- **Update** I installed this app several months ago. And I mention that this happens after a restart. So I don't open the app from a DMG, which would be unmounted after a restart anyways.
2020/05/14
[ "https://apple.stackexchange.com/questions/391144", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/35070/" ]
* <https://bugs.documentfoundation.org/show_bug.cgi?id=126409> It is a bug filed on LibreOffice's tracker. So they're aware of it. Please do not flood the tracker with "me too" comments.
You still seem to start LibreOffice from the DMG file it was delivered in. Just drag the LibreOffice icon into your `/Applications` folder to install it properly. You can then eject and delete the DMG file.
391,144
Why does macOS need to verify LibreOffice each time after a restart? I haven't updated the app in a while, and after the first verification it opens normally the next time. This is annoying and it takes a long time (about a minute). This should happen once, after installing (in the /Applications folder), not repeatedly. This doesn't happen for other apps. [![Verifying Libreoffice App](https://i.stack.imgur.com/mLnnj.png)](https://i.stack.imgur.com/mLnnj.png) **How can I make macOS stop verifying LO after a restart?** NB: Saw the same happening to Firefox, but not Thunderbird and Evernote. --- **Update** I installed this app several months ago. And I mention that this happens after a restart. So I don't open the app from a DMG, which would be unmounted after a restart anyways.
2020/05/14
[ "https://apple.stackexchange.com/questions/391144", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/35070/" ]
* <https://bugs.documentfoundation.org/show_bug.cgi?id=126409> It is a bug filed on LibreOffice's tracker. So they're aware of it. Please do not flood the tracker with "me too" comments.
It appears you do not have the app installed on your computer, and hence the app config is missing, causing macOS to ask you to verify with every restart. You should consider installing it as mentioned in [@nohillside's answer](https://apple.stackexchange.com/a/391145/279727), by dragging to copy the LibreOffice.app into the `/Applications` directory. [![enter image description here](https://i.stack.imgur.com/tVdkU.png)](https://i.stack.imgur.com/tVdkU.png) Alternatively, you can also install the app using [Homebrew](https://brew.sh). If you already use Homebrew, you can simply run the following command-line in Terminal.app to install the app: ``` brew cask install libreoffice ``` If you do not have Homebrew installed, you can follow the installation instructions on Homebrew [website](https://brew.sh) to install it before running the above command.
405,305
It is well known that an estimator's MSE can be decomposed into the sum of the variance and the squared bias. I'd like to actually perform this decomposition. Here is some code to set up and train a small model. ``` import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.kernel_ridge import KernelRidge x = np.linspace(0,10,1001).reshape(-1,1) X = np.random.uniform(low = 0, high =10, size = 2000).reshape(-1,1) y = 3*np.sin(X) + 2.5*np.random.normal(size = X.shape) X_train, X_test, y_train, y_test = train_test_split(X,y,train_size = 0.6) reg = KernelRidge(kernel='rbf', gamma = 1).fit(X,y) mse = mean_squared_error(y_test, reg.predict(X_test)) print(mse) ``` How can I go about computing the squared bias and the variance for this estimator?
2019/04/26
[ "https://stats.stackexchange.com/questions/405305", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/111259/" ]
The MSE and its components (squared bias and variance) are random variables. Therefore, in order to accurately access these statistics you need to iterate the process many times. For this purpose, we generally use bootstrapping. The procedure for obtaining bias and variance terms is as follows: 1. Generate multiple training data sets by bootstrapping (e.g. K=200). 2. For each set, train your model. You will end up with K=200 models. 3. For each model, predict the targets for the out-of-bag samples (samples which did not appear in the training sets). Now, for each out-of-bag sample $(x\_i,y\_i)$ you can obtain K predictions (say $h^1, h^2,.....,h^k$). 4. Average these predictions to obtain $\bar{h}$ 5. Then, the bias of your model (for a single sample) will be $(\bar{h}-y\_i)$ 6. The variance will be $\sum\_{k} \frac{(y\_i^k-\bar{h})^2}{K-1}$ 7. Do this for all out-of-bag samples and average bias and variance values for better estimates.
[![MSE Variance|Bias decomposition](https://i.stack.imgur.com/Jr6Zo.png)](https://i.stack.imgur.com/Jr6Zo.png) The key for understanding the previous MSE decomposition is to realise that $\theta$ represents a point variable with a fixed value and $\hat{\theta}$ represents a vector containing samples from the estimator (random variable). *As clarification, this formula does not apply to the case where $\theta$ represents a series of values and $\hat{\theta}$ contains element-wise estimations of these points.* A simple numpy example that verifies the previous formula might be useful for understanding this: ``` import numpy as np # theta is the target value (point) theta = 10 # theta_hat contains estimations of theta (vector of 1000 samples) theta_hat = np.random.normal(theta,0.2,1000) mse = np.mean(np.square(theta-theta_hat)) var = np.var(theta_hat) bias = np.mean(theta_hat) - theta print("MSE result:", mse) print("Decomposed result:", var + bias*bias) ``` Which in my case returns `0.042668...` in both cases.
10,008,614
I've just moved a Joomla 1.7 site to a new server. Administration back-end works fine. Configuration.php seems fine. Get "The requested document was not found on this server." for every page other than Home. Must be talking to the database OK or I'd get an error. Could this be a problem with the PHP? Thanks, Andy
2012/04/04
[ "https://Stackoverflow.com/questions/10008614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559152/" ]
* Did you clear joomla cache ? * Disable page and/or module caching. * Disable any plugin that optimizes "loading speed". * Try removing SEF URLs (Joomla! and any 3rd party extension). * If you are using a custom .htacess, then use an unmodified joomla one. * Disable some system plugins. * Disable modules in the homepage. * Have you tried using another template (site) ?
Check whether you are using any modules that is calling database and you have not changed DB details in that module after migration. If admin panel is working fine then I think problem with some modules that are used in front-end. You can do debugging by disabling few suspected modules and check whether your site works fine or not. Else provide some more information about your site so that I can check further.
10,008,614
I've just moved a Joomla 1.7 site to a new server. Administration back-end works fine. Configuration.php seems fine. Get "The requested document was not found on this server." for every page other than Home. Must be talking to the database OK or I'd get an error. Could this be a problem with the PHP? Thanks, Andy
2012/04/04
[ "https://Stackoverflow.com/questions/10008614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559152/" ]
You have Seach Engine Friendly URLs enabled in /administrator/ area's global configuration settings. You have probably enabled the option to use the mod\_rewrite function which removes the /index.php/ portion of the urls. It is a requirement of this mode that you have the .htaccess file in place in the root of your site. You probably had this correctly configured on your development server but perhaps forgot to move the file across when you went live. Some FTP programs hide dot files (files starting with a leading dot in the filename) so depending upon how you transferred the files (I'm guessing manually with FTP rather than Akeeba backup or similar) the file may have been missed. Look through your FTP client's options/preferences for an option to show/hide hidden files. Failing this - the file could be correctly in place - but if you were developing in a sub-folder on your development server you would have set the RewriteBase line to your /sub-folder/ ``` RewriteBase /sub-folder/ ``` Now you've moved to the live server this line could be incorrect. If this is the case, edit the file to Read ``` RewriteBase / ``` Chances are it is one or other of these issues - missing .htaccess file or incorrect RewriteBase. A third and nowadays somewhat more unlikely option is that your server doesn't have mod\_rewrite enabled - but I think that would result in server 500 errors.
Check whether you are using any modules that is calling database and you have not changed DB details in that module after migration. If admin panel is working fine then I think problem with some modules that are used in front-end. You can do debugging by disabling few suspected modules and check whether your site works fine or not. Else provide some more information about your site so that I can check further.
10,008,614
I've just moved a Joomla 1.7 site to a new server. Administration back-end works fine. Configuration.php seems fine. Get "The requested document was not found on this server." for every page other than Home. Must be talking to the database OK or I'd get an error. Could this be a problem with the PHP? Thanks, Andy
2012/04/04
[ "https://Stackoverflow.com/questions/10008614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559152/" ]
* Did you clear joomla cache ? * Disable page and/or module caching. * Disable any plugin that optimizes "loading speed". * Try removing SEF URLs (Joomla! and any 3rd party extension). * If you are using a custom .htacess, then use an unmodified joomla one. * Disable some system plugins. * Disable modules in the homepage. * Have you tried using another template (site) ?
You have Seach Engine Friendly URLs enabled in /administrator/ area's global configuration settings. You have probably enabled the option to use the mod\_rewrite function which removes the /index.php/ portion of the urls. It is a requirement of this mode that you have the .htaccess file in place in the root of your site. You probably had this correctly configured on your development server but perhaps forgot to move the file across when you went live. Some FTP programs hide dot files (files starting with a leading dot in the filename) so depending upon how you transferred the files (I'm guessing manually with FTP rather than Akeeba backup or similar) the file may have been missed. Look through your FTP client's options/preferences for an option to show/hide hidden files. Failing this - the file could be correctly in place - but if you were developing in a sub-folder on your development server you would have set the RewriteBase line to your /sub-folder/ ``` RewriteBase /sub-folder/ ``` Now you've moved to the live server this line could be incorrect. If this is the case, edit the file to Read ``` RewriteBase / ``` Chances are it is one or other of these issues - missing .htaccess file or incorrect RewriteBase. A third and nowadays somewhat more unlikely option is that your server doesn't have mod\_rewrite enabled - but I think that would result in server 500 errors.
150,327
A lot of universities are expecting not to be able to run in-person exams for at least part of the 2020/21 academic year. I believe, for example, that no UK universities is currently planning to hold in-person exams this coming January. I can see how other forms of assessment might be possible for some subjects. But I can't see how this can work for math. > > For those universities which will not run math exams in-person for this > coming year, what are the plans for how to replace them? > > >
2020/06/10
[ "https://academia.stackexchange.com/questions/150327", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/37765/" ]
Here are some examples of how it is done at the University of Copenhagen for the two courses that I have exams in next week. One course has a written exam: We are given a problem sheet that we write up a solution to and submit to an online portal after a time limit of four hours. We are allowed to use the internet and any other aids we wish, except that we are not allowed to communicate with other people. Another course has a verbal exam: A verbal exam is performed using Zoom. There is no preparation time. Both courses were intended to be verbal exams pre-covid-19.
It's not possible to give a universal answer, of course, as that depends on many factors: how many people are available to grade, how many students need to pass the course (solutions that work for 20 students may not work for 200), what technological solutions are available… In our department somewhere in France, the solutions adopted for the various exams are: * A normal homework, sent electronically by taking a picture of the answers, graded normally, with a long delay (a week or so) to complete. For very low level courses it's also possible to have a fully online exam, with multiple choice questions and short answers. * A timed exam. This can be the same time for all students, common for low level courses where copying others' answers is trivial. Or it can be an exam available during a whole day, and when the student downloads the exam they are put on a timer and must give back their answers before a time limit (a few hours). * Oral examinations using visioconference tools. The students connects with the examiner and gets asked questions, usually with the help of a virtual whiteboard. * A hybrid method: students are given a timed exam, which is then graded (takes a few days). Then students pass a short oral exam about the content of the written exam. Depending on the size of the class, this can either be all students, or students who got above a certain grade on the written exam (to avoid "wasting" time on students who have no chance of passing regardless of how well they perform on the oral exam). The goal is try and bump up students, and detect some cheating. My preference goes towards the last item, but it's a significant time investment, much more so than a traditional handwritten exam. It takes a lot of organization, there is a lot of cheating anyway, technical issues arise all the time for the video chat, the exam needs to be specially designed... After a department-wide meeting, we have pretty much all agreed that there was no good solution anyway. Maybe someone here has a better one...
15,470,937
I have been trying to populate an array using a for loop and taking such values using `document.getElementById("spin " + i).value;` The `ids` on my html for every input tag go from spin1 to spin18. Any suggestions on what I am doing wrong? Or what I can change? ``` var nums = []; for(var i = 1; i <= 18; i++){ var num[i] = parseInt(document.getElementById("spin" + i).value); nums.push(num[i]); } alert(nums.length); ```
2013/03/18
[ "https://Stackoverflow.com/questions/15470937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1890684/" ]
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like. The js looks compilable, but here are some pointers. **The number 0 is before 1** ---------------------------- It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart. ``` 0 10 1 11 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19 ``` **Avoid unnecessary variables** ------------------------------- Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one. ``` var nums = []; for( var i = 0; i < 18; i++ ) { nums[i] = parseInt( document.getElementById("spin" + i).value ); } ``` **Don't push, insert** ---------------------- The push method has an expensive overhead so use it with caution. **Loggers** ----------- The console has a built in logger, why not use that instead of an alert box? ``` console.log( nums.length ); ```
try this ``` var nums = []; for(var i = 1; i <= 18; i++){ var num= parseInt(document.getElementById("spin" + i).value); nums.push(num); } alert(nums.length); ```
15,470,937
I have been trying to populate an array using a for loop and taking such values using `document.getElementById("spin " + i).value;` The `ids` on my html for every input tag go from spin1 to spin18. Any suggestions on what I am doing wrong? Or what I can change? ``` var nums = []; for(var i = 1; i <= 18; i++){ var num[i] = parseInt(document.getElementById("spin" + i).value); nums.push(num[i]); } alert(nums.length); ```
2013/03/18
[ "https://Stackoverflow.com/questions/15470937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1890684/" ]
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like. The js looks compilable, but here are some pointers. **The number 0 is before 1** ---------------------------- It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart. ``` 0 10 1 11 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19 ``` **Avoid unnecessary variables** ------------------------------- Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one. ``` var nums = []; for( var i = 0; i < 18; i++ ) { nums[i] = parseInt( document.getElementById("spin" + i).value ); } ``` **Don't push, insert** ---------------------- The push method has an expensive overhead so use it with caution. **Loggers** ----------- The console has a built in logger, why not use that instead of an alert box? ``` console.log( nums.length ); ```
A couple of things to note: 1. As PSR has mentioned, you use: ``` var num[i] ``` when it should be ``` var num ``` 1. `getElementById(id).value` only works for form elements, you have to use `.innerHTML` for divs. This works for me: <http://jsfiddle.net/sbqeT/>
127,679
How can I adjust the placement of `y unit` with `pgfplots`? I'm trying to put it near the top-left corner of the graph box. However, there *may* (but does not have to) be a scientific multiplier. As shown in the professionally type-set picture below, the unit should be displayed just after the multiplier and of course be lined up with it as if written as a whole: `$10^3$[m]`. In case values on `y` axis were smaller and exponential notation wasn't shown, the `[m]` unit should be still rendered above the top-left corner, but preferably closer to the left edge. ![output graph](https://i.stack.imgur.com/72XTS.jpg) I'm aware of the fact that the `[m]` unit in the picture is drawn along with `y` axis label. I don't need to put the whole `y label` near the multiplier, but just the unit. In fact I don't need the axis label at all. Is it possible to control how the scientific multiplier is formatted and append a unit? I'm not sure whether it's important, but for the sake of completeness, let me add that I have incorporated Jake's tick scaling solution from [here](https://tex.stackexchange.com/a/124268/10662) to have only exponents, which are a multiple of 3. MWE provided: ``` \documentclass{minimal} \usepackage{pgfplots} \usepgfplotslibrary{units} \makeatletter \newif\ifpgfplots@scaled@x@ticks@engineering \pgfplots@scaled@x@ticks@engineeringfalse \newif\ifpgfplots@scaled@y@ticks@engineering \pgfplots@scaled@y@ticks@engineeringfalse \newif\ifpgfplots@scaled@z@ticks@engineering \pgfplots@scaled@z@ticks@engineeringfalse \pgfplotsset{ scaled x ticks/engineering/.code= \pgfplots@scaled@x@ticks@engineeringtrue, scaled y ticks/engineering/.code= \pgfplots@scaled@y@ticks@engineeringtrue, scaled z ticks/engineering/.code= \pgfplots@scaled@y@ticks@engineeringtrue, % scaled ticks=engineering % Uncomment this line if you want "engineering" to be on by default } \def\pgfplots@init@scaled@tick@for#1{% \global\def\pgfplots@glob@TMPa{0}% \expandafter\pgfplotslistcheckempty\csname pgfplots@prepared@tick@positions@major@#1\endcsname \ifpgfplotslistempty % we have no tick labels. Omit the tick scale label as well! \else \begingroup \ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname\relax % CASE 0 : scaled #1 ticks=false: do nothing here. \or % CASE 1 : scaled #1 ticks=true: %-------------------------------- % the \pgfplots@xmin@unscaled@as@float is set just before the data % scale transformation is initialised. % % The variables are empty if there is no datascale transformation. \expandafter\let\expandafter\pgfplots@cur@min@unscaled\csname pgfplots@#1min@unscaled@as@float\endcsname \expandafter\let\expandafter\pgfplots@cur@max@unscaled\csname pgfplots@#1max@unscaled@as@float\endcsname % \ifx\pgfplots@cur@min@unscaled\pgfutil@empty \edef\pgfplots@loc@TMPa{\csname pgfplots@#1min\endcsname}% \expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}% \let\pgfplots@cur@min@unscaled=\pgfmathresult \edef\pgfplots@loc@TMPa{\csname pgfplots@#1max\endcsname}% \expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}% \let\pgfplots@cur@max@unscaled=\pgfmathresult \fi % \expandafter\pgfmathfloat@decompose@E\pgfplots@cur@min@unscaled\relax\pgfmathfloat@a@E \expandafter\pgfmathfloat@decompose@E\pgfplots@cur@max@unscaled\relax\pgfmathfloat@b@E \pgfplots@init@scaled@tick@normalize@exponents \ifnum\pgfmathfloat@b@E<\pgfmathfloat@a@E \pgfmathfloat@b@E=\pgfmathfloat@a@E \fi \xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@above@exponent}% \ifnum\pgfplots@glob@TMPa<\pgfmathfloat@b@E % ok, scale it: \expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three) \csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname \csname iftrue\endcsname \divide\pgfmathfloat@b@E by 3 \multiply\pgfmathfloat@b@E by 3 \fi \multiply\pgfmathfloat@b@E by-1 \xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}% \else \xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@below@exponent}% \ifnum\pgfplots@glob@TMPa>\pgfmathfloat@b@E % ok, scale it: \expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three) \csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname \csname iftrue\endcsname \advance\pgfmathfloat@b@E by -2 \divide\pgfmathfloat@b@E by 3 \multiply\pgfmathfloat@b@E by 3 \fi \multiply\pgfmathfloat@b@E by-1 \xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}% \else % no scaling necessary: \xdef\pgfplots@glob@TMPa{0}% \fi \fi \or % CASE 2 : scaled #1 ticks=base 10: %-------------------------------- \c@pgf@counta=\csname pgfplots@scaled@ticks@#1@arg\endcsname\relax %\multiply\c@pgf@counta by-1 \xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}% \or % CASE 3 : scaled #1 ticks=real: %-------------------------------- \pgfmathfloatparsenumber{\csname pgfplots@scaled@ticks@#1@arg\endcsname}% \global\let\pgfplots@glob@TMPa=\pgfmathresult \or % CASE 4 : scaled #1 ticks=manual: \expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@scaled@ticks@#1@arg\endcsname \fi \endgroup \fi \expandafter\let\csname pgfplots@tick@scale@#1\endcsname=\pgfplots@glob@TMPa% } \makeatother \begin{document} \begin{tikzpicture} \begin{axis}[scaled ticks=engineering, y unit=m,height=4cm] \addplot [domain=0:1] {10000*\x}; \end{axis} \end{tikzpicture} The multiplier should be printed as $\cdot10^3$[m] instead of merely $\cdot10^3$. \end{document} ```
2013/08/11
[ "https://tex.stackexchange.com/questions/127679", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10662/" ]
Here's an approach that doesn't use the `units` library, but instead defines a new key `y unit label=<text>` that places the `<text>` behind the scale label (if it exists) or at the position of the scale label (if it doesn't). If you put the following code in your preamble... ``` \makeatletter \long\def\ifnodedefined#1#2#3{% \@ifundefined{pgf@sh@ns@#1}{#3}{#2}% } \pgfplotsset{ y unit label/.style={ y tick scale label style={ name=y tick scale label, inner xsep=0pt }, after end axis/.append code={ \ifnodedefined{y tick scale label}{% \tikzset{ every y unit label/.append style={ anchor=base west, at=(y tick scale label.base east) } } }{% \tikzset{ every y unit label/.append style={ /pgfplots/every y tick scale label } } } \node [every y unit label] {#1}; } } } \makeatother ``` ... you can write the following ... ``` \begin{axis}[ scaled ticks=engineering, y unit label=m, height=4cm, ] \addplot [domain=0:1] {10000*\x}; \end{axis} ``` ... to get ... ![](https://i.stack.imgur.com/j2ZnT.png) ... or ... ``` \begin{axis}[ scaled ticks=engineering, y unit label=m, height=4cm, ] \addplot [domain=0:1] {10000*\x}; \end{axis} ``` ... to get ... ![](https://i.stack.imgur.com/1Gg0B.png) --- Complete code: ``` \documentclass{article} \usepackage{pgfplots} \makeatletter \newif\ifpgfplots@scaled@x@ticks@engineering \pgfplots@scaled@x@ticks@engineeringfalse \newif\ifpgfplots@scaled@y@ticks@engineering \pgfplots@scaled@y@ticks@engineeringfalse \newif\ifpgfplots@scaled@z@ticks@engineering \pgfplots@scaled@z@ticks@engineeringfalse \pgfplotsset{ scaled x ticks/engineering/.code= \pgfplots@scaled@x@ticks@engineeringtrue, scaled y ticks/engineering/.code= \pgfplots@scaled@y@ticks@engineeringtrue, scaled z ticks/engineering/.code= \pgfplots@scaled@y@ticks@engineeringtrue, % scaled ticks=engineering % Uncomment this line if you want "engineering" to be on by default } \def\pgfplots@init@scaled@tick@for#1{% \global\def\pgfplots@glob@TMPa{0}% \expandafter\pgfplotslistcheckempty\csname pgfplots@prepared@tick@positions@major@#1\endcsname \ifpgfplotslistempty % we have no tick labels. Omit the tick scale label as well! \else \begingroup \ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname\relax % CASE 0 : scaled #1 ticks=false: do nothing here. \or % CASE 1 : scaled #1 ticks=true: %-------------------------------- % the \pgfplots@xmin@unscaled@as@float is set just before the data % scale transformation is initialised. % % The variables are empty if there is no datascale transformation. \expandafter\let\expandafter\pgfplots@cur@min@unscaled\csname pgfplots@#1min@unscaled@as@float\endcsname \expandafter\let\expandafter\pgfplots@cur@max@unscaled\csname pgfplots@#1max@unscaled@as@float\endcsname % \ifx\pgfplots@cur@min@unscaled\pgfutil@empty \edef\pgfplots@loc@TMPa{\csname pgfplots@#1min\endcsname}% \expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}% \let\pgfplots@cur@min@unscaled=\pgfmathresult \edef\pgfplots@loc@TMPa{\csname pgfplots@#1max\endcsname}% \expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}% \let\pgfplots@cur@max@unscaled=\pgfmathresult \fi % \expandafter\pgfmathfloat@decompose@E\pgfplots@cur@min@unscaled\relax\pgfmathfloat@a@E \expandafter\pgfmathfloat@decompose@E\pgfplots@cur@max@unscaled\relax\pgfmathfloat@b@E \pgfplots@init@scaled@tick@normalize@exponents \ifnum\pgfmathfloat@b@E<\pgfmathfloat@a@E \pgfmathfloat@b@E=\pgfmathfloat@a@E \fi \xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@above@exponent}% \ifnum\pgfplots@glob@TMPa<\pgfmathfloat@b@E % ok, scale it: \expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three) \csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname \csname iftrue\endcsname \divide\pgfmathfloat@b@E by 3 \multiply\pgfmathfloat@b@E by 3 \fi \multiply\pgfmathfloat@b@E by-1 \xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}% \else \xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@below@exponent}% \ifnum\pgfplots@glob@TMPa>\pgfmathfloat@b@E % ok, scale it: \expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three) \csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname \csname iftrue\endcsname \advance\pgfmathfloat@b@E by -2 \divide\pgfmathfloat@b@E by 3 \multiply\pgfmathfloat@b@E by 3 \fi \multiply\pgfmathfloat@b@E by-1 \xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}% \else % no scaling necessary: \xdef\pgfplots@glob@TMPa{0}% \fi \fi \or % CASE 2 : scaled #1 ticks=base 10: %-------------------------------- \c@pgf@counta=\csname pgfplots@scaled@ticks@#1@arg\endcsname\relax %\multiply\c@pgf@counta by-1 \xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}% \or % CASE 3 : scaled #1 ticks=real: %-------------------------------- \pgfmathfloatparsenumber{\csname pgfplots@scaled@ticks@#1@arg\endcsname}% \global\let\pgfplots@glob@TMPa=\pgfmathresult \or % CASE 4 : scaled #1 ticks=manual: \expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@scaled@ticks@#1@arg\endcsname \fi \endgroup \fi \expandafter\let\csname pgfplots@tick@scale@#1\endcsname=\pgfplots@glob@TMPa% } \makeatother \makeatletter \long\def\ifnodedefined#1#2#3{% \@ifundefined{pgf@sh@ns@#1}{#3}{#2}% } \pgfplotsset{ y unit label/.style={ y tick scale label style={ name=y tick scale label, inner xsep=0pt }, after end axis/.append code={ \ifnodedefined{y tick scale label}{% \tikzset{ every y unit label/.append style={ anchor=base west, at=(y tick scale label.base east) } } }{% \tikzset{ every y unit label/.append style={ /pgfplots/every y tick scale label } } } \node [every y unit label] {#1}; } } } \makeatother \pgfplotsset{compat=1.8} \begin{document} \begin{tikzpicture} \begin{axis}[ scaled ticks=engineering, y unit label=m, height=4cm, ] \addplot [domain=0:1] {10*\x}; \end{axis} \end{tikzpicture} \end{document} ```
Not a general approach, but a stopgap in case no other solution presents itself. In this case, turn off the y-axis label, and overlay the image with the desired text at the specified location. The relevant lines that changed relative to your MWE were the following: ``` \usepackage{stackengine} \def\stackalignment{l} \begin{document} \topinset{[m]}{% \begin{tikzpicture} \begin{axis}[scaled ticks=engineering, height=4cm] \addplot [domain=0:1] {10000*\x}; \end{axis} \end{tikzpicture}% }{.03in}{.8in} ``` ![enter image description here](https://i.stack.imgur.com/pOlAd.jpg)
4,599,321
i have a problem with Autotest. In my user model are the username & email address unique. When i start Autotest everything works fine. In the secound round, from autotest, i have a > > Validation failed: Email has already been taken, Username has already been taken > > > error in only two test. I dont understand why, i use factorygirl with an sequenze and this should generate everytime a new username. This is my rspec2 file: ``` describe User do specify { Factory.build(:user).should be_valid } context "unique values" do before :all do @user = Factory.create(:user) end it "should have an unique email address" do Factory.build(:user, :email => @user.email).should_not be_valid end it "should have an unique username" do Factory.build(:user, :username => @user.username).should_not be_valid end end context "required attributes" do it "should be invalid without an email address" do Factory.build(:user, :email => nil).should_not be_valid end it "should be invalid without an username" do Factory.build(:user, :username => nil).should_not be_valid end it "should be invalid without an password" do Factory.build(:user, :password => nil).should_not be_valid end it "should be invalid without an address" do Factory.build(:user, :address => nil).should_not be_valid end end end ``` The Factory: ``` Factory.sequence :username do |n| "Outfit#{n}er" end Factory.sequence :email do |n| "user#{n}@example.com" end Factory.define :user do |u| u.username { Factory.next :username } u.email { Factory.next :email } u.password 'secret' u.phone_number '02214565854' u.association :address, :factory => :address end Factory.define :confirmed_user, :parent => :user do |u| u.after_build { |user| user.confirm! } end ``` The only two test that are not working are in the "unique values" context. All other test works without an error. Thanks
2011/01/04
[ "https://Stackoverflow.com/questions/4599321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210023/" ]
This is exactly the problem I had just run into -- and had a strange experience where this problem didn't seem to happen if I was just running "rake spec". After not finding an obvious answer, I did try something that seems to have solved the problem! It seems like setting a class variable inside a before() block is the culprit, if you're using FactoryGirl. I had something very similar: ``` factory :widget do sequence(:name) { |n| "widget#{n}" } end ``` then: ``` describe Widget do before(:each) { @widget = FactoryGirl.create(:widget) } it ...yadda yadda... @widget.foo() end end ``` autotest would find uniqueness constraint problems. I changed the rspect test to this: ``` describe Widget do let(:widget) { FactoryGirl.create(:widget) } it ...yadda yadda... widget.foo() end end ``` ...and the uniqueness constraint issues went away. Not sure why this happens, and it seems like it *shouldn't* happen, but may be a workable resolution.
The problem is probably in your config file. You have a line in your spec config file (probably spec\_helper.rb) that reads: ``` config.use_transactional_fixtures = false ``` This should be: ``` config.use_transactional_fixtures = true ``` Or if you don't want to use transactional fixtures, you should have a before(:each) function in your test: ``` before :each do User.destroy_all end ``` Alternatively, I use [the Sham gem](https://rubygems.org/gems/sham) for my factories because it's more compatible with non-transactional fixtures and sequences.
4,599,321
i have a problem with Autotest. In my user model are the username & email address unique. When i start Autotest everything works fine. In the secound round, from autotest, i have a > > Validation failed: Email has already been taken, Username has already been taken > > > error in only two test. I dont understand why, i use factorygirl with an sequenze and this should generate everytime a new username. This is my rspec2 file: ``` describe User do specify { Factory.build(:user).should be_valid } context "unique values" do before :all do @user = Factory.create(:user) end it "should have an unique email address" do Factory.build(:user, :email => @user.email).should_not be_valid end it "should have an unique username" do Factory.build(:user, :username => @user.username).should_not be_valid end end context "required attributes" do it "should be invalid without an email address" do Factory.build(:user, :email => nil).should_not be_valid end it "should be invalid without an username" do Factory.build(:user, :username => nil).should_not be_valid end it "should be invalid without an password" do Factory.build(:user, :password => nil).should_not be_valid end it "should be invalid without an address" do Factory.build(:user, :address => nil).should_not be_valid end end end ``` The Factory: ``` Factory.sequence :username do |n| "Outfit#{n}er" end Factory.sequence :email do |n| "user#{n}@example.com" end Factory.define :user do |u| u.username { Factory.next :username } u.email { Factory.next :email } u.password 'secret' u.phone_number '02214565854' u.association :address, :factory => :address end Factory.define :confirmed_user, :parent => :user do |u| u.after_build { |user| user.confirm! } end ``` The only two test that are not working are in the "unique values" context. All other test works without an error. Thanks
2011/01/04
[ "https://Stackoverflow.com/questions/4599321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210023/" ]
I have gotten that problem from having the database not being properly cleared after some tests. If you run: rake db:test:prepare before the autotest, does it still happen? I eventually got around it by isolating which tests were not being cleared and fixing them (or removing them). Sorry, I can't remember what was the problem, but it had some error causing it. Oh, and I ran it without spork, so that I could see my logger messages mixed in with the results. Hope this helps.
The problem is probably in your config file. You have a line in your spec config file (probably spec\_helper.rb) that reads: ``` config.use_transactional_fixtures = false ``` This should be: ``` config.use_transactional_fixtures = true ``` Or if you don't want to use transactional fixtures, you should have a before(:each) function in your test: ``` before :each do User.destroy_all end ``` Alternatively, I use [the Sham gem](https://rubygems.org/gems/sham) for my factories because it's more compatible with non-transactional fixtures and sequences.
4,599,321
i have a problem with Autotest. In my user model are the username & email address unique. When i start Autotest everything works fine. In the secound round, from autotest, i have a > > Validation failed: Email has already been taken, Username has already been taken > > > error in only two test. I dont understand why, i use factorygirl with an sequenze and this should generate everytime a new username. This is my rspec2 file: ``` describe User do specify { Factory.build(:user).should be_valid } context "unique values" do before :all do @user = Factory.create(:user) end it "should have an unique email address" do Factory.build(:user, :email => @user.email).should_not be_valid end it "should have an unique username" do Factory.build(:user, :username => @user.username).should_not be_valid end end context "required attributes" do it "should be invalid without an email address" do Factory.build(:user, :email => nil).should_not be_valid end it "should be invalid without an username" do Factory.build(:user, :username => nil).should_not be_valid end it "should be invalid without an password" do Factory.build(:user, :password => nil).should_not be_valid end it "should be invalid without an address" do Factory.build(:user, :address => nil).should_not be_valid end end end ``` The Factory: ``` Factory.sequence :username do |n| "Outfit#{n}er" end Factory.sequence :email do |n| "user#{n}@example.com" end Factory.define :user do |u| u.username { Factory.next :username } u.email { Factory.next :email } u.password 'secret' u.phone_number '02214565854' u.association :address, :factory => :address end Factory.define :confirmed_user, :parent => :user do |u| u.after_build { |user| user.confirm! } end ``` The only two test that are not working are in the "unique values" context. All other test works without an error. Thanks
2011/01/04
[ "https://Stackoverflow.com/questions/4599321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210023/" ]
This is exactly the problem I had just run into -- and had a strange experience where this problem didn't seem to happen if I was just running "rake spec". After not finding an obvious answer, I did try something that seems to have solved the problem! It seems like setting a class variable inside a before() block is the culprit, if you're using FactoryGirl. I had something very similar: ``` factory :widget do sequence(:name) { |n| "widget#{n}" } end ``` then: ``` describe Widget do before(:each) { @widget = FactoryGirl.create(:widget) } it ...yadda yadda... @widget.foo() end end ``` autotest would find uniqueness constraint problems. I changed the rspect test to this: ``` describe Widget do let(:widget) { FactoryGirl.create(:widget) } it ...yadda yadda... widget.foo() end end ``` ...and the uniqueness constraint issues went away. Not sure why this happens, and it seems like it *shouldn't* happen, but may be a workable resolution.
I ran into a very similar problem and I tried several of the suggestions on this thread with no luck. I did however fix it with adding the following to my spec\_helper.rb: ``` # Clean up the database require 'database_cleaner' config.before(:suite) do DatabaseCleaner.strategy = :truncation DatabaseCleaner.orm = "mongoid" end config.before(:each) do DatabaseCleaner.clean end ``` Also don't forget to add the DatabaseCleaner gem to your gemfile
4,599,321
i have a problem with Autotest. In my user model are the username & email address unique. When i start Autotest everything works fine. In the secound round, from autotest, i have a > > Validation failed: Email has already been taken, Username has already been taken > > > error in only two test. I dont understand why, i use factorygirl with an sequenze and this should generate everytime a new username. This is my rspec2 file: ``` describe User do specify { Factory.build(:user).should be_valid } context "unique values" do before :all do @user = Factory.create(:user) end it "should have an unique email address" do Factory.build(:user, :email => @user.email).should_not be_valid end it "should have an unique username" do Factory.build(:user, :username => @user.username).should_not be_valid end end context "required attributes" do it "should be invalid without an email address" do Factory.build(:user, :email => nil).should_not be_valid end it "should be invalid without an username" do Factory.build(:user, :username => nil).should_not be_valid end it "should be invalid without an password" do Factory.build(:user, :password => nil).should_not be_valid end it "should be invalid without an address" do Factory.build(:user, :address => nil).should_not be_valid end end end ``` The Factory: ``` Factory.sequence :username do |n| "Outfit#{n}er" end Factory.sequence :email do |n| "user#{n}@example.com" end Factory.define :user do |u| u.username { Factory.next :username } u.email { Factory.next :email } u.password 'secret' u.phone_number '02214565854' u.association :address, :factory => :address end Factory.define :confirmed_user, :parent => :user do |u| u.after_build { |user| user.confirm! } end ``` The only two test that are not working are in the "unique values" context. All other test works without an error. Thanks
2011/01/04
[ "https://Stackoverflow.com/questions/4599321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210023/" ]
I have gotten that problem from having the database not being properly cleared after some tests. If you run: rake db:test:prepare before the autotest, does it still happen? I eventually got around it by isolating which tests were not being cleared and fixing them (or removing them). Sorry, I can't remember what was the problem, but it had some error causing it. Oh, and I ran it without spork, so that I could see my logger messages mixed in with the results. Hope this helps.
I ran into a very similar problem and I tried several of the suggestions on this thread with no luck. I did however fix it with adding the following to my spec\_helper.rb: ``` # Clean up the database require 'database_cleaner' config.before(:suite) do DatabaseCleaner.strategy = :truncation DatabaseCleaner.orm = "mongoid" end config.before(:each) do DatabaseCleaner.clean end ``` Also don't forget to add the DatabaseCleaner gem to your gemfile
2,999,058
Cutting a 1D Line: ``` We can cut a 1D line via 0D point. if we want to cut a 1D line via a 1D line. we have to move 1 dimension up that is in 2D ``` [(Image for 1D Line cut by 0D pt.)](https://i.stack.imgur.com/EE3Fn.png) [(Image for 1D Line cut by 1D line)](https://i.stack.imgur.com/fTzeS.png) Cutting a 2d Plane: ``` We can cut a 2D plane via 1D Line. if we want to cut a 2D plane by a 2D plane we have to move 1 dimension up that is in 2D ``` [(Image for 2D plane cut by 1D line)](https://i.stack.imgur.com/uADHJ.png) [(Image for 2D plane cut by 2D plane)](https://i.stack.imgur.com/oLzbN.png) **Cutting of a 3D Cube:** ``` We can cut a 3D Cube by a 2D Plane So the question arises that Can we cut a 3D cube by a 3D cube? And if yes then how ? For it we may require 1 more dimension (4th dimension). ``` [(Image for 3D Cube cut by 2D Plane)](https://i.stack.imgur.com/dww3b.png) **So how can we do that**! In all the cases sizes doesn't matter: Size of a Line doesn't matter that if we cut a Line by another Line. And Size of a Plane doesn't matter that if we cut a Plane by another Plane. Is it same for Cubes? Does Cubes size also doesn't matter. Can we cut a Cube by another Cube(Like a Plane cuts a Cube) and that another Cube's size can by 10x, 100x, 1000x etc ? I think understanding how a 3D Cube is cut by a 3D cube help me to understand (or say visualize) what 4th Dimension is?
2018/11/15
[ "https://math.stackexchange.com/questions/2999058", "https://math.stackexchange.com", "https://math.stackexchange.com/users/494766/" ]
How are you choosing the $s\_j$? The definition in Stephen Abbott's book allows us to choose the $s\_j$ freely so long as $\Delta\_j<\delta$. Let $P=\{x\_i\}\_1^n$ with $x\_i<x\_{i+1}$ and $\Delta\_i<\delta$ for all $i$. Then if $f$ is bounded on $[x\_i,x\_{i+1}]$, then it is bounded on $[a,b]$, hence if it is unbounded, then there exists $[x\_i,x\_{i+1}]$ such that $f$ is unbounded on $[x\_i,x\_{i+1}]$. Suppose $f$ is unbounded and choose an $i$ such that $f$ is unbounded on $[x\_i,x\_{i+1}]$. For simplicity we assume it is unbounded above (the case for unbounded below is similar). Now fix $s\_j\in[x\_j,x\_{j+1}]$ for all $j\not=i$. Then we can make $$\sum\_{j=1}^nf(s\_j)\Delta\_j$$ as large as we wish by varying $s\_i$. For if $Q>0$, then choose $s\_i$ such that $$f(s\_i)>\dfrac{Q-\sum\_{\substack{j=1\\j\not=i}}^nf(s\_j)\Delta\_j}{\Delta\_i}.$$ Then $$\sum\_{j=1}^nf(s\_j)\Delta\_j>\sum\_{\substack{j=1\\j\not=i}}^nf(s\_j)\Delta\_j+\dfrac{Q-\sum\_{\substack{j=1\\j\not=i}}^nf(s\_j)\Delta\_j}{\Delta\_i}\Delta\_i=Q.$$ This shows for any $\delta$ that there exists no real number $A$ such that for every tagged partition $(P,\{s\_k\})$ with $\Delta\_k<\delta$ we find $\mathcal{R}(f,P)\in(A-\epsilon,A+\epsilon)$. Contrapositively if $f$ is Riemann integrable, then it is bounded.
Assuming $f$ is not bounded we get that for every $K>0$ and every Partition $\mathcal{P}$ of $[a,b]$ we find $x\in [a,b]$ such that for every $\Delta\_j$ of this partition we have $f(x)\cdot \Delta\_j>K$ so $f$ is not Riemann integrable. So we conclude that if $f$ is Riemann integrable, it is bounded. That should be all you need to show.
41,759
To express "lengthen an essay", should I write "*prolonger la composition*" or "*allonger la composition*"? I found in the dictionary saying these two words both means to lengthen. My question is "Elle a essayé de/d' \_\_\_\_\_\_\_\_ son article", given the options to fill in the blank are A prolonger B longer C allonger D accroître. Thank you so much for your help :)
2020/04/18
[ "https://french.stackexchange.com/questions/41759", "https://french.stackexchange.com", "https://french.stackexchange.com/users/22658/" ]
Bonjour Claire, "prolonger" est à prendre au sens *"étendre"* dans la durée **(lié au temps)**, par exemple "je *prolonge la durée* du confinement". *"Allonger"* est plus à prendre au **sens physique** ou au **sens spatial (ajouter de la longueur)** : "je m'allonge sur mon lit". Bien entendu, il existe des exceptions. Dans le cas de votre composition, je dirai plutôt (au choix) : * "poursuivre la composition" * "continuer la composition" * "prolonger la composition" Vous pouvez écrire la phrase qui vous pose problème ici si vous le voulez, je me ferai un plaisir de vous accorder de l'aide supplémentaire. Bonne journée.
If what you mean is that she padded her essay with less relevant stuff to make it longer, then *allonger* is perfect. It is used in cooking, where *allonger une sauce* means to dilute it with water. It can be used figuratively for productions of the mind such as an essay or an article and it would be understood as a slight criticism. Otherwise, a neutral way of expressing the idea would be *rallonger l'article*.
41,759
To express "lengthen an essay", should I write "*prolonger la composition*" or "*allonger la composition*"? I found in the dictionary saying these two words both means to lengthen. My question is "Elle a essayé de/d' \_\_\_\_\_\_\_\_ son article", given the options to fill in the blank are A prolonger B longer C allonger D accroître. Thank you so much for your help :)
2020/04/18
[ "https://french.stackexchange.com/questions/41759", "https://french.stackexchange.com", "https://french.stackexchange.com/users/22658/" ]
To express "lengthen an essay", I would personally use "rallonger la composition". According to [Larousse definition](https://www.larousse.fr/dictionnaires/francais/rallonger/66321): > > Accroître la longueur de quelque chose : *Rallonger un article de quelques lignes*. > > > It is a very close synonym of "allonger" (and nowadays, I think you can use both as you wish), but it expresses the idea of adding something. The definition I linked above states: > > Allonger = rendre plus long ou faire paraître plus long. > > > Rallonger = rendre plus long **en ajoutant quelque chose**. > > > But it's a subtle difference. Back to your question. **What is the difference between *allonger* and *prolonger*?** Most of the times, "prolonger" is used to express lenghtening something **in time**, or for an existing **line** (road, train line, etc). > > *Suite à ses performances, nous avons décidé de prolonger sa période d'essai.* > > > *Grâce aux récents travaux, la route a été prolongée jusqu'à la ville voisine.* > > > I would use "allonger" when I'm talking about something more abstract. **Please note** that "allonger" also has other meanings, the main ones being: * To lay someone down: *J'ai allongé la victime par terre pour qu'elle se sente mieux.* * To extend / stretch a body part: *J'ai besoin d'allonger le bras pour atteindre cette boîte dans mon placard.* All the meanings are listed in the [Larousse definition](https://www.larousse.fr/dictionnaires/francais/allonger/2416) for "allonger".
If what you mean is that she padded her essay with less relevant stuff to make it longer, then *allonger* is perfect. It is used in cooking, where *allonger une sauce* means to dilute it with water. It can be used figuratively for productions of the mind such as an essay or an article and it would be understood as a slight criticism. Otherwise, a neutral way of expressing the idea would be *rallonger l'article*.
41,759
To express "lengthen an essay", should I write "*prolonger la composition*" or "*allonger la composition*"? I found in the dictionary saying these two words both means to lengthen. My question is "Elle a essayé de/d' \_\_\_\_\_\_\_\_ son article", given the options to fill in the blank are A prolonger B longer C allonger D accroître. Thank you so much for your help :)
2020/04/18
[ "https://french.stackexchange.com/questions/41759", "https://french.stackexchange.com", "https://french.stackexchange.com/users/22658/" ]
*Prolonger* is more like to append something at the end of an existing object while *allonger* can also mean to stretch something to increase its length. Both *prolonger* and *allonger* are then possible among the four suggested choices but for an essay, I'd rather write : > > *Elle a essayé d'étoffer son article.* (add more substance to it) > > >
If what you mean is that she padded her essay with less relevant stuff to make it longer, then *allonger* is perfect. It is used in cooking, where *allonger une sauce* means to dilute it with water. It can be used figuratively for productions of the mind such as an essay or an article and it would be understood as a slight criticism. Otherwise, a neutral way of expressing the idea would be *rallonger l'article*.
164,128
Would you be kind enough to explain the nuance between "pitiful" and "pitiable"? My Oxford Advanced Learner's Dictionary shows two similar meanings for the aforementioned words. 1. deserving pity or causing you to feel pity. 2. not deserving respect I am confused as to why there are two different adjectives with almost the similar meaning and examples.
2014/04/16
[ "https://english.stackexchange.com/questions/164128", "https://english.stackexchange.com", "https://english.stackexchange.com/users/70234/" ]
I'd say that pitiful might be either of those two definitions (you use context to know which is being used), but pitiable is only the first. A coach might tell his team "Your guys on defense were pitiful today". He's telling them that they did a bad job. But you would never use pitiable there.
I would distinguish them as **Pitiable** is something evocative of pity or sympathy, but not necessarily in a bad condition **Pitiful** is something deserving of pity, and disadvantaged in some way Consider a cute kitten giving an imploring look in a picture - she is **pitiable** and you mentally go 'aww, what a cute & weak creature, let me fuss over it!' even though its perfectly fine and not *pitiful*. Now consider a thief or molestor who got beaten to a pulp by a crowd. He's in a **pitiful** condition with multiple fractures, but your initial response might be vindication rather than sympathy; he's not *pitiable*.
66,603,998
``` drinks = 5 if drinks <= 2: print("Keep going buddy") elif drinks == 3: print("I believe you've had enough, sir") else: print("stop") ``` This was the code I was trying to run, and it keeps giving me a syntax error with the "else" and I don't know why.
2021/03/12
[ "https://Stackoverflow.com/questions/66603998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15384124/" ]
Your syntax is wrong. Remove the space before the `else:`
The syntax of your code is labeled as incorrect because an `else` statement and clause cannot exist without an `if` statement and clause preceding it. Since you have an `else` statement alone inside an `elif` clause, an error is thrown. Likely this is just an issue with your indentation, which you need to be very careful about, since Python emphasizes whitespace. Here is the code I believe you meant to type: ```py drinks = 5 if drinks <= 2: print("Keep going buddy") elif drinks == 3: print("I believe you've had enough, sir") else: print("stop") ```
33,596,145
In a bash script I need to compare the first char of two Strings. To do this, I use the `head` operator like this: ``` var1="foo" var2="doo" headVar1=$(head -c1 $var1) headVar2=$(head -c1 $var2) if [ $headVar1 == $headVar2 ] then #miau fi ``` But the console says "head: cant open foo for reading: Doesnt exist the file or directorie" And the same with doo Some help? Thanks.
2015/11/08
[ "https://Stackoverflow.com/questions/33596145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1886172/" ]
`head` interpreted `foo` as a filename. See `man head` on what options are available for the command. To store command output in a variable, use command substitution: ``` headVar1=$(printf %s "$var1" | head -c1) ``` which could be shortened using a "here string": ``` headVar1=$(head -c1 <<< "$var1") ``` But parameter expansion is much faster in this case, as it doesn't spawn a subshell: ``` headVar1=${var1:0:1} ```
Your code must be, ``` var1="foo" var2="doo" headVar1=$(head -c1 <<<"$var1") headVar2=$(head -c1 <<<"$var2") if [[ "$headVar1" == "$headVar2" ]] then echo "It's same" else echo "Not same" fi ``` * remove the space which exists next to equal sign (*variable assignment part*). * Use `<<<` to fed input from a variable to the corresponding function. * Variable names must be preceded by the dollar `$` symbol.
33,596,145
In a bash script I need to compare the first char of two Strings. To do this, I use the `head` operator like this: ``` var1="foo" var2="doo" headVar1=$(head -c1 $var1) headVar2=$(head -c1 $var2) if [ $headVar1 == $headVar2 ] then #miau fi ``` But the console says "head: cant open foo for reading: Doesnt exist the file or directorie" And the same with doo Some help? Thanks.
2015/11/08
[ "https://Stackoverflow.com/questions/33596145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1886172/" ]
Your code must be, ``` var1="foo" var2="doo" headVar1=$(head -c1 <<<"$var1") headVar2=$(head -c1 <<<"$var2") if [[ "$headVar1" == "$headVar2" ]] then echo "It's same" else echo "Not same" fi ``` * remove the space which exists next to equal sign (*variable assignment part*). * Use `<<<` to fed input from a variable to the corresponding function. * Variable names must be preceded by the dollar `$` symbol.
A circuitous, but POSIX-compatible, solution: ``` var1="foo" var2="doo" headVar1=${var1%${var1#?}} headVar2=${var2%${var2#?}} if [ "$headVar1" = "$headVar2" ] then #miau fi ``` `${var1#?}` expands to the value of `var1` minus its first character. That is used as the *suffix* to remove with `${var1%...}`, leaving in the end just the first character of `var1`.
33,596,145
In a bash script I need to compare the first char of two Strings. To do this, I use the `head` operator like this: ``` var1="foo" var2="doo" headVar1=$(head -c1 $var1) headVar2=$(head -c1 $var2) if [ $headVar1 == $headVar2 ] then #miau fi ``` But the console says "head: cant open foo for reading: Doesnt exist the file or directorie" And the same with doo Some help? Thanks.
2015/11/08
[ "https://Stackoverflow.com/questions/33596145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1886172/" ]
`head` interpreted `foo` as a filename. See `man head` on what options are available for the command. To store command output in a variable, use command substitution: ``` headVar1=$(printf %s "$var1" | head -c1) ``` which could be shortened using a "here string": ``` headVar1=$(head -c1 <<< "$var1") ``` But parameter expansion is much faster in this case, as it doesn't spawn a subshell: ``` headVar1=${var1:0:1} ```
A circuitous, but POSIX-compatible, solution: ``` var1="foo" var2="doo" headVar1=${var1%${var1#?}} headVar2=${var2%${var2#?}} if [ "$headVar1" = "$headVar2" ] then #miau fi ``` `${var1#?}` expands to the value of `var1` minus its first character. That is used as the *suffix* to remove with `${var1%...}`, leaving in the end just the first character of `var1`.
65,036,643
There is a page where you can see the details of a user's loan. There is a decorator where I return values ​​using the get () method. In general, there is a partial refund, which returns items of partial payments as shown in the photo. My problem is that I cannot specify all partial payments, only receive one by one. Loan Details component: ``` <div className="ClientLoanDetails__card__content__inner__wrapper"> {Object.keys(payments[0]).map(val => { { [payments[0][val]].map((payment: any, index: number) => ( <div className="ClientLoanDetails__card__content-inner" key={index}> {paymentsFields.map((item, indexInner) => ( <div className="ClientLoanDetails__card__content-item" key={indexInner}> <div className="ClientLoanDetails__card__content-item__title"> {item.title} </div> <div className="ClientLoanDetails__card__content-item__value"> {payment[item.key]} </div> </div> ))} </div> )); }} ) }} </div> ``` This is code snippet for key & titles from loan.ts: ``` export const repaymentsFields = [ { key: 'issuedDate', title: lang.CLIENTS.REPAYMENTS.ISSUED_DATE, }, { key: 'period', title: lang.CLIENTS.REPAYMENTS.PERIOD_IN_DAYS, }, ] ``` JSON of repayments: ``` "partialRepayments": [ { "orderId": "A11Fz090VT1BmObJ0S-0", "repaidPrincipalAmount": { "amount": 250000.0 }, "repaidInterestAmount": { "amount": 0 }, "repaidOverdueAmount": { "amount": 0 }, "repaidProlongationAmount": { "amount": 0 }, "started": "2020-11-09T16:52:08.981+0600", "completed": "2020-11-09T16:52:21.170+0600", "period": 25, "timestamp": "2020-11-09T16:52:21.174+0600" }, { "orderId": "A11Fz090VT1BmObJ0S-1", "repaidPrincipalAmount": { "amount": 300000.0 }, "repaidInterestAmount": { "amount": 0 }, "repaidOverdueAmount": { "amount": 0 }, "repaidProlongationAmount": { "amount": 0 }, "started": "2020-11-09T16:54:31.923+0600", "completed": "2020-11-09T16:54:46.313+0600", "period": 25, "timestamp": "2020-11-09T16:54:46.317+0600" } ], ``` the problem is that it is impossible to display the values ​​that come as in the photo (one loan may have several repayments) I have to return all values from an Object [IMAGE of console](https://i.stack.imgur.com/hQS1R.png)
2020/11/27
[ "https://Stackoverflow.com/questions/65036643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14719180/" ]
For starters the argument of malloc is confusing ``` arr = malloc(sizeof(arr[SIZE]) * 10); ``` It seems you mean ``` arr = malloc(sizeof( *arr ) * 10); ``` That is you are trying to allocate dynamically an array of the type `int[10][SIZE]`. More precisely the record used as an argument in the call of malloc ``` arr = malloc(sizeof(arr[SIZE]) * 10); ``` is correct but very confusing. It is better not to use such a record for the `sizeof` operator. The function declaration can look like ``` int ( *allocation( size_t n ) )[SIZE]; ``` Or you can introduce a typedef name like ``` typedef int ( *Array2D )[SIZE]; ``` and then declare the function like ``` Array2D allocation( size_t n ); ``` where `n` corresponds to the used by you value 10. That is using the parameter you can specify any number for the array dimension apart from 10.
The allocation size `sizeof(arr[SIZE]) * 10` is incorrect but will evaluate to the expected size by coincidence. It should be `sizeof(*arr) * 10`, meaning 10 times the size of whatever `arr` points to, in this case arrays of `SIZE` `int`. You can encapsulate this allocation in a function this way: ``` int (*allocate2D(size_t n))[SIZE] { int (*arr)[SIZE] = malloc(sizeof(*arr) * n); return arr; } ``` Or better: ``` int (*allocate2D(size_t n))[SIZE] { return calloc(sizeof(int[SIZE]), n); } ```
35,769,134
**CONTEXT** The code is supposed to get a file object and extract information from it using awk. It uses readlines() with 'pieceSize' as an argument. 'pieceSize' is the number of MBs I want readlines() to work with as it goes through the file. I did this with hopes that my program wont run into trouble if the file that needs to be read is much greater than my computer's memory. The file being read has many rows and columns. The code below is trying to read the first field from the first line using awk. ``` import os from subprocess import Popen, PIPE, STDOUT def extract_info(file_object): pieceSize = 16777216 # 16MB for line in file_object.readlines(pieceSize): eachline = line.rsplit() # removing extra returns p = Popen(['awk','{{print `$`1}}'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) pOut = p.communicate(input=eachline)[0] print(pOut.decode()) ``` **THE ERROR MESSAGE** The error I receive reads something like ... ``` ... in _communicate_with_poll(self, input) chunk = input[input_offset : input_offset + _PIPE_BUF] try: -> input_offset += os.write(fd, chunk) except OSError as e: if e.errno == errno.EPIPE: TypeError: must be string or buffer, not list ```
2016/03/03
[ "https://Stackoverflow.com/questions/35769134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6012406/" ]
The error occurs because `str.rsplit()` returns a *list*, but `Popen.communicate()` expects a string (or buffer). So you can't pass the result of `eachline` to `communicate()`. That's the cause of the problem, but I'm not sure why you are splitting the lines. `rsplit()` will split on *all* whitespace, that includes spaces, tabs etc. Is that really what you want? Also, this code will iterate over the first set of lines returned by `readlines()`. The rest of the file remains unprocessed. You need an outer loop to keep things going until the input file is exhausted (possibly there is in the calling code that you don't show?). And then it is calling `Popen` once for every line of input which is going to be very inefficient. I suggest that you handle the processing entirely in Python. `line.split()[0]` is effectively giving you the data that you need (the first column of the file) without passing it to awk. Iterating line-by-line is memory efficient. Perhaps a generator is a better solution: ``` def extract_info(file_object): for line in file_object: yield line.split()[0] ``` Then you can iterate over it in the calling code: ``` with open('inputfile') as f: for first_field in extract_info(f): print first_field ```
You need to pass a string inside the list returned from split to input: ``` pOut, _ = p.communicate(input=eachline[0]) ``` You are passing `line.rsplit()` i.e a list, not sure what you want to pass exactly, maybe you want `input=" ".join(eachline)` but whatever it is, it should be a string not the list itself you pass to input. Also your awk syntax seems to be incorrect. You can also iterate over the file object itself to go line by line avoiding readlines altogether. ``` for line in file_object: ``` So the whole code would be something like: ``` def extract_info(file_object): for line in file_object: eachline = line.rsplit() # removing extra returns p = Popen(['awk','{print $1}'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) pOut,_ = p.communicate(input=" ".join(eachline)) print(pOut.decode()) ``` Obviously fixing the `eachline` logic to do whatever it is you expect it to do. On another note there is no need to use awk at all, you can do all this with python. ``` def extract_info(file_object): for line in file_object: eachline = line.split(None, 1) print(eachline[0]) ``` Or even more succinctly with map and extended iterable unpacking for python3: ``` def extract_info(file_object): for i, *_ in map(str.split, file_object): print(i) ```
35,769,134
**CONTEXT** The code is supposed to get a file object and extract information from it using awk. It uses readlines() with 'pieceSize' as an argument. 'pieceSize' is the number of MBs I want readlines() to work with as it goes through the file. I did this with hopes that my program wont run into trouble if the file that needs to be read is much greater than my computer's memory. The file being read has many rows and columns. The code below is trying to read the first field from the first line using awk. ``` import os from subprocess import Popen, PIPE, STDOUT def extract_info(file_object): pieceSize = 16777216 # 16MB for line in file_object.readlines(pieceSize): eachline = line.rsplit() # removing extra returns p = Popen(['awk','{{print `$`1}}'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) pOut = p.communicate(input=eachline)[0] print(pOut.decode()) ``` **THE ERROR MESSAGE** The error I receive reads something like ... ``` ... in _communicate_with_poll(self, input) chunk = input[input_offset : input_offset + _PIPE_BUF] try: -> input_offset += os.write(fd, chunk) except OSError as e: if e.errno == errno.EPIPE: TypeError: must be string or buffer, not list ```
2016/03/03
[ "https://Stackoverflow.com/questions/35769134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6012406/" ]
The error occurs because `str.rsplit()` returns a *list*, but `Popen.communicate()` expects a string (or buffer). So you can't pass the result of `eachline` to `communicate()`. That's the cause of the problem, but I'm not sure why you are splitting the lines. `rsplit()` will split on *all* whitespace, that includes spaces, tabs etc. Is that really what you want? Also, this code will iterate over the first set of lines returned by `readlines()`. The rest of the file remains unprocessed. You need an outer loop to keep things going until the input file is exhausted (possibly there is in the calling code that you don't show?). And then it is calling `Popen` once for every line of input which is going to be very inefficient. I suggest that you handle the processing entirely in Python. `line.split()[0]` is effectively giving you the data that you need (the first column of the file) without passing it to awk. Iterating line-by-line is memory efficient. Perhaps a generator is a better solution: ``` def extract_info(file_object): for line in file_object: yield line.split()[0] ``` Then you can iterate over it in the calling code: ``` with open('inputfile') as f: for first_field in extract_info(f): print first_field ```
It's not fully clear what output you are expecting to achieve. However, maybe this will be helpful: * Why use `awk` if all you are doing is print the first word in a line, you can use python for that. * If you would like to read a file with size larger than your memory, you can load each line using `readline` or `for line in file_handler`, you should avoid using `readlines()` and `read()` which load the entire file. Try this: ``` with open('myfile.txt') as f: for line in f: first_word = line.split()[0] ```
50,318,309
I use Python 2.7. I'm trying to run my UI-automation script, but I got ImportError. I have at least 30 Classes with methods. I want to have these methods in each and any class that's why I created BaseClass(MainClass) and created objects of all my classes. Please advise what should I do in this case or how I can solve this problem. Here the example what similar to my code. test\_class/baseclass.py ``` from test_class.first_class import FirstClass from test_class.second_class import SecondClass class MainClass: def __init__(self): self.firstclass = FirstClass() self.secondclass = SecondClass() ``` test\_class/first\_class.py ``` from test_class.baseclass import MainClass class FirstClass(MainClass): def __init__(self): MainClass.__init__(self) def add_two_number(self): return 2 + 2 ``` test\_class/second\_class.py ``` from test_class.baseclass import MainClass class SecondClass(MainClass): def __init__(self): MainClass.__init__(self) def minus_number(self): return self.firstclass.add_two_number() - 10 if __name__ == '__main__': print(SecondClass().minus_number()) ``` When I run the last file I get this error ``` Traceback (most recent call last): File "/Users/nik-edcast/git/ui-automation/test_class/second_class.py", line 1, in <module> from test_class.baseclass import MainClass File "/Users/nik-edcast/git/ui-automation/test_class/baseclass.py", line 1, in <module> from test_class.first_class import FirstClass File "/Users/nik-edcast/git/ui-automation/test_class/first_class.py", line 1, in <module> from test_class.baseclass import MainClass ImportError: cannot import name MainClass ```
2018/05/13
[ "https://Stackoverflow.com/questions/50318309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687066/" ]
check this line: from test\_class.baseclass import MainClass -> it seems like all other imports had a '\_' between the names like second\_class. So try maybe to write base\_class. who knows might work
Are you proabably running your code like `python test_class/second_class.py`. If you just do this then python will think the base directory to find modules is `./test_class`. So when you import the `test_class` package python will start looking for a folder called `./test_class/test_class` to find the sub-modules. This directory doesn't exist and so the import fails. There are several ways that you can tell python how to correctly find your modules. Using `PYTHONPATH` ------------------ One way to get around this is to set `PYTHONPATH` before starting python. This is just an environment variable with which you can tell python where to look for your modules. eg. ``` export PYTHONPATH=/path/to/your/root/folder python test_class/second_class.py ``` Using the `-m` switch for python -------------------------------- Be default python treats the directory of the main module as the place to look for other modules. However, if you use `-m` python will fall back to looking in the current directory. But you also need to specify the full name of the module you want to run (rather than as a file). eg. ``` python -m test_class.second_class ``` Writing a root entry point -------------------------- In this we just define your main module at the base level (the directory that contains `test_class`. Python will treat this folder as the place to look for user modules and will find everything appropriately. eg. ### main.py (in `/path/to/your/root/folder`) ``` from test_class.second_class import SecondClass if __name__ == '__main__': print(SecondClass().minus_number()) ``` ### at the command line ``` python main.py ```
50,318,309
I use Python 2.7. I'm trying to run my UI-automation script, but I got ImportError. I have at least 30 Classes with methods. I want to have these methods in each and any class that's why I created BaseClass(MainClass) and created objects of all my classes. Please advise what should I do in this case or how I can solve this problem. Here the example what similar to my code. test\_class/baseclass.py ``` from test_class.first_class import FirstClass from test_class.second_class import SecondClass class MainClass: def __init__(self): self.firstclass = FirstClass() self.secondclass = SecondClass() ``` test\_class/first\_class.py ``` from test_class.baseclass import MainClass class FirstClass(MainClass): def __init__(self): MainClass.__init__(self) def add_two_number(self): return 2 + 2 ``` test\_class/second\_class.py ``` from test_class.baseclass import MainClass class SecondClass(MainClass): def __init__(self): MainClass.__init__(self) def minus_number(self): return self.firstclass.add_two_number() - 10 if __name__ == '__main__': print(SecondClass().minus_number()) ``` When I run the last file I get this error ``` Traceback (most recent call last): File "/Users/nik-edcast/git/ui-automation/test_class/second_class.py", line 1, in <module> from test_class.baseclass import MainClass File "/Users/nik-edcast/git/ui-automation/test_class/baseclass.py", line 1, in <module> from test_class.first_class import FirstClass File "/Users/nik-edcast/git/ui-automation/test_class/first_class.py", line 1, in <module> from test_class.baseclass import MainClass ImportError: cannot import name MainClass ```
2018/05/13
[ "https://Stackoverflow.com/questions/50318309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8687066/" ]
check this line: from test\_class.baseclass import MainClass -> it seems like all other imports had a '\_' between the names like second\_class. So try maybe to write base\_class. who knows might work
You could try importing the full files instead of using from file import class. Then you would only need to add the file name before referencing something from another file.
1,710,070
I know that the solution to the differential equation $\frac{dy}{dt}=y(a-by), a>0, b>0, y(0)=y\_0$ can be derived using integration using partial fractions, and the final result is: $$y=a/(b+ke^{-at})$$ where $k$ is $(a/y\_0)-b$. My doubt is: Say $y\_0<0$. Then the differential equation itself tells me that $\frac{dy}{dt}<0$ and hence $y$ would just go on falling as $t$ increases, and it would always remain negative. But if you look at the behaviour of the function $y$, there would be a vertical asymptote at some positive value of $t$ (to be precise, where $b+ke^{-at}=0$. Beyond this value of $t$, $y$ would be positive. What am I getting wrong here?
2016/03/23
[ "https://math.stackexchange.com/questions/1710070", "https://math.stackexchange.com", "https://math.stackexchange.com/users/325288/" ]
You got nothing wrong, it is just that the solution ends at the asymptote. Solutions of differential equations are defined over intervals containing the initial point. These intervals can have finite end points even for the so-called "maximal solution". Often these finite end points happen because the trajectory of the solution moves to infinity in finite time, as happens here.
It is a classical differential equation called the **logistic differential equation** <http://math.usu.edu/~powell/biomath/mlab3-02/node2.html>
72,436,803
After in my Laravel 9 project I run `composer update` I faced this error message: ``` Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 0 installs, 1 update, 1 removal - Downloading fruitcake/laravel-cors (v3.0.0) - Removing asm89/stack-cors (v2.1.1) - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive 77 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi In Finder.php line 588: syntax error, unexpected token ")" Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 ``` It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`. I checked this file and it's looks correct. When I open my project in browser I get this error: ``` Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334 Stack trace: #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array) #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException)) #4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError)) #6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError)) #7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError)) #8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #9 {main} thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334 ``` I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too. I use PHP version 8.0.16. Composer version 2.0.12 2021-04-01 10:14:59. Any idea how can I fix this?
2022/05/30
[ "https://Stackoverflow.com/questions/72436803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972828/" ]
I found a soution: 1. upgrade to PHP 8.1 2. run `docker pull composer` to upgrade latest version of composer (from 2.0 to 2.2) 3. run `composer update` in Docker container
I did : ``` composer require --ignore-platform-reqs symfony/finder 6.1 ``` and i have a similar issue now : ``` [2022-05-30 17:52:03] laravel.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token \")\" at /vendor/symfony/finder/Finder.php:588) [stacktrace] #0 /vendor/composer/ClassLoader.php(346): Composer\\Autoload\\includeFile() #1 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(88): Composer\\Autoload\\ClassLoader->loadClass() #2 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(65): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->getConfigurationFiles() #3 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(39): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->loadConfigurationFiles() #4 /vendor/laravel/framework/src/Illuminate/Foundation/Application.php(239): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->bootstrap() #5 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(310): Illuminate\\Foundation\\Application->bootstrapWith() #6 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(127): Illuminate\\Foundation\\Console\\Kernel->bootstrap() #7 /artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle() #8 {main} "} ``` So i think it's the version of symfony/finder that is not compatible with php 8.0, try to downgrade any symfony related package to 6.0.x, because i don't think you require symfony/finder directly, but some other package like symfony/http-client I think you perhaps installed dependencies using php 8.1 at some point and you got wrong packages versions, or perhaps you have laravel 10 installed and not laravel 9 ?
72,436,803
After in my Laravel 9 project I run `composer update` I faced this error message: ``` Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 0 installs, 1 update, 1 removal - Downloading fruitcake/laravel-cors (v3.0.0) - Removing asm89/stack-cors (v2.1.1) - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive 77 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi In Finder.php line 588: syntax error, unexpected token ")" Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 ``` It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`. I checked this file and it's looks correct. When I open my project in browser I get this error: ``` Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334 Stack trace: #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array) #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException)) #4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError)) #6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError)) #7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError)) #8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #9 {main} thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334 ``` I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too. I use PHP version 8.0.16. Composer version 2.0.12 2021-04-01 10:14:59. Any idea how can I fix this?
2022/05/30
[ "https://Stackoverflow.com/questions/72436803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972828/" ]
To continue using php 8.0 add these entries to your composer.json ``` "require": { ... "symfony/console": "6.0.*", "symfony/error-handler": "6.0.*", "symfony/finder": "6.0.*", "symfony/http-foundation": "6.0.*", "symfony/http-kernel": "6.0.*", "symfony/mailer": "6.0.*", "symfony/mime": "6.0.*", "symfony/process": "6.0.*", "symfony/routing": "6.0.*", "symfony/var-dumper": "6.0.*", "symfony/event-dispatcher": "6.0.*", "symfony/string": "6.0.*", "symfony/translation": "6.0.*", "symfony/translation-contracts": "3.0.*", "symfony/service-contracts": "3.0.*", "symfony/event-dispatcher-contracts": "3.0.*", "symfony/deprecation-contracts": "3.0.*", ... } ``` Worked for me with php 8.0 and Laravel 9.
I did : ``` composer require --ignore-platform-reqs symfony/finder 6.1 ``` and i have a similar issue now : ``` [2022-05-30 17:52:03] laravel.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token \")\" at /vendor/symfony/finder/Finder.php:588) [stacktrace] #0 /vendor/composer/ClassLoader.php(346): Composer\\Autoload\\includeFile() #1 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(88): Composer\\Autoload\\ClassLoader->loadClass() #2 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(65): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->getConfigurationFiles() #3 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(39): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->loadConfigurationFiles() #4 /vendor/laravel/framework/src/Illuminate/Foundation/Application.php(239): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->bootstrap() #5 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(310): Illuminate\\Foundation\\Application->bootstrapWith() #6 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(127): Illuminate\\Foundation\\Console\\Kernel->bootstrap() #7 /artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle() #8 {main} "} ``` So i think it's the version of symfony/finder that is not compatible with php 8.0, try to downgrade any symfony related package to 6.0.x, because i don't think you require symfony/finder directly, but some other package like symfony/http-client I think you perhaps installed dependencies using php 8.1 at some point and you got wrong packages versions, or perhaps you have laravel 10 installed and not laravel 9 ?
72,436,803
After in my Laravel 9 project I run `composer update` I faced this error message: ``` Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 0 installs, 1 update, 1 removal - Downloading fruitcake/laravel-cors (v3.0.0) - Removing asm89/stack-cors (v2.1.1) - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive 77 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi In Finder.php line 588: syntax error, unexpected token ")" Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 ``` It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`. I checked this file and it's looks correct. When I open my project in browser I get this error: ``` Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334 Stack trace: #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array) #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException)) #4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError)) #6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError)) #7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError)) #8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #9 {main} thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334 ``` I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too. I use PHP version 8.0.16. Composer version 2.0.12 2021-04-01 10:14:59. Any idea how can I fix this?
2022/05/30
[ "https://Stackoverflow.com/questions/72436803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972828/" ]
I did : ``` composer require --ignore-platform-reqs symfony/finder 6.1 ``` and i have a similar issue now : ``` [2022-05-30 17:52:03] laravel.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token \")\" at /vendor/symfony/finder/Finder.php:588) [stacktrace] #0 /vendor/composer/ClassLoader.php(346): Composer\\Autoload\\includeFile() #1 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(88): Composer\\Autoload\\ClassLoader->loadClass() #2 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(65): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->getConfigurationFiles() #3 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(39): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->loadConfigurationFiles() #4 /vendor/laravel/framework/src/Illuminate/Foundation/Application.php(239): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->bootstrap() #5 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(310): Illuminate\\Foundation\\Application->bootstrapWith() #6 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(127): Illuminate\\Foundation\\Console\\Kernel->bootstrap() #7 /artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle() #8 {main} "} ``` So i think it's the version of symfony/finder that is not compatible with php 8.0, try to downgrade any symfony related package to 6.0.x, because i don't think you require symfony/finder directly, but some other package like symfony/http-client I think you perhaps installed dependencies using php 8.1 at some point and you got wrong packages versions, or perhaps you have laravel 10 installed and not laravel 9 ?
Upgrading your PHP version to `PHP 8.1` should solve the problem. And just make sure to run `composer install` or `composer update` again
72,436,803
After in my Laravel 9 project I run `composer update` I faced this error message: ``` Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 0 installs, 1 update, 1 removal - Downloading fruitcake/laravel-cors (v3.0.0) - Removing asm89/stack-cors (v2.1.1) - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive 77 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi In Finder.php line 588: syntax error, unexpected token ")" Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 ``` It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`. I checked this file and it's looks correct. When I open my project in browser I get this error: ``` Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334 Stack trace: #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array) #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException)) #4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError)) #6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError)) #7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError)) #8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #9 {main} thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334 ``` I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too. I use PHP version 8.0.16. Composer version 2.0.12 2021-04-01 10:14:59. Any idea how can I fix this?
2022/05/30
[ "https://Stackoverflow.com/questions/72436803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972828/" ]
To continue using php 8.0 add these entries to your composer.json ``` "require": { ... "symfony/console": "6.0.*", "symfony/error-handler": "6.0.*", "symfony/finder": "6.0.*", "symfony/http-foundation": "6.0.*", "symfony/http-kernel": "6.0.*", "symfony/mailer": "6.0.*", "symfony/mime": "6.0.*", "symfony/process": "6.0.*", "symfony/routing": "6.0.*", "symfony/var-dumper": "6.0.*", "symfony/event-dispatcher": "6.0.*", "symfony/string": "6.0.*", "symfony/translation": "6.0.*", "symfony/translation-contracts": "3.0.*", "symfony/service-contracts": "3.0.*", "symfony/event-dispatcher-contracts": "3.0.*", "symfony/deprecation-contracts": "3.0.*", ... } ``` Worked for me with php 8.0 and Laravel 9.
I found a soution: 1. upgrade to PHP 8.1 2. run `docker pull composer` to upgrade latest version of composer (from 2.0 to 2.2) 3. run `composer update` in Docker container
72,436,803
After in my Laravel 9 project I run `composer update` I faced this error message: ``` Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 0 installs, 1 update, 1 removal - Downloading fruitcake/laravel-cors (v3.0.0) - Removing asm89/stack-cors (v2.1.1) - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive 77 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi In Finder.php line 588: syntax error, unexpected token ")" Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 ``` It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`. I checked this file and it's looks correct. When I open my project in browser I get this error: ``` Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334 Stack trace: #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array) #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException)) #4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError)) #6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError)) #7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError)) #8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #9 {main} thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334 ``` I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too. I use PHP version 8.0.16. Composer version 2.0.12 2021-04-01 10:14:59. Any idea how can I fix this?
2022/05/30
[ "https://Stackoverflow.com/questions/72436803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972828/" ]
I found a soution: 1. upgrade to PHP 8.1 2. run `docker pull composer` to upgrade latest version of composer (from 2.0 to 2.2) 3. run `composer update` in Docker container
Upgrading your PHP version to `PHP 8.1` should solve the problem. And just make sure to run `composer install` or `composer update` again
72,436,803
After in my Laravel 9 project I run `composer update` I faced this error message: ``` Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 0 installs, 1 update, 1 removal - Downloading fruitcake/laravel-cors (v3.0.0) - Removing asm89/stack-cors (v2.1.1) - Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive 77 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi In Finder.php line 588: syntax error, unexpected token ")" Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 ``` It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`. I checked this file and it's looks correct. When I open my project in browser I get this error: ``` Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334 Stack trace: #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array) #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException)) #4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError)) #6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError)) #7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError)) #8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #9 {main} thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334 ``` I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too. I use PHP version 8.0.16. Composer version 2.0.12 2021-04-01 10:14:59. Any idea how can I fix this?
2022/05/30
[ "https://Stackoverflow.com/questions/72436803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972828/" ]
To continue using php 8.0 add these entries to your composer.json ``` "require": { ... "symfony/console": "6.0.*", "symfony/error-handler": "6.0.*", "symfony/finder": "6.0.*", "symfony/http-foundation": "6.0.*", "symfony/http-kernel": "6.0.*", "symfony/mailer": "6.0.*", "symfony/mime": "6.0.*", "symfony/process": "6.0.*", "symfony/routing": "6.0.*", "symfony/var-dumper": "6.0.*", "symfony/event-dispatcher": "6.0.*", "symfony/string": "6.0.*", "symfony/translation": "6.0.*", "symfony/translation-contracts": "3.0.*", "symfony/service-contracts": "3.0.*", "symfony/event-dispatcher-contracts": "3.0.*", "symfony/deprecation-contracts": "3.0.*", ... } ``` Worked for me with php 8.0 and Laravel 9.
Upgrading your PHP version to `PHP 8.1` should solve the problem. And just make sure to run `composer install` or `composer update` again
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Stop Making Excuses ------------------- > > "I have six [to] eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise." > > > Either you have a serious medical issue or I call bullshit. I bet the reason you're not getting results is that you *"have [never] been satisfied with results from any workout program or routine over any period of time".* You try something halfheartedly for a little while, then stop, right? You just lift what you feel like and then go home? [That's not going to work.](http://www.t-nation.com/free_online_article/most_recent/the_biggest_training_fallacy_of_all&cr=) If you think you have a serious medical issue then see a doctor about your health, particularly any possible hormone issues. Stop making up reasons not to see a medical professional. Address your problem head-on. Lift, Eat, Repeat ----------------- You must [lift and eat](https://fitness.stackexchange.com/a/6836/1771) if you want to be big and strong. You must work hard. You must be consistent. There is no other way. There are no excuses. There are no alternative methods. Buck up and be serious about your training. Stop being concerned about other people's success and focus on your own progress. You know nothing about what they do. What they do has nothing to do with your own success or failure. Stop distracting yourself with fantasies about other people's supposedly quick and easy results and focus on working out hard and consistently. Follow a Program ---------------- *Originally I asked the OP to detail their workouts. ("If you want help on how to make your workouts effective, describe what you've been doing in as much detail as you possibly can: programs, lifts, sets, reps, rest periods, weights, frequency per week, diet, sleep. If you can't be bothered to even write a short description of your lifting then I seriously doubt your commitment to your project.") They have since responded:* > > I do not really follow any programs; I just lift stuff. Plenty get strong this way, so what is wrong with me? > > > You have [fuckarounditis](http://www.leangains.com/2011/09/fuckarounditis.html). I would sympathize, but it's hard when you seem more interested in whinging about other people than actually doing something productive. There are genetic freaks who can sit on a couch for ten years and still lift 400 pounds. They aren't me, so why would I do what they do? I am me. I do what works for me. You are you. You can do what would work for you. Some people can get away with not doing a program. Most people can't. Stop making excuses and pick a program. StrongLifts would be fine, as would Starting Strength, as would 5/3/1 or GreySkull Linear Progression. Pick one of those four--it really doesn't matter which--and follow it unerringly for six months. Keep a workout log. Eat and sleep right. If you do that and it doesn't work, then you will *know* why it didn't work, because you will see it in the log. Skipped workouts or failed lifts will be quite evident in the log. If you are interested in results--and that's a big *if*--then you'll pick a program, follow it, focus on quality sleep, and eat plenty of good food. (You have not described your diet so we can't yet help on that front.)
> > A 22 year old man who is out lifted by small teenagers who barely > workout ... I am a shame of a man and person overall. > > > With that attitude, what you are experiencing is not that strange. When thoughts of that kind manifest in your mind, notice that they don't serve you, and are not even logical (why would your worthiness/value have anything to do with people you don't even know?). They are not even your ideas, but someone else's. Your environment (culture) has implanted detri-mental ideas into your unconscious. So why give them credence? The more you believe your negative thoughts, the more negative results you will experience. I suggest you get rid of your TV and learn to meditate. And then, if you still experience negative thoughts of self-doubt, perhaps have an entheogenic experience that might help you shed the baggage. Addressing your perception of (what you have defined as) your problem should be your primary focus. Without addressing your negative thoughts (i.e. your state of being), you will continue to experience a negative reality, no matter what exercises you do. With that said, thinking about exogenous steroids is a very bad idea in your case, I think. You want to read about endogenous growth factors instead (HGH, BDNF, etc). Consider supplements that decrease metabolic rate and increase growth factors. You'll have to spend the time to research this though; you ought to understand how they work. There is no single magical pill. Consider also meditation, as mentioned, and high-intensity exercises, like HIIT. There is no better way to make your body grow (via HGH) than HIIT (followed by a high-quality whey protein shake), and it requires very little of your time. Consider also steering your diet toward a high-fat low-carb diet. It may seem contradictory but that's because of the failure to understand the metabolic role of fructose, and the falsehoods spread long ago by one Dr. Ancel Keys that began the baseless demonization of dietary fats (particularly saturated fats), which are actually your body's preferred source of fuel. Personally, I only began to gain weight/muscle when slowing my metabolism and increasing growth factors using the methods above. I didn't include any links because if you really are determined you can simply google everything.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
If exercise really would not work then your muscles should have wasted away by now and you would not be able to get out of bed. Astronauts who stay on board the ISS for more than a few weeks have to work very hard to compensate for not having to carry their body weights all day long. So, your muscles are able to repair themselves and maintain the strength needed to do your daily tasks. But it would be an enormous coincidence if this would be precisely the limit of your maximum muscle strength. Given your age (you are not 90 years old), that would be extremely unlikely anyway. So, you will get stronger if you do some exercise.
I have had a problem with the confidence and energy(visible as enthusiasm) which allow me to exercise and feel good until recently and I believe it was diet and sleep related. Because it sounds as though confidence and enthusiasm are likely a large part of your problem, I suggest getting at least 30 grams of protein (even better, the US government's recommended 50 grams per day) and try to sleep eight hours. Separately, it sounds like you might have a shame issue with working out so that you don't exhaust your muscles fully(to failure) in public. Perhaps you are embarrassed to be seen struggling with what you consider light weight? To remedy this issue, you can do exercises that no one can see you do. Examples include pushups, tricep extensions, curls, and shrugs. Try these with 20lbs. or less and marvel at how your arms shape up. This can be a ten minute super-set every day before you shower in the privacy of your home. If you've tried for eight years, what's the harm in another month with a new tactic? PS: A super set is one which alternates muscle-groups between sets, thereby letting lactic acid flush from one muscle group while working other muscle groups.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Genetically engineering your muscles? Not in the next decade or two. Steroids without exercise? No. Steroids increase the protein available to cells, which effectively allows you to work your muscles harder so they grow more. > > A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall. > > > Your worth is not measured by how much you can lift. “Until you value yourself, you won't value your time. Until you value your time, you will not do anything with it. ” ― M. Scott Peck I suspect your barrier to change is not physical, but in your head. No, I don't think you're crazy, but (speaking from personal experience here) many people believe things about themselves that are not true and cause them to limit themselves drastically.
If exercise really would not work then your muscles should have wasted away by now and you would not be able to get out of bed. Astronauts who stay on board the ISS for more than a few weeks have to work very hard to compensate for not having to carry their body weights all day long. So, your muscles are able to repair themselves and maintain the strength needed to do your daily tasks. But it would be an enormous coincidence if this would be precisely the limit of your maximum muscle strength. Given your age (you are not 90 years old), that would be extremely unlikely anyway. So, you will get stronger if you do some exercise.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Disregarding the fact that I agree with Dave Liepmann (either you are not training properly or you have a medical condition inhibiting your performance), I will give you a constructive answer. There is one thing you can do to increase strength without training. It is something that elite athletes use, and is one of the main factors that separates the best athletes from the mediocre ones. Mental imagery. Mental imagery is the use of imagination to visualize certain movements. Science has shown that visualization of a movement increases activity in those areas of the brain, potentiation through the corticospinal tract (motor neuron axons), and activity of the EMG. All these effects lead to gains in strength (<http://www.ncbi.nlm.nih.gov/pubmed/24133427>, <http://www.ncbi.nlm.nih.gov/pubmed/22127572> etc.). The increase in strength comes about by two factors. Firstly, there is increased intra- and intermuscular coordination. That is, by visualizing a movement, your brain is getting used to the sequence of contractions between the muscles and inside them. Secondly, the areas of the brain controlling that movement get increased activity, and this leads to long term changes in activity (sort of like learning to ride a bike, and then remembering; someone who has squatted 300 pounds in their youth will be a stronger squatter than the average person even in old age).
It can be a medical condition like growth hormone deficiency or testosteron deficiency, which you probably won't be able to get confirmed by a normal doctor. Also the mental problems you have with it, feeling unworthy etc, can also stem from there, so balancing your body hormones would be a good first start. (assuming there is a medical condition) You can find doctors specialized in so called anti-aging (e.g. Dr. Hertoghe and colleagues from Belgium) or men medicine who can help you diagnose and treat such a deficiency, but they will only supply the body with the hormones it is lacking, so usually get you on the level a "normal" person of your age would have. Taking steroids en masse will open up a new world full of problems which you really don't wanna have, so I would strongly suggest to not follow this path, especially if you want to have children one day or don't want to have early heart attacks, etc. ;) If the specialist can't detect a deficiency, you will probably have to live with the fact that your body is just not as strong as you want it to be. Every body is different in it's limits and that's definitely nothing to be ashamed of.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Genetically engineering your muscles? Not in the next decade or two. Steroids without exercise? No. Steroids increase the protein available to cells, which effectively allows you to work your muscles harder so they grow more. > > A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall. > > > Your worth is not measured by how much you can lift. “Until you value yourself, you won't value your time. Until you value your time, you will not do anything with it. ” ― M. Scott Peck I suspect your barrier to change is not physical, but in your head. No, I don't think you're crazy, but (speaking from personal experience here) many people believe things about themselves that are not true and cause them to limit themselves drastically.
I have had a problem with the confidence and energy(visible as enthusiasm) which allow me to exercise and feel good until recently and I believe it was diet and sleep related. Because it sounds as though confidence and enthusiasm are likely a large part of your problem, I suggest getting at least 30 grams of protein (even better, the US government's recommended 50 grams per day) and try to sleep eight hours. Separately, it sounds like you might have a shame issue with working out so that you don't exhaust your muscles fully(to failure) in public. Perhaps you are embarrassed to be seen struggling with what you consider light weight? To remedy this issue, you can do exercises that no one can see you do. Examples include pushups, tricep extensions, curls, and shrugs. Try these with 20lbs. or less and marvel at how your arms shape up. This can be a ten minute super-set every day before you shower in the privacy of your home. If you've tried for eight years, what's the harm in another month with a new tactic? PS: A super set is one which alternates muscle-groups between sets, thereby letting lactic acid flush from one muscle group while working other muscle groups.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Stop Making Excuses ------------------- > > "I have six [to] eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise." > > > Either you have a serious medical issue or I call bullshit. I bet the reason you're not getting results is that you *"have [never] been satisfied with results from any workout program or routine over any period of time".* You try something halfheartedly for a little while, then stop, right? You just lift what you feel like and then go home? [That's not going to work.](http://www.t-nation.com/free_online_article/most_recent/the_biggest_training_fallacy_of_all&cr=) If you think you have a serious medical issue then see a doctor about your health, particularly any possible hormone issues. Stop making up reasons not to see a medical professional. Address your problem head-on. Lift, Eat, Repeat ----------------- You must [lift and eat](https://fitness.stackexchange.com/a/6836/1771) if you want to be big and strong. You must work hard. You must be consistent. There is no other way. There are no excuses. There are no alternative methods. Buck up and be serious about your training. Stop being concerned about other people's success and focus on your own progress. You know nothing about what they do. What they do has nothing to do with your own success or failure. Stop distracting yourself with fantasies about other people's supposedly quick and easy results and focus on working out hard and consistently. Follow a Program ---------------- *Originally I asked the OP to detail their workouts. ("If you want help on how to make your workouts effective, describe what you've been doing in as much detail as you possibly can: programs, lifts, sets, reps, rest periods, weights, frequency per week, diet, sleep. If you can't be bothered to even write a short description of your lifting then I seriously doubt your commitment to your project.") They have since responded:* > > I do not really follow any programs; I just lift stuff. Plenty get strong this way, so what is wrong with me? > > > You have [fuckarounditis](http://www.leangains.com/2011/09/fuckarounditis.html). I would sympathize, but it's hard when you seem more interested in whinging about other people than actually doing something productive. There are genetic freaks who can sit on a couch for ten years and still lift 400 pounds. They aren't me, so why would I do what they do? I am me. I do what works for me. You are you. You can do what would work for you. Some people can get away with not doing a program. Most people can't. Stop making excuses and pick a program. StrongLifts would be fine, as would Starting Strength, as would 5/3/1 or GreySkull Linear Progression. Pick one of those four--it really doesn't matter which--and follow it unerringly for six months. Keep a workout log. Eat and sleep right. If you do that and it doesn't work, then you will *know* why it didn't work, because you will see it in the log. Skipped workouts or failed lifts will be quite evident in the log. If you are interested in results--and that's a big *if*--then you'll pick a program, follow it, focus on quality sleep, and eat plenty of good food. (You have not described your diet so we can't yet help on that front.)
Disregarding the fact that I agree with Dave Liepmann (either you are not training properly or you have a medical condition inhibiting your performance), I will give you a constructive answer. There is one thing you can do to increase strength without training. It is something that elite athletes use, and is one of the main factors that separates the best athletes from the mediocre ones. Mental imagery. Mental imagery is the use of imagination to visualize certain movements. Science has shown that visualization of a movement increases activity in those areas of the brain, potentiation through the corticospinal tract (motor neuron axons), and activity of the EMG. All these effects lead to gains in strength (<http://www.ncbi.nlm.nih.gov/pubmed/24133427>, <http://www.ncbi.nlm.nih.gov/pubmed/22127572> etc.). The increase in strength comes about by two factors. Firstly, there is increased intra- and intermuscular coordination. That is, by visualizing a movement, your brain is getting used to the sequence of contractions between the muscles and inside them. Secondly, the areas of the brain controlling that movement get increased activity, and this leads to long term changes in activity (sort of like learning to ride a bike, and then remembering; someone who has squatted 300 pounds in their youth will be a stronger squatter than the average person even in old age).
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Disregarding the fact that I agree with Dave Liepmann (either you are not training properly or you have a medical condition inhibiting your performance), I will give you a constructive answer. There is one thing you can do to increase strength without training. It is something that elite athletes use, and is one of the main factors that separates the best athletes from the mediocre ones. Mental imagery. Mental imagery is the use of imagination to visualize certain movements. Science has shown that visualization of a movement increases activity in those areas of the brain, potentiation through the corticospinal tract (motor neuron axons), and activity of the EMG. All these effects lead to gains in strength (<http://www.ncbi.nlm.nih.gov/pubmed/24133427>, <http://www.ncbi.nlm.nih.gov/pubmed/22127572> etc.). The increase in strength comes about by two factors. Firstly, there is increased intra- and intermuscular coordination. That is, by visualizing a movement, your brain is getting used to the sequence of contractions between the muscles and inside them. Secondly, the areas of the brain controlling that movement get increased activity, and this leads to long term changes in activity (sort of like learning to ride a bike, and then remembering; someone who has squatted 300 pounds in their youth will be a stronger squatter than the average person even in old age).
If exercise really would not work then your muscles should have wasted away by now and you would not be able to get out of bed. Astronauts who stay on board the ISS for more than a few weeks have to work very hard to compensate for not having to carry their body weights all day long. So, your muscles are able to repair themselves and maintain the strength needed to do your daily tasks. But it would be an enormous coincidence if this would be precisely the limit of your maximum muscle strength. Given your age (you are not 90 years old), that would be extremely unlikely anyway. So, you will get stronger if you do some exercise.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Stop Making Excuses ------------------- > > "I have six [to] eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise." > > > Either you have a serious medical issue or I call bullshit. I bet the reason you're not getting results is that you *"have [never] been satisfied with results from any workout program or routine over any period of time".* You try something halfheartedly for a little while, then stop, right? You just lift what you feel like and then go home? [That's not going to work.](http://www.t-nation.com/free_online_article/most_recent/the_biggest_training_fallacy_of_all&cr=) If you think you have a serious medical issue then see a doctor about your health, particularly any possible hormone issues. Stop making up reasons not to see a medical professional. Address your problem head-on. Lift, Eat, Repeat ----------------- You must [lift and eat](https://fitness.stackexchange.com/a/6836/1771) if you want to be big and strong. You must work hard. You must be consistent. There is no other way. There are no excuses. There are no alternative methods. Buck up and be serious about your training. Stop being concerned about other people's success and focus on your own progress. You know nothing about what they do. What they do has nothing to do with your own success or failure. Stop distracting yourself with fantasies about other people's supposedly quick and easy results and focus on working out hard and consistently. Follow a Program ---------------- *Originally I asked the OP to detail their workouts. ("If you want help on how to make your workouts effective, describe what you've been doing in as much detail as you possibly can: programs, lifts, sets, reps, rest periods, weights, frequency per week, diet, sleep. If you can't be bothered to even write a short description of your lifting then I seriously doubt your commitment to your project.") They have since responded:* > > I do not really follow any programs; I just lift stuff. Plenty get strong this way, so what is wrong with me? > > > You have [fuckarounditis](http://www.leangains.com/2011/09/fuckarounditis.html). I would sympathize, but it's hard when you seem more interested in whinging about other people than actually doing something productive. There are genetic freaks who can sit on a couch for ten years and still lift 400 pounds. They aren't me, so why would I do what they do? I am me. I do what works for me. You are you. You can do what would work for you. Some people can get away with not doing a program. Most people can't. Stop making excuses and pick a program. StrongLifts would be fine, as would Starting Strength, as would 5/3/1 or GreySkull Linear Progression. Pick one of those four--it really doesn't matter which--and follow it unerringly for six months. Keep a workout log. Eat and sleep right. If you do that and it doesn't work, then you will *know* why it didn't work, because you will see it in the log. Skipped workouts or failed lifts will be quite evident in the log. If you are interested in results--and that's a big *if*--then you'll pick a program, follow it, focus on quality sleep, and eat plenty of good food. (You have not described your diet so we can't yet help on that front.)
If exercise really would not work then your muscles should have wasted away by now and you would not be able to get out of bed. Astronauts who stay on board the ISS for more than a few weeks have to work very hard to compensate for not having to carry their body weights all day long. So, your muscles are able to repair themselves and maintain the strength needed to do your daily tasks. But it would be an enormous coincidence if this would be precisely the limit of your maximum muscle strength. Given your age (you are not 90 years old), that would be extremely unlikely anyway. So, you will get stronger if you do some exercise.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Disregarding the fact that I agree with Dave Liepmann (either you are not training properly or you have a medical condition inhibiting your performance), I will give you a constructive answer. There is one thing you can do to increase strength without training. It is something that elite athletes use, and is one of the main factors that separates the best athletes from the mediocre ones. Mental imagery. Mental imagery is the use of imagination to visualize certain movements. Science has shown that visualization of a movement increases activity in those areas of the brain, potentiation through the corticospinal tract (motor neuron axons), and activity of the EMG. All these effects lead to gains in strength (<http://www.ncbi.nlm.nih.gov/pubmed/24133427>, <http://www.ncbi.nlm.nih.gov/pubmed/22127572> etc.). The increase in strength comes about by two factors. Firstly, there is increased intra- and intermuscular coordination. That is, by visualizing a movement, your brain is getting used to the sequence of contractions between the muscles and inside them. Secondly, the areas of the brain controlling that movement get increased activity, and this leads to long term changes in activity (sort of like learning to ride a bike, and then remembering; someone who has squatted 300 pounds in their youth will be a stronger squatter than the average person even in old age).
I have had a problem with the confidence and energy(visible as enthusiasm) which allow me to exercise and feel good until recently and I believe it was diet and sleep related. Because it sounds as though confidence and enthusiasm are likely a large part of your problem, I suggest getting at least 30 grams of protein (even better, the US government's recommended 50 grams per day) and try to sleep eight hours. Separately, it sounds like you might have a shame issue with working out so that you don't exhaust your muscles fully(to failure) in public. Perhaps you are embarrassed to be seen struggling with what you consider light weight? To remedy this issue, you can do exercises that no one can see you do. Examples include pushups, tricep extensions, curls, and shrugs. Try these with 20lbs. or less and marvel at how your arms shape up. This can be a ten minute super-set every day before you shower in the privacy of your home. If you've tried for eight years, what's the harm in another month with a new tactic? PS: A super set is one which alternates muscle-groups between sets, thereby letting lactic acid flush from one muscle group while working other muscle groups.
16,723
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible? Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate. I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for. Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14. A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
2014/06/05
[ "https://fitness.stackexchange.com/questions/16723", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8807/" ]
Disregarding the fact that I agree with Dave Liepmann (either you are not training properly or you have a medical condition inhibiting your performance), I will give you a constructive answer. There is one thing you can do to increase strength without training. It is something that elite athletes use, and is one of the main factors that separates the best athletes from the mediocre ones. Mental imagery. Mental imagery is the use of imagination to visualize certain movements. Science has shown that visualization of a movement increases activity in those areas of the brain, potentiation through the corticospinal tract (motor neuron axons), and activity of the EMG. All these effects lead to gains in strength (<http://www.ncbi.nlm.nih.gov/pubmed/24133427>, <http://www.ncbi.nlm.nih.gov/pubmed/22127572> etc.). The increase in strength comes about by two factors. Firstly, there is increased intra- and intermuscular coordination. That is, by visualizing a movement, your brain is getting used to the sequence of contractions between the muscles and inside them. Secondly, the areas of the brain controlling that movement get increased activity, and this leads to long term changes in activity (sort of like learning to ride a bike, and then remembering; someone who has squatted 300 pounds in their youth will be a stronger squatter than the average person even in old age).
> > A 22 year old man who is out lifted by small teenagers who barely > workout ... I am a shame of a man and person overall. > > > With that attitude, what you are experiencing is not that strange. When thoughts of that kind manifest in your mind, notice that they don't serve you, and are not even logical (why would your worthiness/value have anything to do with people you don't even know?). They are not even your ideas, but someone else's. Your environment (culture) has implanted detri-mental ideas into your unconscious. So why give them credence? The more you believe your negative thoughts, the more negative results you will experience. I suggest you get rid of your TV and learn to meditate. And then, if you still experience negative thoughts of self-doubt, perhaps have an entheogenic experience that might help you shed the baggage. Addressing your perception of (what you have defined as) your problem should be your primary focus. Without addressing your negative thoughts (i.e. your state of being), you will continue to experience a negative reality, no matter what exercises you do. With that said, thinking about exogenous steroids is a very bad idea in your case, I think. You want to read about endogenous growth factors instead (HGH, BDNF, etc). Consider supplements that decrease metabolic rate and increase growth factors. You'll have to spend the time to research this though; you ought to understand how they work. There is no single magical pill. Consider also meditation, as mentioned, and high-intensity exercises, like HIIT. There is no better way to make your body grow (via HGH) than HIIT (followed by a high-quality whey protein shake), and it requires very little of your time. Consider also steering your diet toward a high-fat low-carb diet. It may seem contradictory but that's because of the failure to understand the metabolic role of fructose, and the falsehoods spread long ago by one Dr. Ancel Keys that began the baseless demonization of dietary fats (particularly saturated fats), which are actually your body's preferred source of fuel. Personally, I only began to gain weight/muscle when slowing my metabolism and increasing growth factors using the methods above. I didn't include any links because if you really are determined you can simply google everything.
221,568
Is there a way in SWT to get a monospaced font simply, that works across various operating systems? For example. this works on Linux, but not Windows: ``` Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE); ``` or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup. I tried getting the system font from Display, but that wasn't monospaced.
2008/10/21
[ "https://Stackoverflow.com/questions/221568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17832/" ]
According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files: > > The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways. > > > So in your case, I'd try `Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);` to get a handle to the physical monospaced font of the current platform your code is running on. **Edit**: It seems that SWT doesn't know anything about logical fonts ([Bug 48055](https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055) on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...
To the best of my knowledge, the AWT API does not expose underlying Font information. If you can get to it, I would expect it to be implementation dependent. Certainly, comparing the font mapping files in a couple of JRE lib directories, I can see that they are not defined in a consistent way. You could load your own fonts, but that seems a little wasteful given you know the platform comes with what you need. This is a hack that loads a JRE font: ``` private static Font loadMonospacedFont(Display display) { String jreHome = System.getProperty("java.home"); File file = new File(jreHome, "/lib/fonts/LucidaTypewriterRegular.ttf"); if (!file.exists()) { throw new IllegalStateException(file.toString()); } if (!display.loadFont(file.toString())) { throw new IllegalStateException(file.toString()); } final Font font = new Font(display, "Lucida Sans Typewriter", 10, SWT.NORMAL); display.addListener(SWT.Dispose, new Listener() { public void handleEvent(Event event) { font.dispose(); } }); return font; } ``` It works on IBM/Win32/JRE1.4, Sun/Win32/JRE1.6, Sun/Linux/JRE1.6, but is a pretty fragile approach. Depending on your needs for I18N, it could be trouble there too (I haven't checked). Another hack would be to test the fonts available on the platform: ``` public class Monotest { private static boolean isMonospace(GC gc) { final String wide = "wgh8"; final String narrow = "1l;."; assert wide.length() == narrow.length(); return gc.textExtent(wide).x == gc.textExtent(narrow).x; } private static void testFont(Display display, Font font) { Image image = new Image(display, 100, 100); try { GC gc = new GC(image); try { gc.setFont(font); System.out.println(isMonospace(gc) + "\t" + font.getFontData()[0].getName()); } finally { gc.dispose(); } } finally { image.dispose(); } } private static void walkFonts(Display display) { final boolean scalable = true; for (FontData fontData : display.getFontList(null, scalable)) { Font font = new Font(display, fontData); try { testFont(display, font); } finally { font.dispose(); } } } public static void main(String[] args) { Display display = new Display(); try { walkFonts(display); } finally { display.dispose(); } } } ``` This probably isn't a good approach as it may leave you exposed to locale issues. Besides, you don't know if the first monospaced font you come across isn't some windings icon set. The best approach may just be to take your best guess based on a font/locale mapping whitelist and make sure that the users can easily reconfigure the UI to suit themselves via [FontDialog](http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/FontDialog.html).
221,568
Is there a way in SWT to get a monospaced font simply, that works across various operating systems? For example. this works on Linux, but not Windows: ``` Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE); ``` or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup. I tried getting the system font from Display, but that wasn't monospaced.
2008/10/21
[ "https://Stackoverflow.com/questions/221568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17832/" ]
According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files: > > The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways. > > > So in your case, I'd try `Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);` to get a handle to the physical monospaced font of the current platform your code is running on. **Edit**: It seems that SWT doesn't know anything about logical fonts ([Bug 48055](https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055) on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...
If you want just a Monospaced font use "Courier" => `new Font(display, "Courier", 10, SWT.NORMAL)`