Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
9,071,174 |
As part of strengthening session authentication security for a site that I am building, I am trying to compile a list of the best ways to register a user's computer as a second tier of validation - that is in addition to the standard username/password login, of course. Typical ways of registering a user's computer are by setting a cookie and or IP address validation. As prevalent as mobile computing is, IP mapping is less and less a reliable identifier. Security settings and internet security & system optimization software can make it difficult to keep a cookie in place for very long.
Are there any other methods that can be used for establishing a more reliable computer registration that doesn't require the user to add exceptions to the various cookie deleting software?
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9071174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708034/"
] |
Simply calling read doesn't guarantee that you will receive all the 63 bytes or that you receive the 63 bytes you were hoping for.. I would suggest that you somehow determine how much data you need to receive(send the data length first) and then put the recv function in a loop until you have all the data.. The send function(from the client) should be checked also.
|
How about trying to close the socket at the end of dostuff()?
The server may be getting too many open connections.
|
9,071,174 |
As part of strengthening session authentication security for a site that I am building, I am trying to compile a list of the best ways to register a user's computer as a second tier of validation - that is in addition to the standard username/password login, of course. Typical ways of registering a user's computer are by setting a cookie and or IP address validation. As prevalent as mobile computing is, IP mapping is less and less a reliable identifier. Security settings and internet security & system optimization software can make it difficult to keep a cookie in place for very long.
Are there any other methods that can be used for establishing a more reliable computer registration that doesn't require the user to add exceptions to the various cookie deleting software?
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9071174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708034/"
] |
Simply calling read doesn't guarantee that you will receive all the 63 bytes or that you receive the 63 bytes you were hoping for.. I would suggest that you somehow determine how much data you need to receive(send the data length first) and then put the recv function in a loop until you have all the data.. The send function(from the client) should be checked also.
|
Solution: The error was that the XOpenDisplay was inside an infinite loop without being closed. I simply moved the XOpenDisplay command before the infinite loop in dostuff().
It was in fact not a socket error.
|
43,985,851 |
If I'm using webpack, I can create a program using CommonJS module syntax
```
#File: src-client/entry-point.js
helloWorld1 = require('./hello-world');
alert(helloWorld1.getMessage());
#File: src-client/hello-world.js
var toExport = {};
toExport.getMessage = function(){
return 'Hello Webpack';
}
module.exports = toExport;
```
I can also create a program using ES6/ES2015 module syntax.
```
#File: src-client/entry-point.js
import * as helloWorld2 from './hello-world2';
alert(helloWorld2.getMessage());
#File: src-client/hello-world2.js
var getMessage = function(){
return 'Hello ES2015';
};
export {getMessage};
```
Both of the above programs compile and run (in browser) without issue. However, if I try to mix and match the syntax
```
#File: src-client/entry-point.js
helloWorld1 = require('./hello-world');
import * as helloWorld2 from './hello-world2';
alert(helloWorld1.getMessage());
alert(helloWorld2.getMessage());
```
Webpack itself will happily compile the program
```
$ ./node_modules/webpack/bin/webpack.js src-client/entry-point.js pub/bundle.js
Hash: 1ce72fd037a8461e0509
Version: webpack 2.5.1
Time: 72ms
Asset Size Chunks Chunk Names
bundle.js 3.45 kB 0 [emitted] main
[0] ./src-client/hello-world.js 110 bytes {0} [built]
[1] ./src-client/hello-world2.js 80 bytes {0} [built]
[2] ./src-client/entry-point.js 155 bytes {0} [built]
```
but when I run the program in my browser, I get the following error
```
Uncaught ReferenceError: helloWorld1 is not defined
at Object.<anonymous> (bundle.js:101)
at __webpack_require__ (bundle.js:20)
at toExport (bundle.js:66)
at bundle.js:69
```
I didn't expect this to work (I'm not a monster), but it does raise the question of what, exactly, is going on.
When webpack encounters conflicting module syntax like this -- what happens? Does the presence of an `import` keyword put webpack into "parse ES2015" mode? Is there a way to force webpack to treat certain files as ES2015 and others as CommonJS? i.e. is there a way for webpack to seamlessly handle a project with modules using multiple standards? Or is the general feeling that you shouldn't do this?
|
2017/05/15
|
[
"https://Stackoverflow.com/questions/43985851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4668/"
] |
The presence of `import` automatically puts the module in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode), as defined in the [Spec](https://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code). In strict mode you're not allowed to use a variable that hasn't been defined, whereas in regular mode the variable will implicitly become a global variable. You try to assign the result of `require` to `helloWorld1` which was not previously defined. You need to declare that variable:
```
const helloWorld1 = require('./hello-world');
```
Instead of `const` you may also use `let` or `var`.
|
Webpack should not have any trouble mixing the different module syntaxes.
The problem is you *implicitly declared* `helloWorld1` in an ES2015 module. These modules [are in strict mode by default](https://stackoverflow.com/questions/29283935/which-ecmascript-6-features-imply-strict-mode), which means you can not declare a variable like that in an ES2015 module.
Change your line to the line below, and I'm pretty confident your program will run.
```
let helloWorld1 = require('./hello-world');
```
|
1,439,713 |
I want to build an ant script that does exactly the same compilation actions on a Flash Builder 4 (Gumbo) project as the `Project->Export Release Build...` menu item does. My ant-fu is reasonably strong, that's not the issue, but rather I'm not sure exactly what that entry is doing.
Some details:
* I'll be using the 3.x SDK (say, 3.2 for the sake of specificity) to build this.
* I'll be building on a Mac, and I can happily use ant, make, or some weird shell script stuff if that's the way you roll.
* Any useful optimizations you can suggest will be welcome.
* The project contains a few assets, MXML and actionscript source, and a couple of .swcs that are built into the project (not RSL'd)
Can someone provide an ant build.xml or makefle that they use to build a release .swf file from a similar Flex project?
|
2009/09/17
|
[
"https://Stackoverflow.com/questions/1439713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
One quick way to know the compiler options is to add this tag into your compiler options:
-dump-config your/drive/to/store/the/xmlfile.xml
This will output the entire ant compiler options and you can copy off the parts you want to keep.
|
I had some issues with the Adobe Flex Ant tasks a while back, so I ended up using an exec call to the mxmlc compiler with a boatload of options and we've just built upon it from there. There are a few nagging doubts that what I do with the build.xml is not exactly the same that FB3 (what we have) does, but this might be enough to help get you started... you say your ant-fu is reasonably strong, so I'll skip over most of my build file and let you piece together the pieces.
```
<!--flex stuff-->
<property name="dir.flex.sdk" value="${system.build.flex.sdk}"/>
<property name="dir.flex.home" value="${dir.abc}/flex/sdks/${dir.flex.sdk}"/>
<property name="dir.flex.projects" value="${dir.abcd_plat}/webapp/flexprojects/"/>
<property name="dir.modules" value="${dir.war}/modules/"/>
<property name="FLEX_HOME" value="${dir.flex.home}"/>
<property name="APP_ROOT" value="${dir.war}"/>
<property name="flexc.exe" value="This should be set in the build-${os.family}.xml file"/>
<property name="asdoc.exe" value="This should be set in the build-${os.family}.xml file"/>
<property name="optimizer.exe" value="This should be set in the build-${os.family}.xml file"/>
<property name="flex.mxmlc" value="${dir.flex.home}/bin/${flexc.exe}"/>
<property name="flex.compc" value="${dir.flex.home}/bin/${compc.exe}"/>
<property name="flex.asdoc" value="${dir.flex.home}/bin/${asdoc.exe}"/>
<property name="flex.optimizer" value="${dir.flex.home}/bin/${optimizer.exe}"/>
<property name="flex.options.warnings" value="false"/>
<!--options that are used in common for compiling all .swc and .swf files-->
<property name="flex.meta.1" value="-creator 'MyCorp.' -publisher 'MyCorp.'"/>
<property name="flex.meta.2" value="-title MegaProduct -description http://ourURL.com"/>
<property name="flex.meta.props" value="${flex.meta.1} ${flex.meta.2}"/>
<property name="debug.options" value="-optimize=true -debug=false"/>
<property name="common.flex" value="-as3 -target-player=9.0.124 -warnings=${flex.options.warnings}"/>
<property name="license.flex3" value="(put your own here)"/>
<property name="common.fixed" value="-license=flexbuilder3,${license.flex3} -sp ${dir.war} -library-path+=${dir.webinf}/lib"/>
<property name="flex.common.args" value="${flex.meta.props} ${debug.options} ${common.flex} ${common.fixed}"/>
<!--this is currently unused, but if we make a debug version, this can be set to make a separate output file-->
<property name="swf.suffix" value=""/>
<!--=================================================================================
MACRODEFs
-->
<!--this is used to extract .swf files from 3rd party .swc libraries, in order to do dynamic linking-->
<macrodef name="extract-flex-lib" description="For modularizing flex compilation">
<attribute name="swc-lib" default="NOT SET"/>
<sequential>
<!--use a copy task - it can get the file out of the zip, and rename it at the same time-->
<copy todir="${dir.war}" preservelastmodified="true">
<zipfileset src="${dir.webinf}/lib/@{swc-lib}.swc">
<patternset>
<include name="library.swf"/>
</patternset>
</zipfileset>
<mapper type="glob" from="library.swf" to="@{swc-lib}-debug.swf"/>
</copy>
<!--run the flex optimizer on the extracted .swf - note the as3 metadata that's kept, it's required-->
<exec executable="${flex.optimizer}" failonerror="true">
<arg line="-keep-as3-metadata='Bindable,Managed,ChangeEvent,NonCommittingChangeEvent,Transient'"/>
<arg line="-input @{swc-lib}-debug.swf -output @{swc-lib}.swf"/>
</exec>
<!--delete the unoptimzed swf, don't need it anymore-->
<delete file="@{swc-lib}-debug.swf"/>
</sequential>
</macrodef>
<!--this is used to compile our internal flex modules-->
<macrodef name="flexc-mxml" description="For building the flex modules during flex compilation">
<attribute name="name" default=""/>
<attribute name="mxml.args" default="${flex.common.args} ${module.args}"/>
<attribute name="sourcePath" default=""/>
<attribute name="destPath" default=""/>
<sequential>
<echo message=" Compiling with mxmlc: @{name}"/>
<exec executable="${flex.mxmlc}" failonerror="true">
<arg line="@{mxml.args} @{sourcePath} -output @{destPath}"/>
</exec>
</sequential>
</macrodef>
<!--this is used to compile our subprojects under abcd_plat/webapp/flexprojects-->
<macrodef name="flexc-subproject" description="For compiling the flex subprojects into .swc files">
<attribute name="name" default=""/>
<attribute name="xtra.args" default=""/>
<sequential>
<echo/>
<echo message=" Compiling subproject: @{name}"/>
<xslt in="${dir.flex.projects}/@{name}/.flexLibProperties" out="${dir.flex.projects}/@{name}/src/manifest.xml" style="${dir.war}/build-manifest-style.xsl"/>
<exec executable="${flex.compc}" failonerror="true">
<arg line="-load-config+=${dir.flex.projects}/@{name}/include-files.xml"/>
<arg line="-namespace http://@{name}.ourURL.com ${dir.flex.projects}/@{name}/src/manifest.xml"/>
<arg line="-include-namespaces http://@{name}.ourURL.com @{xtra.args}"/>
<arg line="-library-path+=${dir.webinf}/lib -sp ${dir.flex.projects}/@{name}/src -output ${dir.webinf}/lib/@{name}.swc"/>
</exec>
</sequential>
</macrodef>
<!--=================================================================================
This is where all the compilation is done. The actual work is split among
several different tasks in order to organize them better.
This target uses the html-wrapper task defined in flexTasks.jar - see taskdef above.
-->
<target name="flexcompile" depends="flexc-modularize" description="Builds the Flex sources" unless="flexc.notRequired.main">
<echo message="Compiling MegaProduct Flex application on OS family: ${os.family}"/>
<echo message=" mxmlc is: ${flex.mxmlc}"/>
<echo message=" compc is: ${flex.compc}"/>
<!--compile flex sub-projects first (main application depends on these extra libraries)-->
<antcall target="flexc-projects"/>
<!--compile the main MegaProduct application-->
<antcall target="flexc-main"/>
<!--compile the foobar stuff, which link against the main app. these foorbars are modules
inside a subproject, so they are handled differently from other flex projects and modules-->
<antcall target="flexc-foorbars"/>
<!--generate the html wrapper for the .swf-->
<html-wrapper title="MyCorp MegaProduct" application="app_name" swf="app_name" history="false" template="express-installation"/>
</target>
<target name="flexc-projects">
<!--the name must match the name of the folder exactly, also they are not in parallel as some depend on others-->
<flexc-subproject name="Dockable"/>
<flexc-subproject name="EXRibbon" xtra.args="-source-path+=${dir.flex.projects}/EXRibbon/locale/en_US/"/>
<!--note: MPLib does some extra stuff with the image dir in order to link against images correctly-->
<copy todir="${dir.flex.projects}/MPLib/src/image"><fileset dir="${dir.war}/image"/></copy>
<flexc-subproject name="MPLib"/>
<delete dir="${dir.flex.projects}/MPLib/src/image"/>
</target>
<target name="flexc-main">
<!--the link report is used to create the symbols in the main swf, and modules link against it-->
<property name="link.report" value="${dir.war}/abc_link_report.xml"/>
<!--modular.args is set in flexc-modularize. If not set, this sets it to an empty property-->
<property name="modular.args" value=""/>
<!--set up options specific for the main part and for the modules-->
<property name="main.args" value="-link-report=${link.report} ${modular.args}"/>
<property name="module.args" value="-load-externs=${link.report}"/>
<!--compile abc_flex.mxml here-->
<echo message="Compiling abc_flex application, sub-applications and modules..."/>
<echo/>
<flexc-mxml name="abc_flex" mxml.args="${flex.common.args} ${main.args}"
sourcePath="${dir.war}/abc_flex.mxml" destPath="${dir.war}/abc_flex${swf.suffix}.swf"/>
<!--compile MPMainSubApplication.mxml sub-application here-->
<flexc-mxml name="MPMainSubApplication" mxml.args="${flex.common.args} ${main.args}"
sourcePath="${dir.war}/MPMainSubApplication.mxml" destPath="${dir.war}/MPMainSubApplication.swf"/>
<!--compile internal modules next - just add new modules to the list here -->
<parallel> <!--do in parallel - it goes faster and they don't depend on each other-->
<property name="dir.module.src" value="${dir.war}/module/"/>
<flexc-mxml name="module1" sourcePath="${dir.module.src}/editor/Editor.mxml" destPath="${dir.module.src}/editor/Editor.swf" />
<flexc-mxml name="RunModule" sourcePath="${dir.module.src}/run/RunModule.mxml" destPath="${dir.module.src}/run/RunModule.swf" />
<!--<flexc-mxml name="JobManager" sourcePath="${dir.module.src}/jobmanager/JobManager.mxml" destPath="${dir.module.src}/jobmanager/JobManager.swf" />-->
<flexc-mxml name="Editor2" sourcePath="${dir.module.src}/edit/Editor.mxml" destPath="${dir.module.src}/edit/Editor.swf" />
</parallel>
</target>
```
NOTES:
I'm not sure if it's a good idea or not, but we just put the .swc files to include with our Java middle tier libs in WEB-INF/lib, so whenever we add a new flex lib to source control we just drop it in there. The compilation is done in the macros, and most of the parameters are defined as properties in the top section. The targets split the work because our app is quite large; you probably don't need those but it's an example of doing modules within sub-projects plus the link-report and follows the way a sub-project is referenced from the main application (I think). Our build machine is linux, so that's why the flexc.exe property (and others) are defined that way - it gets set at runtime. Names have been munged by hand for this answer, so please double-check for typos if you cut-n-paste anything.
Also, the incremental compilation isn't actually used; it seems to be buggy. Ditto for the modularization stuff, so I didn't include that target.
I built all of this myself so I'm rather proud of it, but if there's anything that looks iffy or smells bad, please feel free to let me know. Thanks!
|
1,439,713 |
I want to build an ant script that does exactly the same compilation actions on a Flash Builder 4 (Gumbo) project as the `Project->Export Release Build...` menu item does. My ant-fu is reasonably strong, that's not the issue, but rather I'm not sure exactly what that entry is doing.
Some details:
* I'll be using the 3.x SDK (say, 3.2 for the sake of specificity) to build this.
* I'll be building on a Mac, and I can happily use ant, make, or some weird shell script stuff if that's the way you roll.
* Any useful optimizations you can suggest will be welcome.
* The project contains a few assets, MXML and actionscript source, and a couple of .swcs that are built into the project (not RSL'd)
Can someone provide an ant build.xml or makefle that they use to build a release .swf file from a similar Flex project?
|
2009/09/17
|
[
"https://Stackoverflow.com/questions/1439713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
HellFire Compiler Daemon (<http://bytecode-workshop.com>/) can generate build.xml directly from the compiler calls made by Flex/Flash Builder. That means your ant script produces SWCs and SWFs based on the exact same set of compiler settings that you set in Flex/Flash Builder.
Also, check out this blog:
<http://stopcoding.wordpress.com/2010/01/15/ant-tasks-for-hfcd-now-available-2/>
|
I had some issues with the Adobe Flex Ant tasks a while back, so I ended up using an exec call to the mxmlc compiler with a boatload of options and we've just built upon it from there. There are a few nagging doubts that what I do with the build.xml is not exactly the same that FB3 (what we have) does, but this might be enough to help get you started... you say your ant-fu is reasonably strong, so I'll skip over most of my build file and let you piece together the pieces.
```
<!--flex stuff-->
<property name="dir.flex.sdk" value="${system.build.flex.sdk}"/>
<property name="dir.flex.home" value="${dir.abc}/flex/sdks/${dir.flex.sdk}"/>
<property name="dir.flex.projects" value="${dir.abcd_plat}/webapp/flexprojects/"/>
<property name="dir.modules" value="${dir.war}/modules/"/>
<property name="FLEX_HOME" value="${dir.flex.home}"/>
<property name="APP_ROOT" value="${dir.war}"/>
<property name="flexc.exe" value="This should be set in the build-${os.family}.xml file"/>
<property name="asdoc.exe" value="This should be set in the build-${os.family}.xml file"/>
<property name="optimizer.exe" value="This should be set in the build-${os.family}.xml file"/>
<property name="flex.mxmlc" value="${dir.flex.home}/bin/${flexc.exe}"/>
<property name="flex.compc" value="${dir.flex.home}/bin/${compc.exe}"/>
<property name="flex.asdoc" value="${dir.flex.home}/bin/${asdoc.exe}"/>
<property name="flex.optimizer" value="${dir.flex.home}/bin/${optimizer.exe}"/>
<property name="flex.options.warnings" value="false"/>
<!--options that are used in common for compiling all .swc and .swf files-->
<property name="flex.meta.1" value="-creator 'MyCorp.' -publisher 'MyCorp.'"/>
<property name="flex.meta.2" value="-title MegaProduct -description http://ourURL.com"/>
<property name="flex.meta.props" value="${flex.meta.1} ${flex.meta.2}"/>
<property name="debug.options" value="-optimize=true -debug=false"/>
<property name="common.flex" value="-as3 -target-player=9.0.124 -warnings=${flex.options.warnings}"/>
<property name="license.flex3" value="(put your own here)"/>
<property name="common.fixed" value="-license=flexbuilder3,${license.flex3} -sp ${dir.war} -library-path+=${dir.webinf}/lib"/>
<property name="flex.common.args" value="${flex.meta.props} ${debug.options} ${common.flex} ${common.fixed}"/>
<!--this is currently unused, but if we make a debug version, this can be set to make a separate output file-->
<property name="swf.suffix" value=""/>
<!--=================================================================================
MACRODEFs
-->
<!--this is used to extract .swf files from 3rd party .swc libraries, in order to do dynamic linking-->
<macrodef name="extract-flex-lib" description="For modularizing flex compilation">
<attribute name="swc-lib" default="NOT SET"/>
<sequential>
<!--use a copy task - it can get the file out of the zip, and rename it at the same time-->
<copy todir="${dir.war}" preservelastmodified="true">
<zipfileset src="${dir.webinf}/lib/@{swc-lib}.swc">
<patternset>
<include name="library.swf"/>
</patternset>
</zipfileset>
<mapper type="glob" from="library.swf" to="@{swc-lib}-debug.swf"/>
</copy>
<!--run the flex optimizer on the extracted .swf - note the as3 metadata that's kept, it's required-->
<exec executable="${flex.optimizer}" failonerror="true">
<arg line="-keep-as3-metadata='Bindable,Managed,ChangeEvent,NonCommittingChangeEvent,Transient'"/>
<arg line="-input @{swc-lib}-debug.swf -output @{swc-lib}.swf"/>
</exec>
<!--delete the unoptimzed swf, don't need it anymore-->
<delete file="@{swc-lib}-debug.swf"/>
</sequential>
</macrodef>
<!--this is used to compile our internal flex modules-->
<macrodef name="flexc-mxml" description="For building the flex modules during flex compilation">
<attribute name="name" default=""/>
<attribute name="mxml.args" default="${flex.common.args} ${module.args}"/>
<attribute name="sourcePath" default=""/>
<attribute name="destPath" default=""/>
<sequential>
<echo message=" Compiling with mxmlc: @{name}"/>
<exec executable="${flex.mxmlc}" failonerror="true">
<arg line="@{mxml.args} @{sourcePath} -output @{destPath}"/>
</exec>
</sequential>
</macrodef>
<!--this is used to compile our subprojects under abcd_plat/webapp/flexprojects-->
<macrodef name="flexc-subproject" description="For compiling the flex subprojects into .swc files">
<attribute name="name" default=""/>
<attribute name="xtra.args" default=""/>
<sequential>
<echo/>
<echo message=" Compiling subproject: @{name}"/>
<xslt in="${dir.flex.projects}/@{name}/.flexLibProperties" out="${dir.flex.projects}/@{name}/src/manifest.xml" style="${dir.war}/build-manifest-style.xsl"/>
<exec executable="${flex.compc}" failonerror="true">
<arg line="-load-config+=${dir.flex.projects}/@{name}/include-files.xml"/>
<arg line="-namespace http://@{name}.ourURL.com ${dir.flex.projects}/@{name}/src/manifest.xml"/>
<arg line="-include-namespaces http://@{name}.ourURL.com @{xtra.args}"/>
<arg line="-library-path+=${dir.webinf}/lib -sp ${dir.flex.projects}/@{name}/src -output ${dir.webinf}/lib/@{name}.swc"/>
</exec>
</sequential>
</macrodef>
<!--=================================================================================
This is where all the compilation is done. The actual work is split among
several different tasks in order to organize them better.
This target uses the html-wrapper task defined in flexTasks.jar - see taskdef above.
-->
<target name="flexcompile" depends="flexc-modularize" description="Builds the Flex sources" unless="flexc.notRequired.main">
<echo message="Compiling MegaProduct Flex application on OS family: ${os.family}"/>
<echo message=" mxmlc is: ${flex.mxmlc}"/>
<echo message=" compc is: ${flex.compc}"/>
<!--compile flex sub-projects first (main application depends on these extra libraries)-->
<antcall target="flexc-projects"/>
<!--compile the main MegaProduct application-->
<antcall target="flexc-main"/>
<!--compile the foobar stuff, which link against the main app. these foorbars are modules
inside a subproject, so they are handled differently from other flex projects and modules-->
<antcall target="flexc-foorbars"/>
<!--generate the html wrapper for the .swf-->
<html-wrapper title="MyCorp MegaProduct" application="app_name" swf="app_name" history="false" template="express-installation"/>
</target>
<target name="flexc-projects">
<!--the name must match the name of the folder exactly, also they are not in parallel as some depend on others-->
<flexc-subproject name="Dockable"/>
<flexc-subproject name="EXRibbon" xtra.args="-source-path+=${dir.flex.projects}/EXRibbon/locale/en_US/"/>
<!--note: MPLib does some extra stuff with the image dir in order to link against images correctly-->
<copy todir="${dir.flex.projects}/MPLib/src/image"><fileset dir="${dir.war}/image"/></copy>
<flexc-subproject name="MPLib"/>
<delete dir="${dir.flex.projects}/MPLib/src/image"/>
</target>
<target name="flexc-main">
<!--the link report is used to create the symbols in the main swf, and modules link against it-->
<property name="link.report" value="${dir.war}/abc_link_report.xml"/>
<!--modular.args is set in flexc-modularize. If not set, this sets it to an empty property-->
<property name="modular.args" value=""/>
<!--set up options specific for the main part and for the modules-->
<property name="main.args" value="-link-report=${link.report} ${modular.args}"/>
<property name="module.args" value="-load-externs=${link.report}"/>
<!--compile abc_flex.mxml here-->
<echo message="Compiling abc_flex application, sub-applications and modules..."/>
<echo/>
<flexc-mxml name="abc_flex" mxml.args="${flex.common.args} ${main.args}"
sourcePath="${dir.war}/abc_flex.mxml" destPath="${dir.war}/abc_flex${swf.suffix}.swf"/>
<!--compile MPMainSubApplication.mxml sub-application here-->
<flexc-mxml name="MPMainSubApplication" mxml.args="${flex.common.args} ${main.args}"
sourcePath="${dir.war}/MPMainSubApplication.mxml" destPath="${dir.war}/MPMainSubApplication.swf"/>
<!--compile internal modules next - just add new modules to the list here -->
<parallel> <!--do in parallel - it goes faster and they don't depend on each other-->
<property name="dir.module.src" value="${dir.war}/module/"/>
<flexc-mxml name="module1" sourcePath="${dir.module.src}/editor/Editor.mxml" destPath="${dir.module.src}/editor/Editor.swf" />
<flexc-mxml name="RunModule" sourcePath="${dir.module.src}/run/RunModule.mxml" destPath="${dir.module.src}/run/RunModule.swf" />
<!--<flexc-mxml name="JobManager" sourcePath="${dir.module.src}/jobmanager/JobManager.mxml" destPath="${dir.module.src}/jobmanager/JobManager.swf" />-->
<flexc-mxml name="Editor2" sourcePath="${dir.module.src}/edit/Editor.mxml" destPath="${dir.module.src}/edit/Editor.swf" />
</parallel>
</target>
```
NOTES:
I'm not sure if it's a good idea or not, but we just put the .swc files to include with our Java middle tier libs in WEB-INF/lib, so whenever we add a new flex lib to source control we just drop it in there. The compilation is done in the macros, and most of the parameters are defined as properties in the top section. The targets split the work because our app is quite large; you probably don't need those but it's an example of doing modules within sub-projects plus the link-report and follows the way a sub-project is referenced from the main application (I think). Our build machine is linux, so that's why the flexc.exe property (and others) are defined that way - it gets set at runtime. Names have been munged by hand for this answer, so please double-check for typos if you cut-n-paste anything.
Also, the incremental compilation isn't actually used; it seems to be buggy. Ditto for the modularization stuff, so I didn't include that target.
I built all of this myself so I'm rather proud of it, but if there's anything that looks iffy or smells bad, please feel free to let me know. Thanks!
|
1,439,713 |
I want to build an ant script that does exactly the same compilation actions on a Flash Builder 4 (Gumbo) project as the `Project->Export Release Build...` menu item does. My ant-fu is reasonably strong, that's not the issue, but rather I'm not sure exactly what that entry is doing.
Some details:
* I'll be using the 3.x SDK (say, 3.2 for the sake of specificity) to build this.
* I'll be building on a Mac, and I can happily use ant, make, or some weird shell script stuff if that's the way you roll.
* Any useful optimizations you can suggest will be welcome.
* The project contains a few assets, MXML and actionscript source, and a couple of .swcs that are built into the project (not RSL'd)
Can someone provide an ant build.xml or makefle that they use to build a release .swf file from a similar Flex project?
|
2009/09/17
|
[
"https://Stackoverflow.com/questions/1439713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
One quick way to know the compiler options is to add this tag into your compiler options:
-dump-config your/drive/to/store/the/xmlfile.xml
This will output the entire ant compiler options and you can copy off the parts you want to keep.
|
HellFire Compiler Daemon (<http://bytecode-workshop.com>/) can generate build.xml directly from the compiler calls made by Flex/Flash Builder. That means your ant script produces SWCs and SWFs based on the exact same set of compiler settings that you set in Flex/Flash Builder.
Also, check out this blog:
<http://stopcoding.wordpress.com/2010/01/15/ant-tasks-for-hfcd-now-available-2/>
|
40,358,562 |
I wish to use connection pooling using NodeJS with MySQL database. According to docs, there are two ways to do that: either I explicitly get connection from the pool, use it and release it:
```
var pool = require('mysql').createPool(opts);
pool.getConnection(function(err, conn) {
conn.query('select 1+1', function(err, res) {
conn.release();
});
});
```
Or I can use it like this:
```
var mysql = require('mysql');
var pool = mysql.createPool({opts});
pool.query('select 1+1', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
```
If I use the second options, does that mean, that connections are automatically pulled from the pool, used and released? And if so, is there reason to use the first approach?
|
2016/11/01
|
[
"https://Stackoverflow.com/questions/40358562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2882245/"
] |
Yes, the second one means that the pool is responsible to get the next free connection do a query on that and then release it again. You use this for *"one shot"* queries that have no dependencies.
You use the first one if you want to do multiple queries that depend on each other. A connection holds certain states, like locks, transaction, encoding, timezone, variables, ... .
Here an example that changes the used timezone:
```
pool.getConnection(function(err, conn) {
function setTimezone() {
// set the timezone for the this connection
conn.query("SET time_zone='+02:00'", queryData);
}
function queryData() {
conn.query( /* some query */, queryData);
}
function restoreTimezoneToUTC() {
// restore the timezone to UTC (or what ever you use as default)
// otherwise this one connection would use +02 for future request
// if it is reused in a future `getConnection`
conn.query("SET time_zone='+00:00'", releseQuery);
}
function releaseQuery() {
// return the query back to the pool
conn.release()
}
setTimezone();
});
```
|
In case anyone else stumbles upon this:
When you use pool.query you are in fact calling a shortcut which does what the first example does.
From the [readme](https://github.com/mysqljs/mysql#pooling-connections):
>
> This is a shortcut for the pool.getConnection() -> connection.query() -> connection.release() code flow. Using pool.getConnection() is useful to share connection state for subsequent queries. This is because two calls to pool.query() may use two different connections and run in parallel.
>
>
>
So yes, the second one is also calling connection.release() you just don't need to type it.
|
57,832,193 |
The footer disappears when trying to get the "back to top" to the right-hand side just above the footer. I want to try to get the button just above the footer.
Before I implemented the "back to top" button I was also having difficulty with it not being aligned correctly, as it not covering the left-side of the page on the bottom.
Also I've tried to find solutions to this but the ones I've found use javascript/jquery and I've got to make this using only html and css.
Edit: I've removed the unnecessary stuff, left the table in, as I think that's what's causing the problem as it doesn't scale well on the smaller screens. Also forgot to mention earlier it also results in the navbar having space left over to the top-right corner, which is why I've left that in as well.
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="test.css" type="text/css" rel="stylesheet">
<a name="top"></a>
<div class="nav">
<input type="checkbox" id="nav-check">
<div class="nav-header">
<div class="nav-title">
<a href="index.html" class="active">Link1</a>
</div>
</div>
<div class="nav-btn">
<label for="nav-check">
<span></span>
<span></span>
<span></span>
</label>
</div>
<div class="nav-links">
<a href="#">Link2</a>
<a href="#">Link3</a>
<a href="#">Link4</a>
</div>
</div>
<h1>Comments</h1>
<table id = "table">
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td>html</td>
<td>Element</td>
<td>fdsfdddddddddddd ddddddd dffdfds fdfds</td>
</tr>
<tr>
<td>html</td>
<td>Element</td>
<td>fdsfdddddddddddd ddddddd dffdfds fdfds</td>
</tr>
<tr>
<td>html</td>
<td>Element</td>
<td>fdsfdddddddddddd ddddddd dffdfds fdfds</td>
</tr>
</table>
</td>
</tr>
<div class="btopbutton">
<a href="#top">Back to top</a>
<div>
<div class="footer">
<p><span> Website | Website | Copyright 2019</span></p>
<a href="#"> Link 1 </a> | <a href="#">Link 2</a> | <a href="#">Link 3</a> | <a href="#">Link 4</a></div>
</div>
</body></html>
@charset "UTF-8";
/*set background for whole page*/
html {
background-color: #26734d;
scroll-behavior: smooth;
margin: 0;
padding: 0;
width: 100%;
height: 100%;}
/*--start of nav bar--*/
* {
box-sizing: border-box;
}
.nav {
/* height: 50px;*/
width: 100%;
background-color: #4d4d4d;
position: relative;
}
.nav > .nav-header {
display: inline;
}
.nav > .nav-header > .nav-title {
display: inline-block;
font-size: 22px;
color: #fff;
padding: 10px 10px 10px 10px;
}
.nav > .nav-btn {
display: none;
}
.nav > .nav-links {
display: inline;
float: center;
font-size: 18px;
}
.nav > .nav-links > a {
display: inline-block;
padding: 13px 10px 13px 10px;
text-decoration: none;
color: #efefef;
text-transform: uppercase;
}
.nav > .nav-links > a:hover {
font-weight: bold;
/* background-color: rgba(0, 0, 0, 0.3);*/
}
:any-link {
color: #efefef;
text-decoration: none;
text-transform: uppercase;
font-size: 18px;
}
:any-link:hover {
font-weight: bold;
cursor: pointer;
}
.nav > #nav-check {
display: none;
}
/*--end of nav bar--*/
.heading1{
color:#FFFFFF;
}
/* Style the validation */
#validation{
text-align:center;
padding: 10px 10px;
}
.footer {
text-align: center;
padding-top:20px;
padding-bottom: 20px;
background-color: #1B1B1B;
color: #FFFFFF;
text-transform: uppercase;
font-weight: lighter;
letter-spacing: 2px;
border-top-width: 2px;
padding: 2px;
color:#ffffff;
width: 100%;
position: absolute;
font-weight: 200;
}
/*back to top button*/
.btopbutton
{
position: fixed;
bottom: 0;
right: 0;
text-align:right;
}
/*--table in comments section --*/
#table{
border: solid 1px black;
border-collapse: collapse;
width:100%;
text-align: center;
}
#table th{
border: solid 1px black;
border-collapse: collapse;
background-color: inherit;
}
#table td{
border: solid 1px black;
background-color: inherit;
border-collapse: collapse;
}
/*--end of table in the comments --*/
div.desc {
padding: 15px;
text-align: center;
}
* {
box-sizing: border-box;
}
.responsive {
padding: 0 6px;
float: left;
width: 24.99999%;
}
@media only screen and (max-width: 700px) {
.responsive {
width: 49.99999%;
margin: 6px 0;
}
}
@media only screen and (max-width: 500px) {
.responsive {
width: 100%;
}
.clearfix:after {
content: "";
display: table;
clear: both;
}
/* Moved Content Below Header */
.content {
margin-top:50px;
}
}
@media (max-width:600px) {
.nav > .nav-btn {
display: inline-block;
position: absolute;
right: 0px;
top: 0px;
}
.nav > .nav-btn > label {
display: inline-block;
width: 50px;
height: 50px;
padding: 13px;
}
.nav > .nav-btn > label:hover,.nav #nav-check:checked ~ .nav-btn > label {
background-color: rgba(0, 0, 0, 0.3);
}
.nav > .nav-btn > label > span {
display: block;
width: 25px;
height: 10px;
border-top: 2px solid #eee;
}
.nav > .nav-links {
display: block;
width: 100%;
background-color: #333;
height: 0px;
transition: all 0.3s ease-in;
overflow-y: hidden;
}
.nav > .nav-links > a {
display: block;
width: 100%;
}
.nav > #nav-check:not(:checked) ~ .nav-links {
height: 0px;
}
.nav > #nav-check:checked ~ .nav-links {
height: auto;
overflow-y: auto;
}
}
@media (max-width:300px){
#table p{
width:100%;
text-align: justify;
}
#table ul{
width: 58%
}
#table tr{
display: inline-flex;
width: 100%;
}
#table th{
width: 100%;
}
}
```
|
2019/09/07
|
[
"https://Stackoverflow.com/questions/57832193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12028650/"
] |
Using strongly typed datasets would make parts of this easier (Actually, they nearly always make all work with datatable and dataset easier; I would use them by default)
I would perform the following steps:
* Add a DataSet to your project
* Add a table to it (open it in the visual designer, right click the surface, add a datatable)
* Add your columns to the table and choose their data types (string, decimal etc) - right click the datatable and choose "add column"
* Right click the prodCode column and set it to be the primary key
* Set the Expression property of the Total column to be `[Qty] * [Price]` - it will now auto-calculate itself, so you don't need to do the calc in your code
In your code:
```
string prodCode = txtProductCode.Text;
decimal qty = Convert.ToInt32(txtQty.Text);
decimal price = Convert.ToInt32(txtPrice.Text);
//does the row exist?
var ro = dt.FindByProdCode(prodCode); //the typed datatable will have a FindByXX method generated on whatever column(s) are the primary key
if(ro != null){
ro.Price = price; //update the existing row
ro.Qty += qty;
} else {
dt.AddXXRow(prodCode, qty, price); //AddXXRow is generated for typed datatables depending on the table name
}
```
If you have a back end database related to these datatables, you life will get a lot easier if you connect your dataset to the database and have visual studio generate mappings between the dataset and the tables in the database. The TableAdapters it generates take the place of generic DataAdapters, and manage all the db connections, store the SQLs that retrieve and update the db etc.
|
You can use DataTable.NewRow() method to have a reference to the new row.
```
var rowNew = dt.NewRow()
...
dt.AddRow(rowNew);
```
Prefer using strong typed DataTable if the schema is not generated at runtime.
Also you can find an existing row using:
```
int found = -1;
for (int index = 0; i < dt.Count; index++)
{
if ( !condition ) continue;
found = index;
break;
}
```
Or use the Find() method.
|
57,832,193 |
The footer disappears when trying to get the "back to top" to the right-hand side just above the footer. I want to try to get the button just above the footer.
Before I implemented the "back to top" button I was also having difficulty with it not being aligned correctly, as it not covering the left-side of the page on the bottom.
Also I've tried to find solutions to this but the ones I've found use javascript/jquery and I've got to make this using only html and css.
Edit: I've removed the unnecessary stuff, left the table in, as I think that's what's causing the problem as it doesn't scale well on the smaller screens. Also forgot to mention earlier it also results in the navbar having space left over to the top-right corner, which is why I've left that in as well.
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="test.css" type="text/css" rel="stylesheet">
<a name="top"></a>
<div class="nav">
<input type="checkbox" id="nav-check">
<div class="nav-header">
<div class="nav-title">
<a href="index.html" class="active">Link1</a>
</div>
</div>
<div class="nav-btn">
<label for="nav-check">
<span></span>
<span></span>
<span></span>
</label>
</div>
<div class="nav-links">
<a href="#">Link2</a>
<a href="#">Link3</a>
<a href="#">Link4</a>
</div>
</div>
<h1>Comments</h1>
<table id = "table">
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td>html</td>
<td>Element</td>
<td>fdsfdddddddddddd ddddddd dffdfds fdfds</td>
</tr>
<tr>
<td>html</td>
<td>Element</td>
<td>fdsfdddddddddddd ddddddd dffdfds fdfds</td>
</tr>
<tr>
<td>html</td>
<td>Element</td>
<td>fdsfdddddddddddd ddddddd dffdfds fdfds</td>
</tr>
</table>
</td>
</tr>
<div class="btopbutton">
<a href="#top">Back to top</a>
<div>
<div class="footer">
<p><span> Website | Website | Copyright 2019</span></p>
<a href="#"> Link 1 </a> | <a href="#">Link 2</a> | <a href="#">Link 3</a> | <a href="#">Link 4</a></div>
</div>
</body></html>
@charset "UTF-8";
/*set background for whole page*/
html {
background-color: #26734d;
scroll-behavior: smooth;
margin: 0;
padding: 0;
width: 100%;
height: 100%;}
/*--start of nav bar--*/
* {
box-sizing: border-box;
}
.nav {
/* height: 50px;*/
width: 100%;
background-color: #4d4d4d;
position: relative;
}
.nav > .nav-header {
display: inline;
}
.nav > .nav-header > .nav-title {
display: inline-block;
font-size: 22px;
color: #fff;
padding: 10px 10px 10px 10px;
}
.nav > .nav-btn {
display: none;
}
.nav > .nav-links {
display: inline;
float: center;
font-size: 18px;
}
.nav > .nav-links > a {
display: inline-block;
padding: 13px 10px 13px 10px;
text-decoration: none;
color: #efefef;
text-transform: uppercase;
}
.nav > .nav-links > a:hover {
font-weight: bold;
/* background-color: rgba(0, 0, 0, 0.3);*/
}
:any-link {
color: #efefef;
text-decoration: none;
text-transform: uppercase;
font-size: 18px;
}
:any-link:hover {
font-weight: bold;
cursor: pointer;
}
.nav > #nav-check {
display: none;
}
/*--end of nav bar--*/
.heading1{
color:#FFFFFF;
}
/* Style the validation */
#validation{
text-align:center;
padding: 10px 10px;
}
.footer {
text-align: center;
padding-top:20px;
padding-bottom: 20px;
background-color: #1B1B1B;
color: #FFFFFF;
text-transform: uppercase;
font-weight: lighter;
letter-spacing: 2px;
border-top-width: 2px;
padding: 2px;
color:#ffffff;
width: 100%;
position: absolute;
font-weight: 200;
}
/*back to top button*/
.btopbutton
{
position: fixed;
bottom: 0;
right: 0;
text-align:right;
}
/*--table in comments section --*/
#table{
border: solid 1px black;
border-collapse: collapse;
width:100%;
text-align: center;
}
#table th{
border: solid 1px black;
border-collapse: collapse;
background-color: inherit;
}
#table td{
border: solid 1px black;
background-color: inherit;
border-collapse: collapse;
}
/*--end of table in the comments --*/
div.desc {
padding: 15px;
text-align: center;
}
* {
box-sizing: border-box;
}
.responsive {
padding: 0 6px;
float: left;
width: 24.99999%;
}
@media only screen and (max-width: 700px) {
.responsive {
width: 49.99999%;
margin: 6px 0;
}
}
@media only screen and (max-width: 500px) {
.responsive {
width: 100%;
}
.clearfix:after {
content: "";
display: table;
clear: both;
}
/* Moved Content Below Header */
.content {
margin-top:50px;
}
}
@media (max-width:600px) {
.nav > .nav-btn {
display: inline-block;
position: absolute;
right: 0px;
top: 0px;
}
.nav > .nav-btn > label {
display: inline-block;
width: 50px;
height: 50px;
padding: 13px;
}
.nav > .nav-btn > label:hover,.nav #nav-check:checked ~ .nav-btn > label {
background-color: rgba(0, 0, 0, 0.3);
}
.nav > .nav-btn > label > span {
display: block;
width: 25px;
height: 10px;
border-top: 2px solid #eee;
}
.nav > .nav-links {
display: block;
width: 100%;
background-color: #333;
height: 0px;
transition: all 0.3s ease-in;
overflow-y: hidden;
}
.nav > .nav-links > a {
display: block;
width: 100%;
}
.nav > #nav-check:not(:checked) ~ .nav-links {
height: 0px;
}
.nav > #nav-check:checked ~ .nav-links {
height: auto;
overflow-y: auto;
}
}
@media (max-width:300px){
#table p{
width:100%;
text-align: justify;
}
#table ul{
width: 58%
}
#table tr{
display: inline-flex;
width: 100%;
}
#table th{
width: 100%;
}
}
```
|
2019/09/07
|
[
"https://Stackoverflow.com/questions/57832193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12028650/"
] |
Using strongly typed datasets would make parts of this easier (Actually, they nearly always make all work with datatable and dataset easier; I would use them by default)
I would perform the following steps:
* Add a DataSet to your project
* Add a table to it (open it in the visual designer, right click the surface, add a datatable)
* Add your columns to the table and choose their data types (string, decimal etc) - right click the datatable and choose "add column"
* Right click the prodCode column and set it to be the primary key
* Set the Expression property of the Total column to be `[Qty] * [Price]` - it will now auto-calculate itself, so you don't need to do the calc in your code
In your code:
```
string prodCode = txtProductCode.Text;
decimal qty = Convert.ToInt32(txtQty.Text);
decimal price = Convert.ToInt32(txtPrice.Text);
//does the row exist?
var ro = dt.FindByProdCode(prodCode); //the typed datatable will have a FindByXX method generated on whatever column(s) are the primary key
if(ro != null){
ro.Price = price; //update the existing row
ro.Qty += qty;
} else {
dt.AddXXRow(prodCode, qty, price); //AddXXRow is generated for typed datatables depending on the table name
}
```
If you have a back end database related to these datatables, you life will get a lot easier if you connect your dataset to the database and have visual studio generate mappings between the dataset and the tables in the database. The TableAdapters it generates take the place of generic DataAdapters, and manage all the db connections, store the SQLs that retrieve and update the db etc.
|
You can loop the whole datagridview rows and check if there is existing row with same new row product code, if yes update the columns you want of this row. This is not tested but something like this:
```
string prodCode = txtProductCode.Text;
decimal qty = Convert.ToInt32(txtQty.Text);
decimal price = Convert.ToInt32(txtPrice.Text);
decimal total = qty*price;
bool isRowExist = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value.ToString().Equals(prodCode))
{
var totalQty = Convert.ToInt32(row.Cells[1].Value.ToString()) + qty ;
var updateTotal = Convert.ToInt32(row.Cells[3].Value.ToString()) + total ;
row.Cells[1].Value = totalQty;
row.Cells[3].Value = total;
isRowExist = true
}
}
if(!isRowExist)
dt.Rows.Add(prodCode,qty,price,total);
```
|
185,728 |
I wrote a function in python to count the number of 1-bits in a sorted bit array. I'm basically using binary search but the code seems unnecessarily long and awkward. I did test it for several different cases and got the correct output but am looking to write a cleaner code if possible.
Note: I want to use a binary-search inspired solution that theoretically takes O(lg n ) time.
```
def countOnes(arr):
l, r = 0, len(arr)-1
while l <= r:
mid = l + (r-l)/2
if mid == 0 and arr[mid] == 1:
return len(arr)
if mid == len(arr)-1 and arr[mid] == 0:
return 0
if arr[mid] == 1 and arr[mid-1] == 0:
return len(arr) - mid
elif arr[mid] == 1 and arr[mid-1] == 1:
r = mid - 1
elif arr[mid] == 0 and arr[mid+1] == 1:
return len(arr) - (mid+1)
else:
l = mid + 1
print countOnes([0, 0, 0]) # got 0
print countOnes([0, 0, 1, 1]) # got 2
print countOnes([1, 1, 1, 1]) # got 4
print countOnes([0, 1, 1, 1]) # got 3
print countONes([1, 1, 1, 1, 1]) # got 5
```
|
2018/01/22
|
[
"https://codereview.stackexchange.com/questions/185728",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/78739/"
] |
I agree with your assessment of the code being *unnecessarily long and awkward*. It looks like the root cause is an opportunistic optimization.
The bad news is that most of the secondary tests (like `arr[mid - 1] == 0` and `arr[mid - 1] == 1`) are bound to fail, so not only they contribute to awkwardness of the code - they also hurt the performance (by about a factor of 2, if I am not mistaken).
I recommend to keep it simple, and test only what is necessary:
```
l, r = 0, len(arr)
while l < r:
mid = l + (r - l) // 2
if arr[mid] == 1:
r = mid
else:
l = mid + 1
return len(arr) - l
```
Notice that working on a semi-open range (that is, `mid` is *beyond* the range) also makes it cleaner.
|
You can't get much simpler than:
```
sum(arr)
```
This has the benefit of working even if the array isn't sorted.
|
185,728 |
I wrote a function in python to count the number of 1-bits in a sorted bit array. I'm basically using binary search but the code seems unnecessarily long and awkward. I did test it for several different cases and got the correct output but am looking to write a cleaner code if possible.
Note: I want to use a binary-search inspired solution that theoretically takes O(lg n ) time.
```
def countOnes(arr):
l, r = 0, len(arr)-1
while l <= r:
mid = l + (r-l)/2
if mid == 0 and arr[mid] == 1:
return len(arr)
if mid == len(arr)-1 and arr[mid] == 0:
return 0
if arr[mid] == 1 and arr[mid-1] == 0:
return len(arr) - mid
elif arr[mid] == 1 and arr[mid-1] == 1:
r = mid - 1
elif arr[mid] == 0 and arr[mid+1] == 1:
return len(arr) - (mid+1)
else:
l = mid + 1
print countOnes([0, 0, 0]) # got 0
print countOnes([0, 0, 1, 1]) # got 2
print countOnes([1, 1, 1, 1]) # got 4
print countOnes([0, 1, 1, 1]) # got 3
print countONes([1, 1, 1, 1, 1]) # got 5
```
|
2018/01/22
|
[
"https://codereview.stackexchange.com/questions/185728",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/78739/"
] |
This removes the learning part of this (if your goal is to try to learn to implement a binary search in this context), but I contend the most pythonic solution would be to use [`bisect.bisect_right`](https://docs.python.org/3/library/bisect.html#bisect.bisect_right). It gives you the rightmost insertion point for a value via binary search. The rightmost insertion point for a `0` would be the number of zeros, so you just subtract this from the length to get the number of ones:
```
from bisect import bisect_right
def count_ones(bits):
return len(bits) - bisect_right(bits, 0)
```
Some notes:
* Use PEP8 style, `snake_case` function names
* Add a `"""Docstring."""`
* I think `bits` is a more descriptive name than `arr`
* If counting is such a core operation, you should wrap this array in a class that counts the number as you modify the array
* An array is a pretty sparsely packed representation of a bitfield. The [bitarray package](https://pypi.python.org/pypi/bitarray/) is a more efficient C implementation (spacewise). What's fantastic about it is that it conforms to the `list` API, so you should in theory be able to just pass a `bitarray` into `count_ones` instead of a `list` and it will just work™
* You could potentially squeeze more performance out of this if needed. By representing it as a `bytearray`, you'd want to find the first non-zero byte (which can be achieved by `bisect_right(bits, 0)`) and then check the next one to see how many bits into it the first `1` is. This has the advantage of avoiding the shifting and anding to extract specific bits at each point considered by the binary search. The downside here is you loose the ability to address individual bits using a list like interface (and doing the `|` and `<<` in python may be slower than `bitarray`s C implementation). But that all said, you'd definitely want to benchmark; this is just a guess.
**Edit:** Dug a little bit into that last point. Turns out you can do `.tobytes()` which returns a reference to the backing bytes of the `bitarray`. So, you could do the `bisect_right` on it as described above (for what I would imagine would be a faster binary search), but still have the advantage of treating the DS like a list of bits (with operations at the speed the C implementation).
|
You can't get much simpler than:
```
sum(arr)
```
This has the benefit of working even if the array isn't sorted.
|
185,728 |
I wrote a function in python to count the number of 1-bits in a sorted bit array. I'm basically using binary search but the code seems unnecessarily long and awkward. I did test it for several different cases and got the correct output but am looking to write a cleaner code if possible.
Note: I want to use a binary-search inspired solution that theoretically takes O(lg n ) time.
```
def countOnes(arr):
l, r = 0, len(arr)-1
while l <= r:
mid = l + (r-l)/2
if mid == 0 and arr[mid] == 1:
return len(arr)
if mid == len(arr)-1 and arr[mid] == 0:
return 0
if arr[mid] == 1 and arr[mid-1] == 0:
return len(arr) - mid
elif arr[mid] == 1 and arr[mid-1] == 1:
r = mid - 1
elif arr[mid] == 0 and arr[mid+1] == 1:
return len(arr) - (mid+1)
else:
l = mid + 1
print countOnes([0, 0, 0]) # got 0
print countOnes([0, 0, 1, 1]) # got 2
print countOnes([1, 1, 1, 1]) # got 4
print countOnes([0, 1, 1, 1]) # got 3
print countONes([1, 1, 1, 1, 1]) # got 5
```
|
2018/01/22
|
[
"https://codereview.stackexchange.com/questions/185728",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/78739/"
] |
I agree with your assessment of the code being *unnecessarily long and awkward*. It looks like the root cause is an opportunistic optimization.
The bad news is that most of the secondary tests (like `arr[mid - 1] == 0` and `arr[mid - 1] == 1`) are bound to fail, so not only they contribute to awkwardness of the code - they also hurt the performance (by about a factor of 2, if I am not mistaken).
I recommend to keep it simple, and test only what is necessary:
```
l, r = 0, len(arr)
while l < r:
mid = l + (r - l) // 2
if arr[mid] == 1:
r = mid
else:
l = mid + 1
return len(arr) - l
```
Notice that working on a semi-open range (that is, `mid` is *beyond* the range) also makes it cleaner.
|
This removes the learning part of this (if your goal is to try to learn to implement a binary search in this context), but I contend the most pythonic solution would be to use [`bisect.bisect_right`](https://docs.python.org/3/library/bisect.html#bisect.bisect_right). It gives you the rightmost insertion point for a value via binary search. The rightmost insertion point for a `0` would be the number of zeros, so you just subtract this from the length to get the number of ones:
```
from bisect import bisect_right
def count_ones(bits):
return len(bits) - bisect_right(bits, 0)
```
Some notes:
* Use PEP8 style, `snake_case` function names
* Add a `"""Docstring."""`
* I think `bits` is a more descriptive name than `arr`
* If counting is such a core operation, you should wrap this array in a class that counts the number as you modify the array
* An array is a pretty sparsely packed representation of a bitfield. The [bitarray package](https://pypi.python.org/pypi/bitarray/) is a more efficient C implementation (spacewise). What's fantastic about it is that it conforms to the `list` API, so you should in theory be able to just pass a `bitarray` into `count_ones` instead of a `list` and it will just work™
* You could potentially squeeze more performance out of this if needed. By representing it as a `bytearray`, you'd want to find the first non-zero byte (which can be achieved by `bisect_right(bits, 0)`) and then check the next one to see how many bits into it the first `1` is. This has the advantage of avoiding the shifting and anding to extract specific bits at each point considered by the binary search. The downside here is you loose the ability to address individual bits using a list like interface (and doing the `|` and `<<` in python may be slower than `bitarray`s C implementation). But that all said, you'd definitely want to benchmark; this is just a guess.
**Edit:** Dug a little bit into that last point. Turns out you can do `.tobytes()` which returns a reference to the backing bytes of the `bitarray`. So, you could do the `bisect_right` on it as described above (for what I would imagine would be a faster binary search), but still have the advantage of treating the DS like a list of bits (with operations at the speed the C implementation).
|
46,339 |
I'm running F17 and inside of `yum.repos.d`. I see multiple repos listed like `adobe-linux-1386.repo`, `fedora.repo`, `google-chrome.repo`, etc. When I `yum install` are some files being downloaded from multiple different repos or all from one?
|
2012/08/26
|
[
"https://unix.stackexchange.com/questions/46339",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/22122/"
] |
Most packages would be downloaded from fedora.repo. Adobe packages would be downloaded from adobe-linux-i386.repo. Google Chrome packages would be downloaded from google-chrome.repo
|
Also depends on whether a repo is disabled or enabled.
|
46,339 |
I'm running F17 and inside of `yum.repos.d`. I see multiple repos listed like `adobe-linux-1386.repo`, `fedora.repo`, `google-chrome.repo`, etc. When I `yum install` are some files being downloaded from multiple different repos or all from one?
|
2012/08/26
|
[
"https://unix.stackexchange.com/questions/46339",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/22122/"
] |
Most of the repositories specify a `mirrorlist` in their configuration file. When present, `yum` will select one or more of the mirrors provided by the list. Repos that don't have mirrors will have `baseurl` instead of `mirrorlist`.
When downloading multiple packages, yum can download from multiple sites in parallel, though this isn't always obvious in the terminal unless you watch very carefully.
|
Most packages would be downloaded from fedora.repo. Adobe packages would be downloaded from adobe-linux-i386.repo. Google Chrome packages would be downloaded from google-chrome.repo
|
46,339 |
I'm running F17 and inside of `yum.repos.d`. I see multiple repos listed like `adobe-linux-1386.repo`, `fedora.repo`, `google-chrome.repo`, etc. When I `yum install` are some files being downloaded from multiple different repos or all from one?
|
2012/08/26
|
[
"https://unix.stackexchange.com/questions/46339",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/22122/"
] |
Most packages would be downloaded from fedora.repo. Adobe packages would be downloaded from adobe-linux-i386.repo. Google Chrome packages would be downloaded from google-chrome.repo
|
Normally the contents of repository do not have the same rpms (like in your example). If you had "conflicting" rpms you can use yum\_priorities to choose which one to use first.
But in the end a single rpm will be downloaded from a single (mirror)-server that is mentioned in a single repository (directly or via mirror-list).
|
46,339 |
I'm running F17 and inside of `yum.repos.d`. I see multiple repos listed like `adobe-linux-1386.repo`, `fedora.repo`, `google-chrome.repo`, etc. When I `yum install` are some files being downloaded from multiple different repos or all from one?
|
2012/08/26
|
[
"https://unix.stackexchange.com/questions/46339",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/22122/"
] |
Most of the repositories specify a `mirrorlist` in their configuration file. When present, `yum` will select one or more of the mirrors provided by the list. Repos that don't have mirrors will have `baseurl` instead of `mirrorlist`.
When downloading multiple packages, yum can download from multiple sites in parallel, though this isn't always obvious in the terminal unless you watch very carefully.
|
Also depends on whether a repo is disabled or enabled.
|
46,339 |
I'm running F17 and inside of `yum.repos.d`. I see multiple repos listed like `adobe-linux-1386.repo`, `fedora.repo`, `google-chrome.repo`, etc. When I `yum install` are some files being downloaded from multiple different repos or all from one?
|
2012/08/26
|
[
"https://unix.stackexchange.com/questions/46339",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/22122/"
] |
Most of the repositories specify a `mirrorlist` in their configuration file. When present, `yum` will select one or more of the mirrors provided by the list. Repos that don't have mirrors will have `baseurl` instead of `mirrorlist`.
When downloading multiple packages, yum can download from multiple sites in parallel, though this isn't always obvious in the terminal unless you watch very carefully.
|
Normally the contents of repository do not have the same rpms (like in your example). If you had "conflicting" rpms you can use yum\_priorities to choose which one to use first.
But in the end a single rpm will be downloaded from a single (mirror)-server that is mentioned in a single repository (directly or via mirror-list).
|
35,045,808 |
The problem I am facing is that, given a list and a guard condition, I must verify if every element in the list passes the guard condition.
If even one of the elements fails the guard check, then the function should return `false`. If all of them pass the guard check, then the function should return `true`. The restriction on this problem is that **I can only use a single return statement**.
My code:
```
def todos_lista(lista, guarda):
for x in lista:
return(False if guarda(x)==False else True)
```
|
2016/01/27
|
[
"https://Stackoverflow.com/questions/35045808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5588032/"
] |
You should use [all](https://docs.python.org/2/library/functions.html#all):
```
def todos_lista(lista, guarda):
return all(guarda(x) for x in lista)
```
Or in a more functional way:
```
def todos_lista(lista, guarda):
return all(map(guarda, lista))
```
For example for range 0 to 9 (`range(10)`):
```
>>> all(x < 10 for x in range(10))
True
>>> all(x < 9 for x in range(10))
False
>>> all(map(lambda x: x < 9, range(10)))
False
>>> all(map(lambda x: x < 10, range(10)))
True
```
|
`any` will do the job as well:
```
def todos_lista(lista, guarda):
return not any(not guarda(x) for x in lista)
```
|
10,972,246 |
I've built a site <http://ucemeche.weebly.com> , Now I want to transfer it on other server. <http://Weebly.com> provides a function to download whole site in zip format that I've done.
But problem is when I am browsing that downloaded site the slide shows, photo gallery etc are not working in as working in live site. Perhaps it is related to java script.
Why is it happening ? What is the solution ?
|
2012/06/10
|
[
"https://Stackoverflow.com/questions/10972246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447820/"
] |
Check the paths of the javascripts. You might be missing some scripts or you do not include them properly.
Check the error console in your browser. Most likely it will show you what's wrong.
|
You simply have to change the paths to the images in the html file
the paths will be something like:
```
"2\/1\/2\/5\/56254238\/3375189.png"
```
change them to:
```
"..\/folder name where your files are\/uploads\/2\/1\/2\/5\/56254238\/3375189.png"
```
|
10,972,246 |
I've built a site <http://ucemeche.weebly.com> , Now I want to transfer it on other server. <http://Weebly.com> provides a function to download whole site in zip format that I've done.
But problem is when I am browsing that downloaded site the slide shows, photo gallery etc are not working in as working in live site. Perhaps it is related to java script.
Why is it happening ? What is the solution ?
|
2012/06/10
|
[
"https://Stackoverflow.com/questions/10972246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447820/"
] |
Check the paths of the javascripts. You might be missing some scripts or you do not include them properly.
Check the error console in your browser. Most likely it will show you what's wrong.
|
This was three years ago, so perhaps this is a late answer. There is a hosted file slideshow-jq.js. In it, there is a function largeURL(photo).
Copy that slideshow-jq.js into the root of your zip, and edit the file:
`url = '/uploads/' + url.replace(/^\/uploads\//, '');`
Remove the leading / in front of uploads.
Now, update your page and look for this line:
`<script src="http://cdn2.editmysite.com/js/site/main.js?buildTime=1234"></script><script type='text/javascript' src='http://cdn1.editmysite.com/editor/libraries/slideshow-jq.js?buildTime=1234'></script>`
Or something like that. Change the src to the local file, "./slideshow-jq.js"
That corrects the issue.
|
38,448,193 |
I tried doing this in python, but I get an error:
```
import numpy as np
array_to_filter = np.array([1,2,3,4,5])
equal_array = np.array([1,2,5,5,5])
array_to_filter[equal_array]
```
and this results in:
```
IndexError: index 5 is out of bounds for axis 0 with size 5
```
What gives? I thought I was doing the right operation here.
I am expecting that if I do
```
array_to_filter[equal_array]
```
That it would return
```
np.array([1,2,5])
```
If I am not on the right track, how would I get it to do that?
|
2016/07/19
|
[
"https://Stackoverflow.com/questions/38448193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4054573/"
] |
The regex: <http://regexr.com/3dr56>
Will match any nodes that consist of say the following:
`<div>hello world</div>`
Provided that the parameters passed to the function:
```js
function removeNode(str, nodeName) {
var pattern = '<'+nodeName+'>[\\s\\w]+<\/'+nodeName+'>';
var regex = new RegExp(pattern, 'gi');
return str.replace(regex, '').replace(/^\s*[\r\n]/gm, '');
}
console.log("Node: <div>hello world</div>");
var str = removeNode("hello world", "div");
console.log("String returned: " + str);
```
are:
Node match: `<div>hello world</div>`
`removeNode("hello world", "div");` will return:
`hello world`
The function itself will return the `string` within the node.
More info can be found here about [Regular Expressions](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions).
|
For what it's worth here's a solution done using only jQuery.
You could do something similar with a server side XML parser
**Data used for search and replace:**
```
// selector = jQuery selector, final = replacement element
var tags = [{
selector: 'emphasis[Type="Italic"]',
final: '<i>'
}, {
selector: 'emphasis[Type="Bold"]',
final: '<strong>'// note <b> is deprecated
}, {
selector: 'emphasis[Type="Underline"]',
final: '<u>'
}, {
selector: 'para',
final: '<p>'
}
];
```
**Parser:**
```
$(function() {
// get string to parse
var str = $('#txtArea').val();
// inject in temporary div
var $tempdiv = $('<div>').html(str);
// loop over all the tags to replace
$.each(tags, function(_, tag) {
// loop and replace instances of tags
$tempdiv.find(tag.selector).replaceWith(function() {
return $(tag.final).html( $(this).html())
});
});
// get final string from temp div
var finalString = $tempdiv.html()
// update textarea
$('#final').val(finalString );
});
```
`**[DEMO](http://plnkr.co/edit/Er1VWWIpwE9eKZvhsPTh?p=preview)**`
|
21,344,684 |
I've been wrestling with this for several days and have extensively dug through StackOverflow and various other sites. I'm literally drawing a blank. I'm trying to get a single result back from my stored procedure.
Here's my stored procedure:
```
ALTER PROC [dbo].[myHelper_Simulate]
@CCOID nvarchar(100), @RVal nvarchar OUTPUT
AS
DECLARE @UserID int
DECLARE @GUID uniqueidentifier
SELECT @UserID = UserID
FROM [User]
WHERE CCOID = @CCOID AND deleted = 0
SELECT @GUID = newid()
IF @UserID > 0
BEGIN
INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level)
VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success')
SELECT @RVal = 'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50))
RETURN
END
ELSE
SELECT @RVal = 'Couldn''t find a user record for the CCOID ' + @CCOID
RETURN
GO
```
Originally the procedure was written to print out the result. I've added the `@RVal` and the `RETURN` in an attempt to get the value to pass back to my C# code.
Here's my C# routine (`svrConn` has already been connected to the database):
```
private void btnSimulate_MouseClick(object sender, MouseEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = svrConn;
object result = new object();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + tDatabase + "].[dbo].myHelper_Simulate";
cmd.Parameters.Add(new SqlParameter("@CCOID", txtDUserCCOID.Text.Trim()));
cmd.Parameters.Add(new SqlParameter("@RVal", ""));
cmd.Parameters.Add(new SqlParameter("RETURN_VALUE", SqlDbType.NVarChar)).Direction = ParameterDirection.ReturnValue;
try
{
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (result != null)
{
tString = result.ToString();
MessageBox.Show(tString);
}
}
```
The problem is that `result` is coming back null. I'm not sure if it's due to the stored procedure or how I'm setting my parameters and calling `ExecuteScalar`.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21344684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693895/"
] |
[SP return values](http://technet.microsoft.com/en-us/library/ms174998.aspx) are integers and are meant for error code. The correct way is to use `OUTPUT` parameter. You are assigning it correctly in the SP, you don't need the return statements.
In your C# code check the value after execution. Use `ExecuteNonQuery` as there is no result set from the SP.
```
var rval = new SqlParameter("@RVal", SqlDbType.NVarChar);
rval.Direction = ParameterDirection.Output;
cmd.Parameters.Add(rval);
cmd.ExecuteNonQuery();
result = rval.Value;
```
|
try
```
private void btnSimulate_MouseClick(object sender, EventArgs e) {
using (SqlConnection con = svrConn) {
using (SqlCommand cmd = new SqlCommand("myHelper_Simulate", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@CCOID", SqlDbType.VarChar).Value = txtDUserCCOID.Text.Trim();
var output = new SqlParameter("@RVal", SqlDbType.VarChar);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
```
|
21,344,684 |
I've been wrestling with this for several days and have extensively dug through StackOverflow and various other sites. I'm literally drawing a blank. I'm trying to get a single result back from my stored procedure.
Here's my stored procedure:
```
ALTER PROC [dbo].[myHelper_Simulate]
@CCOID nvarchar(100), @RVal nvarchar OUTPUT
AS
DECLARE @UserID int
DECLARE @GUID uniqueidentifier
SELECT @UserID = UserID
FROM [User]
WHERE CCOID = @CCOID AND deleted = 0
SELECT @GUID = newid()
IF @UserID > 0
BEGIN
INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level)
VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success')
SELECT @RVal = 'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50))
RETURN
END
ELSE
SELECT @RVal = 'Couldn''t find a user record for the CCOID ' + @CCOID
RETURN
GO
```
Originally the procedure was written to print out the result. I've added the `@RVal` and the `RETURN` in an attempt to get the value to pass back to my C# code.
Here's my C# routine (`svrConn` has already been connected to the database):
```
private void btnSimulate_MouseClick(object sender, MouseEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = svrConn;
object result = new object();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[" + tDatabase + "].[dbo].myHelper_Simulate";
cmd.Parameters.Add(new SqlParameter("@CCOID", txtDUserCCOID.Text.Trim()));
cmd.Parameters.Add(new SqlParameter("@RVal", ""));
cmd.Parameters.Add(new SqlParameter("RETURN_VALUE", SqlDbType.NVarChar)).Direction = ParameterDirection.ReturnValue;
try
{
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (result != null)
{
tString = result.ToString();
MessageBox.Show(tString);
}
}
```
The problem is that `result` is coming back null. I'm not sure if it's due to the stored procedure or how I'm setting my parameters and calling `ExecuteScalar`.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21344684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693895/"
] |
Don't need the return parameters or output parameters. ExecuteScalar returns the first column of the first row of your result set. So just select the text you want to return, like so...
```
IF @UserID > 0
BEGIN
INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level)
VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success')
SELECT 'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50))
END
ELSE
SELECT 'Couldn''t find a user record for the CCOID ' + @CCOID
RETURN
```
|
try
```
private void btnSimulate_MouseClick(object sender, EventArgs e) {
using (SqlConnection con = svrConn) {
using (SqlCommand cmd = new SqlCommand("myHelper_Simulate", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@CCOID", SqlDbType.VarChar).Value = txtDUserCCOID.Text.Trim();
var output = new SqlParameter("@RVal", SqlDbType.VarChar);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
```
|
61,015,445 |
I'm using [custom-elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) aka web-components within [Preact](https://preactjs.com/). The problem is that Typescript complains about elements not being defined in `JSX.IntrinsicElements` - in this case a `check-box` element:
```html
<div className={styles.option}>
<check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
<p>Dark theme</p>
</div>
```
Error message (path omitted):
```
ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.
```
I came across the following, unfortunately not working, possible solutions:
1. <https://stackoverflow.com/a/57449556/7664765> *- It's an answer not really realted to the question but it covered my problem*
I've tried adding the following to my `typings.d.ts` file:
```js
import * as Preact from 'preact';
declare global {
namespace JSX {
interface IntrinsicElements {
'check-box': any; // The 'any' just for testing purposes
}
}
}
```
My IDE grayed out the import part and `IntrinsicElements` which means it's not used (?!) and it didn't worked anyway. I'm still getting the same error message.
2. <https://stackoverflow.com/a/55424778/7664765> *- Also for react, I've tried to "convert" it to preact and I got the same results as for 1.*
I've even found a [file](https://github.com/GoogleChromeLabs/squoosh/blob/master/src/custom-els/RangeInput/missing-types.d.ts) maintained by google in the [squoosh](https://github.com/GoogleChromeLabs/squoosh) project where they did the following to "polyfill" the support:
>
> In the same folder as the component a `missing-types.d.ts` file with the following content, basically the same setup I have but with a `index.ts` file instead of `check-bock.ts` and they're using an older TS version `v3.5.3`:
>
>
>
```js
declare namespace JSX {
interface IntrinsicElements {
'range-input': HTMLAttributes;
}
}
```
I'm assuming their build didn't fail so how does it work and how do I properly define custom-elements to use them within preact / react components?
I'm currently using `typescript@v3.8.3` and `preact@10.3.4`.
|
2020/04/03
|
[
"https://Stackoverflow.com/questions/61015445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664765/"
] |
Okay I managed to solve it using [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation):
```
declare module 'preact/src/jsx' {
namespace JSXInternal {
// We're extending the IntrinsicElements interface which holds a kv-list of
// available html-tags.
interface IntrinsicElements {
'check-box': unknown;
}
}
}
```
Using the `HTMLAttributes` interface we can tell JSX which attributes are available for our custom-element:
```
// Your .ts file, e.g. index.ts
declare module 'preact/src/jsx' {
namespace JSXInternal {
import HTMLAttributes = JSXInternal.HTMLAttributes;
interface IntrinsicElements {
'check-box': HTMLAttributes<CheckBoxElement>;
}
}
}
// This interface describes our custom element, holding all its
// available attributes. This should be placed within a .d.ts file.
declare interface CheckBoxElement extends HTMLElement {
checked: boolean;
}
```
|
With typescript 4.2.3 and preact 10.5.13, here is what works to define a custom tag name with attributes:
```
declare module 'preact' {
namespace JSX {
interface IntrinsicElements {
'overlay-trigger': OverlayTriggerAttributes;
}
}
}
interface OverlayTriggerAttributes extends preact.JSX.HTMLAttributes<HTMLElement> {
placement?: string;
}
```
Differences:
* The module is `'preact'` (must be quoted).
* The namespace is `JSX`.
* The `IntrinsicElements` value type is an interface that extends HTMLAttributes.
* It extends HTMLAttributes via the name `preact.JSX.HTMLAttributes`.
* It supplies the base element type as `HTMLElement` to populate the eventTarget type in props/attrs like event listeners. You could also put `SVGElement` if applicable.
|
61,015,445 |
I'm using [custom-elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) aka web-components within [Preact](https://preactjs.com/). The problem is that Typescript complains about elements not being defined in `JSX.IntrinsicElements` - in this case a `check-box` element:
```html
<div className={styles.option}>
<check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
<p>Dark theme</p>
</div>
```
Error message (path omitted):
```
ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.
```
I came across the following, unfortunately not working, possible solutions:
1. <https://stackoverflow.com/a/57449556/7664765> *- It's an answer not really realted to the question but it covered my problem*
I've tried adding the following to my `typings.d.ts` file:
```js
import * as Preact from 'preact';
declare global {
namespace JSX {
interface IntrinsicElements {
'check-box': any; // The 'any' just for testing purposes
}
}
}
```
My IDE grayed out the import part and `IntrinsicElements` which means it's not used (?!) and it didn't worked anyway. I'm still getting the same error message.
2. <https://stackoverflow.com/a/55424778/7664765> *- Also for react, I've tried to "convert" it to preact and I got the same results as for 1.*
I've even found a [file](https://github.com/GoogleChromeLabs/squoosh/blob/master/src/custom-els/RangeInput/missing-types.d.ts) maintained by google in the [squoosh](https://github.com/GoogleChromeLabs/squoosh) project where they did the following to "polyfill" the support:
>
> In the same folder as the component a `missing-types.d.ts` file with the following content, basically the same setup I have but with a `index.ts` file instead of `check-bock.ts` and they're using an older TS version `v3.5.3`:
>
>
>
```js
declare namespace JSX {
interface IntrinsicElements {
'range-input': HTMLAttributes;
}
}
```
I'm assuming their build didn't fail so how does it work and how do I properly define custom-elements to use them within preact / react components?
I'm currently using `typescript@v3.8.3` and `preact@10.3.4`.
|
2020/04/03
|
[
"https://Stackoverflow.com/questions/61015445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664765/"
] |
Okay I managed to solve it using [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation):
```
declare module 'preact/src/jsx' {
namespace JSXInternal {
// We're extending the IntrinsicElements interface which holds a kv-list of
// available html-tags.
interface IntrinsicElements {
'check-box': unknown;
}
}
}
```
Using the `HTMLAttributes` interface we can tell JSX which attributes are available for our custom-element:
```
// Your .ts file, e.g. index.ts
declare module 'preact/src/jsx' {
namespace JSXInternal {
import HTMLAttributes = JSXInternal.HTMLAttributes;
interface IntrinsicElements {
'check-box': HTMLAttributes<CheckBoxElement>;
}
}
}
// This interface describes our custom element, holding all its
// available attributes. This should be placed within a .d.ts file.
declare interface CheckBoxElement extends HTMLElement {
checked: boolean;
}
```
|
There is a better way to do this without manually binding events.
You can use `@lit-labs/react`'s `createComponent` to wrap web component to React Component.
```js
import * as React from "react";
import { createComponent } from "@lit-labs/react";
import Slrange from "@shoelace-style/shoelace/dist/components/range/range.js";
export const Range = createComponent(React, "sl-range", Slrange,{
change: "sl-change" // map web component event to react event
});
```
```js
import { Range } from "./SlRange";
export default function App() {
return (
<div className="App">
<Range max={6} min={2} step={2}></Range>
</div>
);
}
```
[](https://codesandbox.io/s/react-web-component-g2p3y?fontsize=14&hidenavigation=1&theme=dark)
|
61,015,445 |
I'm using [custom-elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) aka web-components within [Preact](https://preactjs.com/). The problem is that Typescript complains about elements not being defined in `JSX.IntrinsicElements` - in this case a `check-box` element:
```html
<div className={styles.option}>
<check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
<p>Dark theme</p>
</div>
```
Error message (path omitted):
```
ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.
```
I came across the following, unfortunately not working, possible solutions:
1. <https://stackoverflow.com/a/57449556/7664765> *- It's an answer not really realted to the question but it covered my problem*
I've tried adding the following to my `typings.d.ts` file:
```js
import * as Preact from 'preact';
declare global {
namespace JSX {
interface IntrinsicElements {
'check-box': any; // The 'any' just for testing purposes
}
}
}
```
My IDE grayed out the import part and `IntrinsicElements` which means it's not used (?!) and it didn't worked anyway. I'm still getting the same error message.
2. <https://stackoverflow.com/a/55424778/7664765> *- Also for react, I've tried to "convert" it to preact and I got the same results as for 1.*
I've even found a [file](https://github.com/GoogleChromeLabs/squoosh/blob/master/src/custom-els/RangeInput/missing-types.d.ts) maintained by google in the [squoosh](https://github.com/GoogleChromeLabs/squoosh) project where they did the following to "polyfill" the support:
>
> In the same folder as the component a `missing-types.d.ts` file with the following content, basically the same setup I have but with a `index.ts` file instead of `check-bock.ts` and they're using an older TS version `v3.5.3`:
>
>
>
```js
declare namespace JSX {
interface IntrinsicElements {
'range-input': HTMLAttributes;
}
}
```
I'm assuming their build didn't fail so how does it work and how do I properly define custom-elements to use them within preact / react components?
I'm currently using `typescript@v3.8.3` and `preact@10.3.4`.
|
2020/04/03
|
[
"https://Stackoverflow.com/questions/61015445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664765/"
] |
Here are the correct attributes to use, otherwise you will get an error when passing `key` in for example.
```js
declare global {
namespace JSX {
interface IntrinsicElements {
'xx-element1': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>; // Normal web component
'xx-element2': React.DetailedHTMLProps<React.HTMLAttributes<HTMLInputElement>, HTMLInputElement>; // Web component extended from input
}
}
}
```
|
With typescript 4.2.3 and preact 10.5.13, here is what works to define a custom tag name with attributes:
```
declare module 'preact' {
namespace JSX {
interface IntrinsicElements {
'overlay-trigger': OverlayTriggerAttributes;
}
}
}
interface OverlayTriggerAttributes extends preact.JSX.HTMLAttributes<HTMLElement> {
placement?: string;
}
```
Differences:
* The module is `'preact'` (must be quoted).
* The namespace is `JSX`.
* The `IntrinsicElements` value type is an interface that extends HTMLAttributes.
* It extends HTMLAttributes via the name `preact.JSX.HTMLAttributes`.
* It supplies the base element type as `HTMLElement` to populate the eventTarget type in props/attrs like event listeners. You could also put `SVGElement` if applicable.
|
61,015,445 |
I'm using [custom-elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) aka web-components within [Preact](https://preactjs.com/). The problem is that Typescript complains about elements not being defined in `JSX.IntrinsicElements` - in this case a `check-box` element:
```html
<div className={styles.option}>
<check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
<p>Dark theme</p>
</div>
```
Error message (path omitted):
```
ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.
```
I came across the following, unfortunately not working, possible solutions:
1. <https://stackoverflow.com/a/57449556/7664765> *- It's an answer not really realted to the question but it covered my problem*
I've tried adding the following to my `typings.d.ts` file:
```js
import * as Preact from 'preact';
declare global {
namespace JSX {
interface IntrinsicElements {
'check-box': any; // The 'any' just for testing purposes
}
}
}
```
My IDE grayed out the import part and `IntrinsicElements` which means it's not used (?!) and it didn't worked anyway. I'm still getting the same error message.
2. <https://stackoverflow.com/a/55424778/7664765> *- Also for react, I've tried to "convert" it to preact and I got the same results as for 1.*
I've even found a [file](https://github.com/GoogleChromeLabs/squoosh/blob/master/src/custom-els/RangeInput/missing-types.d.ts) maintained by google in the [squoosh](https://github.com/GoogleChromeLabs/squoosh) project where they did the following to "polyfill" the support:
>
> In the same folder as the component a `missing-types.d.ts` file with the following content, basically the same setup I have but with a `index.ts` file instead of `check-bock.ts` and they're using an older TS version `v3.5.3`:
>
>
>
```js
declare namespace JSX {
interface IntrinsicElements {
'range-input': HTMLAttributes;
}
}
```
I'm assuming their build didn't fail so how does it work and how do I properly define custom-elements to use them within preact / react components?
I'm currently using `typescript@v3.8.3` and `preact@10.3.4`.
|
2020/04/03
|
[
"https://Stackoverflow.com/questions/61015445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664765/"
] |
Here are the correct attributes to use, otherwise you will get an error when passing `key` in for example.
```js
declare global {
namespace JSX {
interface IntrinsicElements {
'xx-element1': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>; // Normal web component
'xx-element2': React.DetailedHTMLProps<React.HTMLAttributes<HTMLInputElement>, HTMLInputElement>; // Web component extended from input
}
}
}
```
|
There is a better way to do this without manually binding events.
You can use `@lit-labs/react`'s `createComponent` to wrap web component to React Component.
```js
import * as React from "react";
import { createComponent } from "@lit-labs/react";
import Slrange from "@shoelace-style/shoelace/dist/components/range/range.js";
export const Range = createComponent(React, "sl-range", Slrange,{
change: "sl-change" // map web component event to react event
});
```
```js
import { Range } from "./SlRange";
export default function App() {
return (
<div className="App">
<Range max={6} min={2} step={2}></Range>
</div>
);
}
```
[](https://codesandbox.io/s/react-web-component-g2p3y?fontsize=14&hidenavigation=1&theme=dark)
|
61,015,445 |
I'm using [custom-elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) aka web-components within [Preact](https://preactjs.com/). The problem is that Typescript complains about elements not being defined in `JSX.IntrinsicElements` - in this case a `check-box` element:
```html
<div className={styles.option}>
<check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
<p>Dark theme</p>
</div>
```
Error message (path omitted):
```
ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.
```
I came across the following, unfortunately not working, possible solutions:
1. <https://stackoverflow.com/a/57449556/7664765> *- It's an answer not really realted to the question but it covered my problem*
I've tried adding the following to my `typings.d.ts` file:
```js
import * as Preact from 'preact';
declare global {
namespace JSX {
interface IntrinsicElements {
'check-box': any; // The 'any' just for testing purposes
}
}
}
```
My IDE grayed out the import part and `IntrinsicElements` which means it's not used (?!) and it didn't worked anyway. I'm still getting the same error message.
2. <https://stackoverflow.com/a/55424778/7664765> *- Also for react, I've tried to "convert" it to preact and I got the same results as for 1.*
I've even found a [file](https://github.com/GoogleChromeLabs/squoosh/blob/master/src/custom-els/RangeInput/missing-types.d.ts) maintained by google in the [squoosh](https://github.com/GoogleChromeLabs/squoosh) project where they did the following to "polyfill" the support:
>
> In the same folder as the component a `missing-types.d.ts` file with the following content, basically the same setup I have but with a `index.ts` file instead of `check-bock.ts` and they're using an older TS version `v3.5.3`:
>
>
>
```js
declare namespace JSX {
interface IntrinsicElements {
'range-input': HTMLAttributes;
}
}
```
I'm assuming their build didn't fail so how does it work and how do I properly define custom-elements to use them within preact / react components?
I'm currently using `typescript@v3.8.3` and `preact@10.3.4`.
|
2020/04/03
|
[
"https://Stackoverflow.com/questions/61015445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664765/"
] |
With typescript 4.2.3 and preact 10.5.13, here is what works to define a custom tag name with attributes:
```
declare module 'preact' {
namespace JSX {
interface IntrinsicElements {
'overlay-trigger': OverlayTriggerAttributes;
}
}
}
interface OverlayTriggerAttributes extends preact.JSX.HTMLAttributes<HTMLElement> {
placement?: string;
}
```
Differences:
* The module is `'preact'` (must be quoted).
* The namespace is `JSX`.
* The `IntrinsicElements` value type is an interface that extends HTMLAttributes.
* It extends HTMLAttributes via the name `preact.JSX.HTMLAttributes`.
* It supplies the base element type as `HTMLElement` to populate the eventTarget type in props/attrs like event listeners. You could also put `SVGElement` if applicable.
|
There is a better way to do this without manually binding events.
You can use `@lit-labs/react`'s `createComponent` to wrap web component to React Component.
```js
import * as React from "react";
import { createComponent } from "@lit-labs/react";
import Slrange from "@shoelace-style/shoelace/dist/components/range/range.js";
export const Range = createComponent(React, "sl-range", Slrange,{
change: "sl-change" // map web component event to react event
});
```
```js
import { Range } from "./SlRange";
export default function App() {
return (
<div className="App">
<Range max={6} min={2} step={2}></Range>
</div>
);
}
```
[](https://codesandbox.io/s/react-web-component-g2p3y?fontsize=14&hidenavigation=1&theme=dark)
|
1,668,531 |
What are some key bindings that aren't included?
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178019/"
] |
You can find the complete list of limitations in MonoTouch at [Xamarin](http://docs.xamarin.com/ios/about/limitations).
A short list of .NET features not available in MonoTouch:
* The Dynamic Language Runtime (DLR)
* Generic Virtual Methods
* P/Invokes in Generic Types
* Value types as Dictionary Keys
* System.Reflection.Emit
* System.Runtime.Remoting
|
Here is a link of the assemblies that it ships with: <http://docs.xamarin.com/ios/about/assemblies>
Here is a summary of the .Net framework assemblies:
>
> **mscorlib.dll**
>
> *Silverlight, plus several .NET 4.0 types*
>
>
> **System.dll**
>
> *Silverlight, plus types from the following namespaces:*
>
> System.Collections.Specialized
>
> System.ComponentModel
>
> System.ComponentModel.Design
>
> System.Diagnostics
>
> System.IO.Compression
>
> System.Net
>
> System.Net.Cache
>
> System.Net.Mail
>
> System.Net.Mime
>
> System.Net.NetworkInformation
>
> System.Net.Security
>
> System.Net.Sockets
>
> System.Security.Authentication
>
> System.Security.Cryptography
>
> System.Timers
>
>
> **System.Core.dll
>
> System.Data.dll
>
> System.Data.Services.Client.dll
>
> System.Json.dll
>
> System.Numerics.dll
>
> System.Runtime.Serialization.dll
>
> System.ServiceModel.dll
>
> System.ServiceModel.Web.dll
>
> System.Transactions.dll
>
> System.Web.Services
>
> System.Xml.dll
>
> System.Xml.Linq.dll**
>
>
>
|
1,668,531 |
What are some key bindings that aren't included?
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178019/"
] |
You can find the complete list of limitations in MonoTouch at [Xamarin](http://docs.xamarin.com/ios/about/limitations).
A short list of .NET features not available in MonoTouch:
* The Dynamic Language Runtime (DLR)
* Generic Virtual Methods
* P/Invokes in Generic Types
* Value types as Dictionary Keys
* System.Reflection.Emit
* System.Runtime.Remoting
|
One thing to also mention is you cannot reference .NET assemblies that haven't been built/compiled using the .NET MonoTouch configuration.
So if you have a favourite .NET 2.0 library you will need to re-import the source into a new MonoTouch project, compile it, and then reference it. There may be an easier way of doing this by editing the `.csproj` file but I haven't found it.
|
1,668,531 |
What are some key bindings that aren't included?
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178019/"
] |
Here is a link of the assemblies that it ships with: <http://docs.xamarin.com/ios/about/assemblies>
Here is a summary of the .Net framework assemblies:
>
> **mscorlib.dll**
>
> *Silverlight, plus several .NET 4.0 types*
>
>
> **System.dll**
>
> *Silverlight, plus types from the following namespaces:*
>
> System.Collections.Specialized
>
> System.ComponentModel
>
> System.ComponentModel.Design
>
> System.Diagnostics
>
> System.IO.Compression
>
> System.Net
>
> System.Net.Cache
>
> System.Net.Mail
>
> System.Net.Mime
>
> System.Net.NetworkInformation
>
> System.Net.Security
>
> System.Net.Sockets
>
> System.Security.Authentication
>
> System.Security.Cryptography
>
> System.Timers
>
>
> **System.Core.dll
>
> System.Data.dll
>
> System.Data.Services.Client.dll
>
> System.Json.dll
>
> System.Numerics.dll
>
> System.Runtime.Serialization.dll
>
> System.ServiceModel.dll
>
> System.ServiceModel.Web.dll
>
> System.Transactions.dll
>
> System.Web.Services
>
> System.Xml.dll
>
> System.Xml.Linq.dll**
>
>
>
|
One thing to also mention is you cannot reference .NET assemblies that haven't been built/compiled using the .NET MonoTouch configuration.
So if you have a favourite .NET 2.0 library you will need to re-import the source into a new MonoTouch project, compile it, and then reference it. There may be an easier way of doing this by editing the `.csproj` file but I haven't found it.
|
67,344,024 |
```py
@app.route('/')
def index():
return render_template("home.html")
```
My folder structure looks like this
```
tree-/
-static/
-styles.css
-templates/
-home.html
-app.py
```
I get
**Not Found**
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
On the browser and
```
127.0.0.1 - - [01/May/2021 09:41:47] "GET / HTTP/1.1" 404 -
```
In the debugger
Have looked at other related posts saying stuff about trailing slashes and it doesn't look like its making a difference, either I access
<http://127.0.0.1:5000>
or
<http://127.0.0.1:5000/>
I run my application using
```py
app = Flask(__name__)
if __name__ == '__main__':
app.run()
```
I get
```py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
```
```py
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
if __name__ == '__main__':
app.run()
@app.route('/')
def index():
return "Hello World"
```
|
2021/05/01
|
[
"https://Stackoverflow.com/questions/67344024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15778393/"
] |
Use conditional aggregation with a `having` clause:
```
select customer_id
from t
where location in ('Santa Clara', 'Milpitas')
group by customer_id
having max(store_entry) filter (where location = 'Santa Clara') >
min(store_entry) filter (where location = 'Milpitas');
```
Your statement is that the customer when to *after* Santa Clara *after* Milpitas. This leaves open the possibility that the customer visited both locations multiple times.
To meet the condition as stated, you need to know that some visit to Santa Clara was later than some visit to Milpitas (at least that is how I interpret the question). Well, that is true if the *lastest* visit to Santa Clara was after the *earliest* visit to Milpitas.
|
```
SELECT DISTINCT Customer_ID
FROM table t1
JOIN table t2 USING (Customer_ID)
WHERE t1.Location = 'Santa Clara'
AND t2.Location = 'Milpitas'
AND t1.Store_Entry > t2.Store_Entry
```
|
67,344,024 |
```py
@app.route('/')
def index():
return render_template("home.html")
```
My folder structure looks like this
```
tree-/
-static/
-styles.css
-templates/
-home.html
-app.py
```
I get
**Not Found**
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
On the browser and
```
127.0.0.1 - - [01/May/2021 09:41:47] "GET / HTTP/1.1" 404 -
```
In the debugger
Have looked at other related posts saying stuff about trailing slashes and it doesn't look like its making a difference, either I access
<http://127.0.0.1:5000>
or
<http://127.0.0.1:5000/>
I run my application using
```py
app = Flask(__name__)
if __name__ == '__main__':
app.run()
```
I get
```py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
```
```py
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
if __name__ == '__main__':
app.run()
@app.route('/')
def index():
return "Hello World"
```
|
2021/05/01
|
[
"https://Stackoverflow.com/questions/67344024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15778393/"
] |
```
SELECT DISTINCT Customer_ID
FROM table t1
JOIN table t2 USING (Customer_ID)
WHERE t1.Location = 'Santa Clara'
AND t2.Location = 'Milpitas'
AND t1.Store_Entry > t2.Store_Entry
```
|
Query For mySQL 8.0
```
WITH cte AS (
SELECT *, LEAD(region) OVER (PARTITION BY customer_id ORDER BY customer_id, store_entry) AS next_region
FROM tour_tab
)
SELECT customer_id
FROM cte
WHERE region=5 AND next_region=2 /* 'Santa Clara' AND 'Milpitas' */
```
|
67,344,024 |
```py
@app.route('/')
def index():
return render_template("home.html")
```
My folder structure looks like this
```
tree-/
-static/
-styles.css
-templates/
-home.html
-app.py
```
I get
**Not Found**
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
On the browser and
```
127.0.0.1 - - [01/May/2021 09:41:47] "GET / HTTP/1.1" 404 -
```
In the debugger
Have looked at other related posts saying stuff about trailing slashes and it doesn't look like its making a difference, either I access
<http://127.0.0.1:5000>
or
<http://127.0.0.1:5000/>
I run my application using
```py
app = Flask(__name__)
if __name__ == '__main__':
app.run()
```
I get
```py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
```
```py
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
if __name__ == '__main__':
app.run()
@app.route('/')
def index():
return "Hello World"
```
|
2021/05/01
|
[
"https://Stackoverflow.com/questions/67344024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15778393/"
] |
Use conditional aggregation with a `having` clause:
```
select customer_id
from t
where location in ('Santa Clara', 'Milpitas')
group by customer_id
having max(store_entry) filter (where location = 'Santa Clara') >
min(store_entry) filter (where location = 'Milpitas');
```
Your statement is that the customer when to *after* Santa Clara *after* Milpitas. This leaves open the possibility that the customer visited both locations multiple times.
To meet the condition as stated, you need to know that some visit to Santa Clara was later than some visit to Milpitas (at least that is how I interpret the question). Well, that is true if the *lastest* visit to Santa Clara was after the *earliest* visit to Milpitas.
|
Query For mySQL 8.0
```
WITH cte AS (
SELECT *, LEAD(region) OVER (PARTITION BY customer_id ORDER BY customer_id, store_entry) AS next_region
FROM tour_tab
)
SELECT customer_id
FROM cte
WHERE region=5 AND next_region=2 /* 'Santa Clara' AND 'Milpitas' */
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
You can use tuples which are hashable and [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter):
```
>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> multituples = [tuple(l) for l in multilist]
>>> from collections import Counter
>>> tc = Counter(multituples)
>>> tc
Counter({(5, 6): 3, (3, 4, 5): 2, (1, 2): 1})
```
To get the set of elements you just need the keys:
```
>>> tc.keys()
dict_keys([(1, 2), (3, 4, 5), (5, 6)])
```
|
---
You can try like this,
```
>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> c = [multilist.count(l) for l in multilist]
>>> for ind, l in enumerate(multilist):
... print( "%s: count %d times" % (str(l), c[ind]))
...
[1, 2]: count 1 times
[3, 4, 5]: count 2 times
[3, 4, 5]: count 2 times
[5, 6]: count 3 times
[5, 6]: count 3 times
[5, 6]: count 3 times
>>> {str(item): multilist.count(item) for item in multilist }
{'[1, 2]': 1, '[3, 4, 5]': 2, '[5, 6]': 3}
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
If you want to guarantee that the order of the unique items is the same as in the original list, you could do something like:
```
>>> class Seen(set):
... def __contains__(self, item):
... res = super(Seen, self).__contains__(item)
... self.add(item)
... return res
...
>>> seen = Seen()
>>> [item for item in multilist if tuple(item) not in seen]
[[1, 2], [3, 4, 5], [5, 6]]
>>>
```
|
As @ReutSharabani suggested, you can use tuples as dictionary keys, and then convert back to lists for display purposes. The code below doesn't reply on `collections` (not that there's anything wrong with that).
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
histogram = {}
for x in multilist:
xt = tuple(x)
if xt not in histogram:
histogram[xt] = 1
else:
histogram[xt] += 1
for k,c in histogram.items():
print "%r: count %d times" % (list(k),c)
print [list(x) for x in histogram.keys()]
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
If you want to guarantee that the order of the unique items is the same as in the original list, you could do something like:
```
>>> class Seen(set):
... def __contains__(self, item):
... res = super(Seen, self).__contains__(item)
... self.add(item)
... return res
...
>>> seen = Seen()
>>> [item for item in multilist if tuple(item) not in seen]
[[1, 2], [3, 4, 5], [5, 6]]
>>>
```
|
---
You can try like this,
```
>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> c = [multilist.count(l) for l in multilist]
>>> for ind, l in enumerate(multilist):
... print( "%s: count %d times" % (str(l), c[ind]))
...
[1, 2]: count 1 times
[3, 4, 5]: count 2 times
[3, 4, 5]: count 2 times
[5, 6]: count 3 times
[5, 6]: count 3 times
[5, 6]: count 3 times
>>> {str(item): multilist.count(item) for item in multilist }
{'[1, 2]': 1, '[3, 4, 5]': 2, '[5, 6]': 3}
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
How about using repr( alist) to convert it to its text string representation?
```
from collections import defaultdict
d = defaultdict(int)
for e in multilist: d[ repr(e)] += 1
for k,v in d.items(): print "{0}: count {1} times".format( k,v)
```
|
You can use a dictionary for this
```
count_data = {}
for my_list in multilist:
count_data.setdefault(tuple(my_list), 0)
count_data[tuple(my_list)] += 1
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
You can use tuples which are hashable and [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter):
```
>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> multituples = [tuple(l) for l in multilist]
>>> from collections import Counter
>>> tc = Counter(multituples)
>>> tc
Counter({(5, 6): 3, (3, 4, 5): 2, (1, 2): 1})
```
To get the set of elements you just need the keys:
```
>>> tc.keys()
dict_keys([(1, 2), (3, 4, 5), (5, 6)])
```
|
How about using repr( alist) to convert it to its text string representation?
```
from collections import defaultdict
d = defaultdict(int)
for e in multilist: d[ repr(e)] += 1
for k,v in d.items(): print "{0}: count {1} times".format( k,v)
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
---
You can try like this,
```
>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> c = [multilist.count(l) for l in multilist]
>>> for ind, l in enumerate(multilist):
... print( "%s: count %d times" % (str(l), c[ind]))
...
[1, 2]: count 1 times
[3, 4, 5]: count 2 times
[3, 4, 5]: count 2 times
[5, 6]: count 3 times
[5, 6]: count 3 times
[5, 6]: count 3 times
>>> {str(item): multilist.count(item) for item in multilist }
{'[1, 2]': 1, '[3, 4, 5]': 2, '[5, 6]': 3}
```
|
You can use a dictionary for this
```
count_data = {}
for my_list in multilist:
count_data.setdefault(tuple(my_list), 0)
count_data[tuple(my_list)] += 1
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
As @ReutSharabani suggested, you can use tuples as dictionary keys, and then convert back to lists for display purposes. The code below doesn't reply on `collections` (not that there's anything wrong with that).
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
histogram = {}
for x in multilist:
xt = tuple(x)
if xt not in histogram:
histogram[xt] = 1
else:
histogram[xt] += 1
for k,c in histogram.items():
print "%r: count %d times" % (list(k),c)
print [list(x) for x in histogram.keys()]
```
|
You can use a dictionary for this
```
count_data = {}
for my_list in multilist:
count_data.setdefault(tuple(my_list), 0)
count_data[tuple(my_list)] += 1
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
If you want to guarantee that the order of the unique items is the same as in the original list, you could do something like:
```
>>> class Seen(set):
... def __contains__(self, item):
... res = super(Seen, self).__contains__(item)
... self.add(item)
... return res
...
>>> seen = Seen()
>>> [item for item in multilist if tuple(item) not in seen]
[[1, 2], [3, 4, 5], [5, 6]]
>>>
```
|
You can use a dictionary for this
```
count_data = {}
for my_list in multilist:
count_data.setdefault(tuple(my_list), 0)
count_data[tuple(my_list)] += 1
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
You can use tuples which are hashable and [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter):
```
>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> multituples = [tuple(l) for l in multilist]
>>> from collections import Counter
>>> tc = Counter(multituples)
>>> tc
Counter({(5, 6): 3, (3, 4, 5): 2, (1, 2): 1})
```
To get the set of elements you just need the keys:
```
>>> tc.keys()
dict_keys([(1, 2), (3, 4, 5), (5, 6)])
```
|
As @ReutSharabani suggested, you can use tuples as dictionary keys, and then convert back to lists for display purposes. The code below doesn't reply on `collections` (not that there's anything wrong with that).
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
histogram = {}
for x in multilist:
xt = tuple(x)
if xt not in histogram:
histogram[xt] = 1
else:
histogram[xt] += 1
for k,c in histogram.items():
print "%r: count %d times" % (list(k),c)
print [list(x) for x in histogram.keys()]
```
|
32,250,035 |
I have a multi-dimensional list as like below
```
multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
```
How can I get below results fast:
```
[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times
```
and also get the unique multi-dimensional list (remove duplicates) :
```
multi_list = [[1,2],[3,4,5],[5,6]]
```
Thanks a lot.
|
2015/08/27
|
[
"https://Stackoverflow.com/questions/32250035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737273/"
] |
If you want to guarantee that the order of the unique items is the same as in the original list, you could do something like:
```
>>> class Seen(set):
... def __contains__(self, item):
... res = super(Seen, self).__contains__(item)
... self.add(item)
... return res
...
>>> seen = Seen()
>>> [item for item in multilist if tuple(item) not in seen]
[[1, 2], [3, 4, 5], [5, 6]]
>>>
```
|
How about using repr( alist) to convert it to its text string representation?
```
from collections import defaultdict
d = defaultdict(int)
for e in multilist: d[ repr(e)] += 1
for k,v in d.items(): print "{0}: count {1} times".format( k,v)
```
|
34,493,008 |
I need to use all the classes in one project in another. I tried adding the references, clicked on the project tab but I can't see the `.cs` or `.sln` files or any other files, just the exe in the debug folder and the `.vshost` file and the manifest file.
What file do I need to reference in the project?
|
2015/12/28
|
[
"https://Stackoverflow.com/questions/34493008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5717987/"
] |
File > Open > Project/Solution > Add to Solution (A little checkbox in the file dialog) then click the .sln you want
|
Right mouse click on the project that needs a reference to another project --> Add Reference --> Click the checkbox(es) next to each project you wish to refer.
[](https://i.stack.imgur.com/vzMDO.png)
Once you have added your reference you will need to include the namespace "using NamespaceOfSecondProject" in the class that will use the referred project.
|
34,493,008 |
I need to use all the classes in one project in another. I tried adding the references, clicked on the project tab but I can't see the `.cs` or `.sln` files or any other files, just the exe in the debug folder and the `.vshost` file and the manifest file.
What file do I need to reference in the project?
|
2015/12/28
|
[
"https://Stackoverflow.com/questions/34493008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5717987/"
] |
File > Open > Project/Solution > Add to Solution (A little checkbox in the file dialog) then click the .sln you want
|
You need to elaborate you question - Well why would you want to have redundant classes in two projects better build a class library and reference the dll in both the projects. If at all you need to include the classes from one project to another you simply need to copy the .cs file to other project and then select project and select add existing item then select the .cs file which you wanted to add. Hope this will help.
|
34,493,008 |
I need to use all the classes in one project in another. I tried adding the references, clicked on the project tab but I can't see the `.cs` or `.sln` files or any other files, just the exe in the debug folder and the `.vshost` file and the manifest file.
What file do I need to reference in the project?
|
2015/12/28
|
[
"https://Stackoverflow.com/questions/34493008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5717987/"
] |
Right mouse click on the project that needs a reference to another project --> Add Reference --> Click the checkbox(es) next to each project you wish to refer.
[](https://i.stack.imgur.com/vzMDO.png)
Once you have added your reference you will need to include the namespace "using NamespaceOfSecondProject" in the class that will use the referred project.
|
You need to elaborate you question - Well why would you want to have redundant classes in two projects better build a class library and reference the dll in both the projects. If at all you need to include the classes from one project to another you simply need to copy the .cs file to other project and then select project and select add existing item then select the .cs file which you wanted to add. Hope this will help.
|
24,377,354 |
I'm struggling to understand what this code does
```
ldi r20, 80
loop: asr r20
brsh loop
nop
```
What is this code doing and how many clock cycles does this code take to execute?
|
2014/06/24
|
[
"https://Stackoverflow.com/questions/24377354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3603183/"
] |
I routinely have
```
static Action<object> o = s => Console.WriteLine(s);
```
in my code which makes debug output so much less noisy. That way I can call Console's static Writeline() much easier. Would that help?
|
In C#? Not possible. Because it's a full OOP programming language and it was designed to work with objects you can't use functions outside the scope of an object. When calling static methods you have to specify the class where that static method lives...
```
Class.StaticMethod();
```
you can only use the short-hand notation if this method is call from within the same class...
```
StaticMethod();
```
But remember that you will not get access to instance members because static methods donot belong to instance of an object
Update based on comment
-----------------------
Looks like it will be possible to call static members without having to specify the class that declares it in C# 6, and you will be able to reference classes directly in `using` statements...in similar fashion to Java...[more info here](http://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Home)
|
24,377,354 |
I'm struggling to understand what this code does
```
ldi r20, 80
loop: asr r20
brsh loop
nop
```
What is this code doing and how many clock cycles does this code take to execute?
|
2014/06/24
|
[
"https://Stackoverflow.com/questions/24377354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3603183/"
] |
If you're looking to define a globally-scoped procedure then the short answer is no, you can't do this in c#. No global functions, procedures or objects.
In C# everything apart from namespaces and types (class, struct, enum, interface) must be defined inside a type. Static members (fields, properties and methods) can be used without an instance of the class, but only by referencing the type that owns them. Non-static members need an instance of the owning class.
This is fundamental to the syntax of the language. C# is neither C nor C++, where you *can* define global objects, functions and procedures.
|
In C#? Not possible. Because it's a full OOP programming language and it was designed to work with objects you can't use functions outside the scope of an object. When calling static methods you have to specify the class where that static method lives...
```
Class.StaticMethod();
```
you can only use the short-hand notation if this method is call from within the same class...
```
StaticMethod();
```
But remember that you will not get access to instance members because static methods donot belong to instance of an object
Update based on comment
-----------------------
Looks like it will be possible to call static members without having to specify the class that declares it in C# 6, and you will be able to reference classes directly in `using` statements...in similar fashion to Java...[more info here](http://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Home)
|
24,377,354 |
I'm struggling to understand what this code does
```
ldi r20, 80
loop: asr r20
brsh loop
nop
```
What is this code doing and how many clock cycles does this code take to execute?
|
2014/06/24
|
[
"https://Stackoverflow.com/questions/24377354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3603183/"
] |
using static yournamespace.yourclassname;
then call the static class method without class name;
Example:
Class1.cs
```
namespace WindowsFormsApplication1
{
class Utils
{
public static void Hello()
{
System.Diagnostics.Debug.WriteLine("Hello world!");
}
}
}
```
Form1.cs
```
using System.Windows.Forms;
using static WindowsFormsApplication1.Utils;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Hello(); // <====== LOOK HERE
}
}
}
```
|
In C#? Not possible. Because it's a full OOP programming language and it was designed to work with objects you can't use functions outside the scope of an object. When calling static methods you have to specify the class where that static method lives...
```
Class.StaticMethod();
```
you can only use the short-hand notation if this method is call from within the same class...
```
StaticMethod();
```
But remember that you will not get access to instance members because static methods donot belong to instance of an object
Update based on comment
-----------------------
Looks like it will be possible to call static members without having to specify the class that declares it in C# 6, and you will be able to reference classes directly in `using` statements...in similar fashion to Java...[more info here](http://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Home)
|
24,377,354 |
I'm struggling to understand what this code does
```
ldi r20, 80
loop: asr r20
brsh loop
nop
```
What is this code doing and how many clock cycles does this code take to execute?
|
2014/06/24
|
[
"https://Stackoverflow.com/questions/24377354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3603183/"
] |
using static yournamespace.yourclassname;
then call the static class method without class name;
Example:
Class1.cs
```
namespace WindowsFormsApplication1
{
class Utils
{
public static void Hello()
{
System.Diagnostics.Debug.WriteLine("Hello world!");
}
}
}
```
Form1.cs
```
using System.Windows.Forms;
using static WindowsFormsApplication1.Utils;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Hello(); // <====== LOOK HERE
}
}
}
```
|
I routinely have
```
static Action<object> o = s => Console.WriteLine(s);
```
in my code which makes debug output so much less noisy. That way I can call Console's static Writeline() much easier. Would that help?
|
24,377,354 |
I'm struggling to understand what this code does
```
ldi r20, 80
loop: asr r20
brsh loop
nop
```
What is this code doing and how many clock cycles does this code take to execute?
|
2014/06/24
|
[
"https://Stackoverflow.com/questions/24377354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3603183/"
] |
using static yournamespace.yourclassname;
then call the static class method without class name;
Example:
Class1.cs
```
namespace WindowsFormsApplication1
{
class Utils
{
public static void Hello()
{
System.Diagnostics.Debug.WriteLine("Hello world!");
}
}
}
```
Form1.cs
```
using System.Windows.Forms;
using static WindowsFormsApplication1.Utils;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Hello(); // <====== LOOK HERE
}
}
}
```
|
If you're looking to define a globally-scoped procedure then the short answer is no, you can't do this in c#. No global functions, procedures or objects.
In C# everything apart from namespaces and types (class, struct, enum, interface) must be defined inside a type. Static members (fields, properties and methods) can be used without an instance of the class, but only by referencing the type that owns them. Non-static members need an instance of the owning class.
This is fundamental to the syntax of the language. C# is neither C nor C++, where you *can* define global objects, functions and procedures.
|
58,106,488 |
Say I have a `Dockerfile` that will run a Ruby on Rails app:
```
FROM ruby:2.5.1
# - apt-get update, install nodejs, yarn, bundler, etc...
# - run yarn install, bundle install, etc...
# - create working directory and copy files
# ....
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
```
From my understanding, a container is an immutable running instance of an image and a set of runtime options (e.g. port mappings, volume mappings, networks, etc...).
So if I build and start a container from the above file, I'll get something that executes the default `CMD` above (`rails server`)
```
docker build -t myapp_web:latest
docker create --name myapp_web -p 3000:3000 -v $PWD:/app -e RAILS_ENV='production' myapp_web:latest
docker start myapp_web
```
Great, so now it's running `rails server` in a container that has a `CONTAINER_ID`.
But lets say tomorrow I want to run `rake db:migrate` because I updated something. How do I do that?
1. I can't use `docker exec` to run it in that container because `db:migrate` will fail while `rails server` is running
2. If I stop the `rails server` (and therefore the container) I have to create a *new container* with the same runtime options but a different command (`rake db:migrate`), which creates a new `CONTAINER_ID`. And then after runs that I have to restart my original container that runs `rails server`.
Is #2 just something we have to live with? Each new rake task I run that requires `rails server` to be shut down will have to create a new CONTAINER and these pile up over time. Is there a more "proper" way to run this?
Thanks!
*EDIT*: If #2 is the way to go, is there an easy way to create a new container from an existing container so I can copy over all the runtime configs and just change the command?
|
2019/09/25
|
[
"https://Stackoverflow.com/questions/58106488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490003/"
] |
You have to capture the event in your callback and get the value from it
```
sendData = e => {
this.props.parentCallback(e.target.value)
}
```
And change `onClick` to `onChange`
|
You can add a onChange attribute to the input field , this will handle the typing as an event.
```
const handleChange = ( event ) => {
console.log(event.target.value)
}
<input onChange={handleChange} type="text" name="name" id="myTextInput" />
```
|
58,106,488 |
Say I have a `Dockerfile` that will run a Ruby on Rails app:
```
FROM ruby:2.5.1
# - apt-get update, install nodejs, yarn, bundler, etc...
# - run yarn install, bundle install, etc...
# - create working directory and copy files
# ....
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
```
From my understanding, a container is an immutable running instance of an image and a set of runtime options (e.g. port mappings, volume mappings, networks, etc...).
So if I build and start a container from the above file, I'll get something that executes the default `CMD` above (`rails server`)
```
docker build -t myapp_web:latest
docker create --name myapp_web -p 3000:3000 -v $PWD:/app -e RAILS_ENV='production' myapp_web:latest
docker start myapp_web
```
Great, so now it's running `rails server` in a container that has a `CONTAINER_ID`.
But lets say tomorrow I want to run `rake db:migrate` because I updated something. How do I do that?
1. I can't use `docker exec` to run it in that container because `db:migrate` will fail while `rails server` is running
2. If I stop the `rails server` (and therefore the container) I have to create a *new container* with the same runtime options but a different command (`rake db:migrate`), which creates a new `CONTAINER_ID`. And then after runs that I have to restart my original container that runs `rails server`.
Is #2 just something we have to live with? Each new rake task I run that requires `rails server` to be shut down will have to create a new CONTAINER and these pile up over time. Is there a more "proper" way to run this?
Thanks!
*EDIT*: If #2 is the way to go, is there an easy way to create a new container from an existing container so I can copy over all the runtime configs and just change the command?
|
2019/09/25
|
[
"https://Stackoverflow.com/questions/58106488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490003/"
] |
You have to capture the event in your callback and get the value from it
```
sendData = e => {
this.props.parentCallback(e.target.value)
}
```
And change `onClick` to `onChange`
|
you should make the `handleChange()` function in `ChangeState` class and get the value.
***for example:***
```js
class ChangeState extends React.Component {
state = {value: ''};
handleChange = (e) => {
this.setState({value: e.target.value});
}
sendData = () => {
this.props.parentCallback(this.state.value);
}
render() {
return (
<div>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<button onClick={this.sendData}>
Click to send data from child to parent component
</button>
</div>
);
}
}
class Application extends React.Component {
state = {value: ''};
handleClick = (value) => {
this.setState({value});
}
render() {
return (
<div>
<ChangeState parentCallback={this.handleClick} />
<div style={{border: '1px solid red', width: '100%', height: 20}}>{this.state.value}</div>
</div>
);
}
}
React.render(<Application />, document.getElementById('app'));
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script>
<div id="app"></div>
```
|
2,864,016 |
I have some troubles with ssl using httpclient on android i am trying to access self signed certificate in details i want my app to trust all certificates ( i will use ssl only for data encryption). First i tried using this guide <http://hc.apache.org/httpclient-3.x/sslguide.html> on Desktop is working fine but on android i still got javax.net.ssl.SSLException: Not trusted server certificate. After searching in google i found some other examples how to enable ssl.
<http://groups.google.com/group/android-developers/browse_thread/thread/62d856cdcfa9f16e> - Working when i use URLConnection but with HttpClient still got the exception.
<http://www.discursive.com/books/cjcook/reference/http-webdav-sect-self-signed.html> - on Desktop using jars from apache is working but in android using included in SDK classes can't make it work.
<http://mail-archives.apache.org/mod_mbox/hc-httpclient-users/200808.mbox/%3C1218824624.6561.14.camel@ubuntu%3E> - also get the same exception
So any ideas how can i trust all certificates on android using HttpClient
|
2010/05/19
|
[
"https://Stackoverflow.com/questions/2864016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184601/"
] |
If you happen to look at the code of DefaultHttpClient, it looks something like this:
```
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(
new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager connManager = null;
HttpParams params = getParams();
...
}
```
Notice the mapping of https scheme to org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory().
You can create a custom implementation for `org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory` interface (<http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.html>) wherein, you can create `java.net.SSLSocket` with a custom `TrustManager` that accepts all certificate.
You may want to look into JSSE for more details at <http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html>
|
The key idea is to use a customized SSLSocketFactory implementing LayeredSocketFactory. The customized socket doesn't need to HostNameVerifier.
```
private static final class TrustAllSSLSocketFactory implements
LayeredSocketFactory {
private static final TrustAllSSLSocketFactory DEFAULT_FACTORY = new TrustAllSSLSocketFactory();
public static TrustAllSSLSocketFactory getSocketFactory() {
return DEFAULT_FACTORY;
}
private SSLContext sslcontext;
private javax.net.ssl.SSLSocketFactory socketfactory;
private TrustAllSSLSocketFactory() {
super();
TrustManager[] tm = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// do nothing
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// do nothing
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} };
try {
this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
this.sslcontext.init(null, tm, new SecureRandom());
this.socketfactory = this.sslcontext.getSocketFactory();
} catch ( NoSuchAlgorithmException e ) {
Log.e(LOG_TAG,
"Failed to instantiate TrustAllSSLSocketFactory!", e);
} catch ( KeyManagementException e ) {
Log.e(LOG_TAG,
"Failed to instantiate TrustAllSSLSocketFactory!", e);
}
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
socket, host, port, autoClose);
return sslSocket;
}
@Override
public Socket connectSocket(Socket sock, String host, int port,
InetAddress localAddress, int localPort, HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
if ( host == null ) {
throw new IllegalArgumentException(
"Target host may not be null.");
}
if ( params == null ) {
throw new IllegalArgumentException(
"Parameters may not be null.");
}
SSLSocket sslsock = (SSLSocket) ( ( sock != null ) ? sock
: createSocket() );
if ( ( localAddress != null ) || ( localPort > 0 ) ) {
// we need to bind explicitly
if ( localPort < 0 ) {
localPort = 0; // indicates "any"
}
InetSocketAddress isa = new InetSocketAddress(localAddress,
localPort);
sslsock.bind(isa);
}
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
InetSocketAddress remoteAddress;
remoteAddress = new InetSocketAddress(host, port);
sslsock.connect(remoteAddress, connTimeout);
sslsock.setSoTimeout(soTimeout);
return sslsock;
}
@Override
public Socket createSocket() throws IOException {
// the cast makes sure that the factory is working as expected
return (SSLSocket) this.socketfactory.createSocket();
}
@Override
public boolean isSecure(Socket sock) throws IllegalArgumentException {
return true;
}
}
```
You can then continue to use the customized SSLSocketFactory in the supported scheme registry.
```
private static final BasicHttpParams sHttpParams = new BasicHttpParams();
private static final SchemeRegistry sSupportedSchemes = new SchemeRegistry();
static {
sHttpParams.setParameter("http.socket.timeout", READ_TIMEOUT);
sHttpParams.setParameter("http.connection.timeout", CONNECT_TIMEOUT);
sSupportedSchemes.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
sSupportedSchemes.register(new Scheme("https",
TrustAllSSLSocketFactory.getSocketFactory(), 443));
}
```
|
2,864,016 |
I have some troubles with ssl using httpclient on android i am trying to access self signed certificate in details i want my app to trust all certificates ( i will use ssl only for data encryption). First i tried using this guide <http://hc.apache.org/httpclient-3.x/sslguide.html> on Desktop is working fine but on android i still got javax.net.ssl.SSLException: Not trusted server certificate. After searching in google i found some other examples how to enable ssl.
<http://groups.google.com/group/android-developers/browse_thread/thread/62d856cdcfa9f16e> - Working when i use URLConnection but with HttpClient still got the exception.
<http://www.discursive.com/books/cjcook/reference/http-webdav-sect-self-signed.html> - on Desktop using jars from apache is working but in android using included in SDK classes can't make it work.
<http://mail-archives.apache.org/mod_mbox/hc-httpclient-users/200808.mbox/%3C1218824624.6561.14.camel@ubuntu%3E> - also get the same exception
So any ideas how can i trust all certificates on android using HttpClient
|
2010/05/19
|
[
"https://Stackoverflow.com/questions/2864016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184601/"
] |
If you happen to look at the code of DefaultHttpClient, it looks something like this:
```
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(
new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager connManager = null;
HttpParams params = getParams();
...
}
```
Notice the mapping of https scheme to org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory().
You can create a custom implementation for `org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory` interface (<http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.html>) wherein, you can create `java.net.SSLSocket` with a custom `TrustManager` that accepts all certificate.
You may want to look into JSSE for more details at <http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html>
|
Rather than accepting all certificates, I recommend this solution: [Trusting all certificates using HttpClient over HTTPS](https://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/6378872#6378872)
|
4,987,429 |
I'm trying to make an array of hashes. This is my code. The $1, $2, etc are matched from a regular expression and I've checked they exist.
**Update:** Fixed my initial issue, but now I'm having the problem that my array is not growing beyond a size of 1 when I push items onto it...
**Update 2:** It is a scope issue, as the @ACLs needs to be declared outside the loop. Thanks everyone!
```
while (<>) {
chomp;
my @ACLs = ();
#Accept ACLs
if($_ =~ /access-list\s+\d+\s+(deny|permit)\s+(ip|udp|tcp|icmp)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\s+eq (\d+))?/i){
my %rule = (
action => $1,
protocol => $2,
srcip => $3,
srcmask => $4,
destip => $5,
destmask => $6,
);
if($8){
$rule{"port"} = $8;
}
push @ACLs, \%rule;
print "Got an ACL rule. Current number of rules:" . @ACLs . "\n";
```
The array of hashes doesn't seem to be getting any bigger.
|
2011/02/13
|
[
"https://Stackoverflow.com/questions/4987429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113705/"
] |
You are pushing `$rule`, which does not exist. You meant to push a reference to `%rule`:
```
push @ACLs, \%rule;
```
Always start your programs with `use strict; use warnings;`. That would have stopped you from trying to push `$rule`.
**Update:** In Perl, an array can only contain scalars. The way complex data structures are constructed is by having an array of hash references. Example:
```
my %hash0 = ( key0 => 1, key1 => 2 );
my %hash1 = ( key0 => 3, key1 => 4 );
my @array_of_hashes = ( \%hash0, \%hash1 );
# or: = ( { key0 => 1, key1 => 2 }, { key0 => 3, key1 => 4 ] );
print $array_of_hashes[0]{key1}; # prints 2
print $array_of_hashes[1]{key0}; # prints 3
```
Please read the [Perl Data Structures Cookbook](http://perldoc.perl.org/perldsc.html).
|
```
my %rule = [...]
push @ACLs, $rule;
```
These two lines refer to two separate variables: a hash and a scalar. They are not the same.
It depends on what you're waning to do, but there are two solutions:
```
push @ACLs, \%rule;
```
would push a reference into the array.
```
push @ACLs, %rule;
```
would push the individual values (as in `$key1`, `$value1`, `$key2`, `$value2`...) into the array.
|
4,987,429 |
I'm trying to make an array of hashes. This is my code. The $1, $2, etc are matched from a regular expression and I've checked they exist.
**Update:** Fixed my initial issue, but now I'm having the problem that my array is not growing beyond a size of 1 when I push items onto it...
**Update 2:** It is a scope issue, as the @ACLs needs to be declared outside the loop. Thanks everyone!
```
while (<>) {
chomp;
my @ACLs = ();
#Accept ACLs
if($_ =~ /access-list\s+\d+\s+(deny|permit)\s+(ip|udp|tcp|icmp)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\s+eq (\d+))?/i){
my %rule = (
action => $1,
protocol => $2,
srcip => $3,
srcmask => $4,
destip => $5,
destmask => $6,
);
if($8){
$rule{"port"} = $8;
}
push @ACLs, \%rule;
print "Got an ACL rule. Current number of rules:" . @ACLs . "\n";
```
The array of hashes doesn't seem to be getting any bigger.
|
2011/02/13
|
[
"https://Stackoverflow.com/questions/4987429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113705/"
] |
You are pushing `$rule`, which does not exist. You meant to push a reference to `%rule`:
```
push @ACLs, \%rule;
```
Always start your programs with `use strict; use warnings;`. That would have stopped you from trying to push `$rule`.
**Update:** In Perl, an array can only contain scalars. The way complex data structures are constructed is by having an array of hash references. Example:
```
my %hash0 = ( key0 => 1, key1 => 2 );
my %hash1 = ( key0 => 3, key1 => 4 );
my @array_of_hashes = ( \%hash0, \%hash1 );
# or: = ( { key0 => 1, key1 => 2 }, { key0 => 3, key1 => 4 ] );
print $array_of_hashes[0]{key1}; # prints 2
print $array_of_hashes[1]{key0}; # prints 3
```
Please read the [Perl Data Structures Cookbook](http://perldoc.perl.org/perldsc.html).
|
You’re clearing `@ACLs` each time through the loop. Your `my` is misplaced.
|
507,894 |
Is it safe if my server will create a SSH key pair for my client?
Scenario: I(server admin) will create a ssh key pair and put public key into authorized\_keys and give the private key to client so he can access my sftp server.
|
2019/03/22
|
[
"https://unix.stackexchange.com/questions/507894",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/343037/"
] |
Quick $0.02 because I've got to get ready for work:
Assuming this server isn't protecting actual banks or national security-level secrecy, you're fine.
About the only potential risk I can imagine from this is if a hostile third party intercepted enough of those private keys and the exact time they were generated, they could use that to make predictions about the state and algorhithm of the server's random number generator, which might be useful in some very sophisticated attacks.
... Of course, if they can intercept that many of your private keys you have *much bigger problems already*.
The safest thing to do would be to let the client generate the keypair and use a *trusted channel* to send you the public key for inclusion into the `authorized_keys` file, but if that isn't an option for whatever reason, your main worry is going to be how to securely get the private key to the recipient and *only* the intended recipient.
|
To allow access vith ssh/scp/sftp you can use public/private key pair. (\*)
I you generate and install such pair you will controll who will access a specific part of your server (in your case sftp directory).
If you have two or more customer/partner, be sure to generate one key per partner.
This way customer1 will access customer1's part. If set correctly (\*\*), private customer1's key will not access customer2's files, nor any other part of the server.
* (\*) assuming as noted by Shadur, that transfert is *safe* from prying eyes.
* (\*\*) using chroot if possible (this depend on your directory structure).
---
As noted in my (deleted) comment, this is also a matter of trust from customer's part, but that should be OK, customer already trust you with his file.
|
507,894 |
Is it safe if my server will create a SSH key pair for my client?
Scenario: I(server admin) will create a ssh key pair and put public key into authorized\_keys and give the private key to client so he can access my sftp server.
|
2019/03/22
|
[
"https://unix.stackexchange.com/questions/507894",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/343037/"
] |
Your customer should be **generating their own keys** and **securing them with a passphrase**, then giving you their **public key** to store on the server you manage and that they need to access. **Their private key should never be given to anyone and it should be encrypted** (i.e. secured with a passphrase).
|
To allow access vith ssh/scp/sftp you can use public/private key pair. (\*)
I you generate and install such pair you will controll who will access a specific part of your server (in your case sftp directory).
If you have two or more customer/partner, be sure to generate one key per partner.
This way customer1 will access customer1's part. If set correctly (\*\*), private customer1's key will not access customer2's files, nor any other part of the server.
* (\*) assuming as noted by Shadur, that transfert is *safe* from prying eyes.
* (\*\*) using chroot if possible (this depend on your directory structure).
---
As noted in my (deleted) comment, this is also a matter of trust from customer's part, but that should be OK, customer already trust you with his file.
|
55,093,954 |
I am new to Spring and Spring Boot and am working through a book that is full of missing information.
I have a taco class:
```
public class Taco {
...
@Size(min=1, message="You must choose at least 1 ingredient")
private List<Ingredient> ingredients;
...
}
```
As you can see `ingredients` is of type `List<Ingredient>` and that is the problem, it used to be of type `List<String>` but that was before I started saving data in the database, now it must be `List<Ingredient>` which breaks the whole thing.
In the contoller I have the following (among other things, I think this is the only required code for the problem at hand but if you need more let me know):
```
@ModelAttribute
public void addIngredientsToModel(Model model) {
List<Ingredient> ingredients = new ArrayList<>();
ingredientRepo.findAll().forEach(i -> ingredients.add(i));
Type[] types = Ingredient.Type.values();
for (Type type : types) {
model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
}
}
private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type) {
return ingredients
.stream()
.filter(x -> x.getType()
.equals(type))
.collect(Collectors.toList());
}
```
And finally in my thymeleaf file I have:
```
<span class="text-danger"
th:if="${#fields.hasErrors('ingredients')}"
th:errors="*{ingredients}">
</span>
```
Which causes the error:
```
thymeleaf Failed to convert property value of type java.lang.String to required type java.util.List
```
Once again, when `private List<Ingredient> ingredients;` was `private List<String> ingredients;` it worked, but now it must be `private List<Ingredient> ingredients;` because of the way it is saved in the database but it breaks at this point, how to fix it?
|
2019/03/11
|
[
"https://Stackoverflow.com/questions/55093954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9949924/"
] |
I met the same problem, what we need here is a converter.
```
package tacos.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import tacos.Ingredient;
import tacos.data.IngredientRepository;
@Component
public class IngredientByIdConverter implements Converter<String, Ingredient> {
private IngredientRepository ingredientRepo;
@Autowired
public IngredientByIdConverter(IngredientRepository ingredientRepo) {
this.ingredientRepo = ingredientRepo;
}
@Override
public Ingredient convert(String id) {
return ingredientRepo.findOne(id);
}
}
```
|
An optimisation of Ian's answer above:
Fetch the ingredients in the constructor of the converter.
```
package com.joeseff.xlabs.chtp01_1.tacos.converter;
import com.joeseff.xlabs.chtp01_1.tacos.model.Ingredient;
import com.joeseff.xlabs.chtp01_1.tacos.respository.jdbc.IngredientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author - JoeSeff
* @created - 23/09/2020 13:41
*/
@Component
public class IngredientConverter implements Converter<String, Ingredient> {
private final IngredientRepository ingredientRepo;
private final List<Ingredient> ingredients = new ArrayList<>();
@Autowired
public IngredientConverter(IngredientRepository ingredientRepo) {
this.ingredientRepo = ingredientRepo;
ingredientRepo.findAll().forEach(ingredients::add);
}
@Override
public Ingredient convert(String ingredientId) {
return ingredients
.stream().filter( i -> i.getId().equals(ingredientId))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Ingredient with ID '" + ingredientId + "' not found!"));
}
}
```
|
7,921,457 |
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/>
any idea?
tnx - luke
|
2011/10/27
|
[
"https://Stackoverflow.com/questions/7921457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998967/"
] |
You're allocating a huge array in stack:
```
int prime[2000000]={};
```
Four bytes times two million equals eight megabytes, which is often the maximum stack size. Allocating more than that results in segmentation fault.
You should allocate the array in heap, instead:
```
int *prime;
prime = malloc(2000000 * sizeof(int));
if(!prime) {
/* not enough memory */
}
/* ... use prime ... */
free(prime);
```
|
Here is my implementation.
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int* sieve(int n) {
int* A = calloc(n, sizeof(int));
for(int i = 2; i < (int) sqrt(n); i++) {
if (!A[i]) {
for (int j = i*i; j < n; j+=i) {
A[j] = 1;
}
}
}
return A;
}
```
I benchmarked it for the first 1,000,000,000 numbers on an i5 Kaby Lake.
```
time ./sieve 1000000000
./sieve 1000000000 16.21s user 1.05s system 99% cpu 17.434 total
```
I simply translated [this](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants) pseudocode from Wikipedia.
|
7,921,457 |
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/>
any idea?
tnx - luke
|
2011/10/27
|
[
"https://Stackoverflow.com/questions/7921457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998967/"
] |
You're allocating a huge array in stack:
```
int prime[2000000]={};
```
Four bytes times two million equals eight megabytes, which is often the maximum stack size. Allocating more than that results in segmentation fault.
You should allocate the array in heap, instead:
```
int *prime;
prime = malloc(2000000 * sizeof(int));
if(!prime) {
/* not enough memory */
}
/* ... use prime ... */
free(prime);
```
|
Here was my implementation (Java)
much simpler in that you really only need one array, just start for loops at 2.
edit: @cheesehead 's solution was probably better, i just read the description of the sieve and thought it would be a good thought exercise.
```
// set max;
int max = 100000000;
// logic
boolean[] marked = new boolean[max]; // all start as false
for (int k = 2; k < max;) {
for (int g = k * 2; g < max; g += k) {
marked[g] = true;
}
k++;
while (k < max && marked[k]) {
k++;
}
}
//print
for (int k = 2; k < max; k++) {
if (!marked[k]) {
System.out.println(k);
}
}
```
|
7,921,457 |
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/>
any idea?
tnx - luke
|
2011/10/27
|
[
"https://Stackoverflow.com/questions/7921457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998967/"
] |
You're allocating a huge array in stack:
```
int prime[2000000]={};
```
Four bytes times two million equals eight megabytes, which is often the maximum stack size. Allocating more than that results in segmentation fault.
You should allocate the array in heap, instead:
```
int *prime;
prime = malloc(2000000 * sizeof(int));
if(!prime) {
/* not enough memory */
}
/* ... use prime ... */
free(prime);
```
|
**Simple implementation of Sieve of Eratosthenes**
**Approach:**
I have created a boolean vector of size n+1(say n=9 then 0 to 9)that holds true at all places. Now, *for i=2* mark all the places that are *multiple of 2 as **false***(like 4,6 and 8 when n=9). For *i=3*, mark all the places that are *multiple of 3 as **false***(like 6 and 9 when n=9). Now, for i=4 condition **i\*i<=n** is ***false*** because 4\*4 =16 > 9. So, now print all the places that hold true value.
```
void sieve(int n)
{
vector<bool> isPrime(n+1,true);
for(int i=2;i*i<=n;i++){
if(isPrime[i])
{
for(int j=2*i;j<=n;j=j+i)
isPrime[j]=false;
}
}
for(int i=2;i<=n;i++){
if(isPrime[i])
cout<<i<<" ";
}
}
```
|
7,921,457 |
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/>
any idea?
tnx - luke
|
2011/10/27
|
[
"https://Stackoverflow.com/questions/7921457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998967/"
] |
Here is my implementation.
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int* sieve(int n) {
int* A = calloc(n, sizeof(int));
for(int i = 2; i < (int) sqrt(n); i++) {
if (!A[i]) {
for (int j = i*i; j < n; j+=i) {
A[j] = 1;
}
}
}
return A;
}
```
I benchmarked it for the first 1,000,000,000 numbers on an i5 Kaby Lake.
```
time ./sieve 1000000000
./sieve 1000000000 16.21s user 1.05s system 99% cpu 17.434 total
```
I simply translated [this](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants) pseudocode from Wikipedia.
|
Here was my implementation (Java)
much simpler in that you really only need one array, just start for loops at 2.
edit: @cheesehead 's solution was probably better, i just read the description of the sieve and thought it would be a good thought exercise.
```
// set max;
int max = 100000000;
// logic
boolean[] marked = new boolean[max]; // all start as false
for (int k = 2; k < max;) {
for (int g = k * 2; g < max; g += k) {
marked[g] = true;
}
k++;
while (k < max && marked[k]) {
k++;
}
}
//print
for (int k = 2; k < max; k++) {
if (!marked[k]) {
System.out.println(k);
}
}
```
|
7,921,457 |
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/>
any idea?
tnx - luke
|
2011/10/27
|
[
"https://Stackoverflow.com/questions/7921457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998967/"
] |
Here is my implementation.
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int* sieve(int n) {
int* A = calloc(n, sizeof(int));
for(int i = 2; i < (int) sqrt(n); i++) {
if (!A[i]) {
for (int j = i*i; j < n; j+=i) {
A[j] = 1;
}
}
}
return A;
}
```
I benchmarked it for the first 1,000,000,000 numbers on an i5 Kaby Lake.
```
time ./sieve 1000000000
./sieve 1000000000 16.21s user 1.05s system 99% cpu 17.434 total
```
I simply translated [this](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants) pseudocode from Wikipedia.
|
**Simple implementation of Sieve of Eratosthenes**
**Approach:**
I have created a boolean vector of size n+1(say n=9 then 0 to 9)that holds true at all places. Now, *for i=2* mark all the places that are *multiple of 2 as **false***(like 4,6 and 8 when n=9). For *i=3*, mark all the places that are *multiple of 3 as **false***(like 6 and 9 when n=9). Now, for i=4 condition **i\*i<=n** is ***false*** because 4\*4 =16 > 9. So, now print all the places that hold true value.
```
void sieve(int n)
{
vector<bool> isPrime(n+1,true);
for(int i=2;i*i<=n;i++){
if(isPrime[i])
{
for(int j=2*i;j<=n;j=j+i)
isPrime[j]=false;
}
}
for(int i=2;i<=n;i++){
if(isPrime[i])
cout<<i<<" ";
}
}
```
|
7,921,457 |
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/>
any idea?
tnx - luke
|
2011/10/27
|
[
"https://Stackoverflow.com/questions/7921457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998967/"
] |
Here was my implementation (Java)
much simpler in that you really only need one array, just start for loops at 2.
edit: @cheesehead 's solution was probably better, i just read the description of the sieve and thought it would be a good thought exercise.
```
// set max;
int max = 100000000;
// logic
boolean[] marked = new boolean[max]; // all start as false
for (int k = 2; k < max;) {
for (int g = k * 2; g < max; g += k) {
marked[g] = true;
}
k++;
while (k < max && marked[k]) {
k++;
}
}
//print
for (int k = 2; k < max; k++) {
if (!marked[k]) {
System.out.println(k);
}
}
```
|
**Simple implementation of Sieve of Eratosthenes**
**Approach:**
I have created a boolean vector of size n+1(say n=9 then 0 to 9)that holds true at all places. Now, *for i=2* mark all the places that are *multiple of 2 as **false***(like 4,6 and 8 when n=9). For *i=3*, mark all the places that are *multiple of 3 as **false***(like 6 and 9 when n=9). Now, for i=4 condition **i\*i<=n** is ***false*** because 4\*4 =16 > 9. So, now print all the places that hold true value.
```
void sieve(int n)
{
vector<bool> isPrime(n+1,true);
for(int i=2;i*i<=n;i++){
if(isPrime[i])
{
for(int j=2*i;j<=n;j=j+i)
isPrime[j]=false;
}
}
for(int i=2;i<=n;i++){
if(isPrime[i])
cout<<i<<" ";
}
}
```
|
58,889,280 |
How to run Ruta scripts from command line?
I tried this but not sure if this is right command.
`javac DataExtraction.ruta`
Error : `error: Class names, 'DataExtraction.ruta', are only accepted if annotation processing is explicitly requested`
|
2019/11/16
|
[
"https://Stackoverflow.com/questions/58889280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894701/"
] |
You are taking the wrong argument from the function parameter and should remove the `return` from `else` statement:
Correct code will be:
```py
import os
def files():
files = os.listdir()
file_found_flag = False
for file in files:
if file.lower().endswith('.jpg'):
name= Dict['jpg']
name(file)
file_found_flag = True
elif file.lower().endswith('.pdf'):
e= Dict['pdf']
e(file)
file_found_flag = True
elif file.lower().endswith('.xlsx'):
f= Dict['xlsx']
f(file)
file_found_flag = True
if not file_found_flag:
print('no file found')
def jpg(file):
print('image file found {}'.format(file))
def pdf(file):
print('pdf file found {}'.format(file))
def xlsx(file):
print('excel file found {}'.format(file))
Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx }
files()
```
|
You can cleanly do it like this
```
EXT_IMAGES = ['.png', '.jpg', '.jpeg', '.bmp', '.svg']
EXT_VIDEOS = ['.mp4', '.mkv', '.webm', '.mpeg', '.flv', '.m4a', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.avi', '.wmv']
EXT_AUDIOS = ['.mp3', '.wav', '.raw', '.wma']
EXT_EXCEL = ['.xlsx']
def check_files():
files = os.listdir()
for file in files:
filename, extension = os.path.splitext(file)
if extension in EXT_IMAGES:
print('image file found {}'.format(file))
elif extension in EXT_VIDEOS:
print('video file found {}'.format(file))
elif extension in EXT_AUDIOS:
print('audio file found {}'.format(file))
elif extension in EXT_EXCEL:
print('excel file found {}'.format(file))
else:
print('unknown file found: %s' % file)
check_files()
```
|
58,889,280 |
How to run Ruta scripts from command line?
I tried this but not sure if this is right command.
`javac DataExtraction.ruta`
Error : `error: Class names, 'DataExtraction.ruta', are only accepted if annotation processing is explicitly requested`
|
2019/11/16
|
[
"https://Stackoverflow.com/questions/58889280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894701/"
] |
You are taking the wrong argument from the function parameter and should remove the `return` from `else` statement:
Correct code will be:
```py
import os
def files():
files = os.listdir()
file_found_flag = False
for file in files:
if file.lower().endswith('.jpg'):
name= Dict['jpg']
name(file)
file_found_flag = True
elif file.lower().endswith('.pdf'):
e= Dict['pdf']
e(file)
file_found_flag = True
elif file.lower().endswith('.xlsx'):
f= Dict['xlsx']
f(file)
file_found_flag = True
if not file_found_flag:
print('no file found')
def jpg(file):
print('image file found {}'.format(file))
def pdf(file):
print('pdf file found {}'.format(file))
def xlsx(file):
print('excel file found {}'.format(file))
Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx }
files()
```
|
A few of things I noticed that might be wrong in your code:
1. file is a builtin in Python. You might want to change your variable name to something other than file.
```
for f in files:
if f.lower().endswith('.jpg'):
name= Dict['jpg']
name(f)
elif f.lower().endswith('.pdf'):
e= Dict['pdf']
e(f)
elif f.lower().endswith('.xlsx'):
func= Dict['xlsx']
func(f)
else:
print('no file found')
return
```
2. You are using the incorrect argument in your jpeg, xlsx, and pdf methods.
def jpg(d):
print('image file found {}'.format(d))
The output produced in my case:
```
image file found abc.Jpg
image file found ferf.jpg
pdf file found vber.pdf
excel file found uvier.xlsx
```
|
81,929 |
I have acquired a lot of nice blue and green equipments ~lvl 20. I have no use for these since my class can't equip them. Should I just npc these or salvage them? What is the most profitable way?
|
2012/08/28
|
[
"https://gaming.stackexchange.com/questions/81929",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/27998/"
] |
The most profitable way to get rid of rare equipment is often the Black Lion Trading Post. For common equipment, the trade price is not even high enough to account for the cost to post the item. In those cases, it is more profitable to just sell them to a merchant.
I would just sell them to a merchant unless you really need the materials that they are composed of, the essences of luck, or are working on the monthly salvages achievement. Salvaging armor pieces usually nets less value than simply selling them.
|
Most common equipment is better off salvaged than sold. Even if you're not going to do crafting, you can usually sell the components you salvage in the TP for more than what you can sell the original item for. For 'green' items and above, better to sell them to the merchant or TP. You can check the prices in the TP wherever you are (no need to be at the trader for that), so you can see what's better for you.
|
81,929 |
I have acquired a lot of nice blue and green equipments ~lvl 20. I have no use for these since my class can't equip them. Should I just npc these or salvage them? What is the most profitable way?
|
2012/08/28
|
[
"https://gaming.stackexchange.com/questions/81929",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/27998/"
] |
The most profitable way to get rid of rare equipment is often the Black Lion Trading Post. For common equipment, the trade price is not even high enough to account for the cost to post the item. In those cases, it is more profitable to just sell them to a merchant.
I would just sell them to a merchant unless you really need the materials that they are composed of, the essences of luck, or are working on the monthly salvages achievement. Salvaging armor pieces usually nets less value than simply selling them.
|
It really depends also on what you are aiming at, for example Legendary weapons require different behavior, but basically that's what I do:
76+ rare/exotic weapons: save for throwing in Mystic Forge for legendary precursor
68+ rare/exotic weapons/armors: salvage with Black Lion Kit for Globes of Ectoplasm (to craft new 80 exotics and legendary)
Then everything selling for good at Trading Post is sold here (I usually sell what is already required by someone)
The white items salvaged (sometimes blue too, if you need the salvage achievement), the rest sold at the merchant
Even if you are not aiming at legendary, salvaging and forging can get you some nice items and components which you can sell at an higher price, compared to the original item
Hope it helps!
|
34,479,693 |
*I am new to StackOverflow so please correct me if there is a better way to post a question which is a specific case of an existing question.*
Alberto Barrera answered
[How does one seed the random number generator in Swift?](https://stackoverflow.com/questions/25895081/how-does-one-seed-the-random-number-generator-in-swift)
with
```
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
```
which is perfect generally, but when I try it in [The IBM Swift Sandbox](http://swiftlang.ng.bluemix.net/#/repl) it gives the same number sequence every run, at least in the space of a half hour.
```
import Foundation
import CoreFoundation
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
```
At the moment, every Run prints 5.
Has anyone found a way to do this in the IBM Sandbox? I have found that random() and srandom() produce a different number sequence but similarly are the same each Run. I haven't found arc4random() in Foundation, CoreFoundation, Darwin, or Glibc.
*As an aside, I humbly suggest someone with reputation above 1500 creates a tag IBM-Swift-Sandbox.*
|
2015/12/27
|
[
"https://Stackoverflow.com/questions/34479693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5646134/"
] |
`srand` is working as expected. If you change value each time in `let time = UInt32(NSDate().timeIntervalSinceReferenceDate)` instead of `NSDate().timeIntervalSinceReferenceDate` with any number, it will output random numbers.
Maybe this is a caching issue, it just doesn't see any changes in code and doesn't send it for recompilation :)
|
I don't know what is going on but today it is totally working. So I guess the question is answered:
```
srand(UInt32(NSDate().timeIntervalSinceReferenceDate))
```
works fine.
(I think something must have changed. It was behaving the same way (generating the same number with repeated attempts) on two different computers for about 10 days... Bizarre.)
|
34,479,693 |
*I am new to StackOverflow so please correct me if there is a better way to post a question which is a specific case of an existing question.*
Alberto Barrera answered
[How does one seed the random number generator in Swift?](https://stackoverflow.com/questions/25895081/how-does-one-seed-the-random-number-generator-in-swift)
with
```
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
```
which is perfect generally, but when I try it in [The IBM Swift Sandbox](http://swiftlang.ng.bluemix.net/#/repl) it gives the same number sequence every run, at least in the space of a half hour.
```
import Foundation
import CoreFoundation
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
```
At the moment, every Run prints 5.
Has anyone found a way to do this in the IBM Sandbox? I have found that random() and srandom() produce a different number sequence but similarly are the same each Run. I haven't found arc4random() in Foundation, CoreFoundation, Darwin, or Glibc.
*As an aside, I humbly suggest someone with reputation above 1500 creates a tag IBM-Swift-Sandbox.*
|
2015/12/27
|
[
"https://Stackoverflow.com/questions/34479693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5646134/"
] |
This was an issue with the way we implemented server-side caching in the Sandbox; non-deterministic code would continually return the same answer even though it should not have. We've disabled it for now, and you should be getting different results with each run. We're currently working on better mechanisms to ensure the scalability of the Sandbox.
I'll see about that tag, as well!
|
`srand` is working as expected. If you change value each time in `let time = UInt32(NSDate().timeIntervalSinceReferenceDate)` instead of `NSDate().timeIntervalSinceReferenceDate` with any number, it will output random numbers.
Maybe this is a caching issue, it just doesn't see any changes in code and doesn't send it for recompilation :)
|
34,479,693 |
*I am new to StackOverflow so please correct me if there is a better way to post a question which is a specific case of an existing question.*
Alberto Barrera answered
[How does one seed the random number generator in Swift?](https://stackoverflow.com/questions/25895081/how-does-one-seed-the-random-number-generator-in-swift)
with
```
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
```
which is perfect generally, but when I try it in [The IBM Swift Sandbox](http://swiftlang.ng.bluemix.net/#/repl) it gives the same number sequence every run, at least in the space of a half hour.
```
import Foundation
import CoreFoundation
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
```
At the moment, every Run prints 5.
Has anyone found a way to do this in the IBM Sandbox? I have found that random() and srandom() produce a different number sequence but similarly are the same each Run. I haven't found arc4random() in Foundation, CoreFoundation, Darwin, or Glibc.
*As an aside, I humbly suggest someone with reputation above 1500 creates a tag IBM-Swift-Sandbox.*
|
2015/12/27
|
[
"https://Stackoverflow.com/questions/34479693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5646134/"
] |
This was an issue with the way we implemented server-side caching in the Sandbox; non-deterministic code would continually return the same answer even though it should not have. We've disabled it for now, and you should be getting different results with each run. We're currently working on better mechanisms to ensure the scalability of the Sandbox.
I'll see about that tag, as well!
|
I don't know what is going on but today it is totally working. So I guess the question is answered:
```
srand(UInt32(NSDate().timeIntervalSinceReferenceDate))
```
works fine.
(I think something must have changed. It was behaving the same way (generating the same number with repeated attempts) on two different computers for about 10 days... Bizarre.)
|
56,955,320 |
I have a JSON file which contains text like this
```
.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...
```
My simple question is how CONVERT (not remove) these \u codes to spaces, apostrophes and e.t.c...?
**Input:** a text file with `.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...`
**Output:** `.....wax, and voila!(converted to the line break)At the moment you can't use our ...`
Python code
```
def TEST():
export= requests.get('https://sample.uk/', auth=('user', 'pass')).text
with open("TEST.json",'w') as file:
file.write(export.decode('utf8'))
```
What I have tried:
* Using .json()
* any different ways of combining .encode().decode() and e.t.c.
**Edit 1**
When I upload this file to BigQuery I have - `Â` symbol
**Bigger Sample:**
```
{
"xxxx1": "...You don\u2019t nee...",
"xxxx2": "...Gu\u00e9rer...",
"xxxx3": "...boost.\u00a0Sit back an....",
"xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"",
"xxxx5": "\u00a0\n\u00a0",
"xxxx6": "It was Christmas Eve babe\u2026",
"xxxx7": "It\u2019s xxx xxx\u2026"
}
```
Python code:
```
import json
import re
import codecs
def load():
epos_export = r'{"xxxx1": "...You don\u2019t nee...","xxxx2": "...Gu\u00e9rer...","xxxx3": "...boost.\u00a0Sit back an....","xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"","xxxx5": "\u00a0\n\u00a0","xxxx6": "It was Christmas Eve babe\u2026","xxxx7": "It\u2019s xxx xxx\u2026"}'
x = json.loads(re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, epos_export))
with open("TEST.json", "w") as file:
json.dump(x,file)
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
return buffer.decode('utf8') # '€'
except UnicodeDecodeError:
print("Could not decode buffer: %s" % buffer)
if __name__ == '__main__':
load()
```
|
2019/07/09
|
[
"https://Stackoverflow.com/questions/56955320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11506172/"
] |
I have made this crude UTF-8 unmangler, which appears to solve your messed-up encoding situation:
```
import codecs
import re
import json
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
return buffer.decode('utf8') # '€'
except UnicodeDecodeError:
print("Could not decode buffer: %s" % buffer)
```
Usage:
```
broken_json = '{"some_key": "... \\u00e2\\u0080\\u0099 w\\u0061x, and voila!\\u00c2\\u00a0\\u00c2\\u00a0At the moment you can\'t use our \\u00e2\\u0082\\u00ac ..."}'
print("Broken JSON\n", broken_json)
converted = re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, broken_json)
print("Fixed JSON\n", converted)
data = json.loads(converted)
print("Parsed data\n", data)
print("Single value\n", data['some_key'])
```
It uses regex to pick up the hex sequences from your string, converts them to individual bytes and decodes them as UTF-8.
For the sample string above (I've included the 3-byte character `€` as a test) this prints:
```
Broken JSON
{"some_key": "... \u00e2\u0080\u0099 w\u0061x, and voila!\u00c2\u00a0\u00c2\u00a0At the moment you can't use our \u00e2\u0082\u00ac ..."}
Fixed JSON
{"some_key": "... ’ wax, and voila! At the moment you can't use our € ..."}
Parsed data
{'some_key': "... ’ wax, and voila!\xa0\xa0At the moment you can't use our € ..."}
Single value
... ’ wax, and voila! At the moment you can't use our € ...
```
The `\xa0` in the "Parsed data" is caused by the way Python outputs dicts to the console, it still is the actual non-breaking space.
|
The hacky approach is to remove the outer layer of encoding:
```py
import re
# Assume export is a bytes-like object
export = re.sub(b'\\\u00([89a-f][0-9a-f])', lambda m: bytes.fromhex(m.group(1).decode()), export, flags=re.IGNORECASE)
```
This matches the escaped UTF-8 bytes and replaces them with actual UTF-8 bytes . Writing the resulting bytes-like object to disk (without further decoding!) should result in a valid UTF-8 JSON file.
Of course this will break if the file contains genuine escaped unicode characters in the UTF-8 range, like `\u00e9` for an accented "e".
|
56,955,320 |
I have a JSON file which contains text like this
```
.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...
```
My simple question is how CONVERT (not remove) these \u codes to spaces, apostrophes and e.t.c...?
**Input:** a text file with `.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...`
**Output:** `.....wax, and voila!(converted to the line break)At the moment you can't use our ...`
Python code
```
def TEST():
export= requests.get('https://sample.uk/', auth=('user', 'pass')).text
with open("TEST.json",'w') as file:
file.write(export.decode('utf8'))
```
What I have tried:
* Using .json()
* any different ways of combining .encode().decode() and e.t.c.
**Edit 1**
When I upload this file to BigQuery I have - `Â` symbol
**Bigger Sample:**
```
{
"xxxx1": "...You don\u2019t nee...",
"xxxx2": "...Gu\u00e9rer...",
"xxxx3": "...boost.\u00a0Sit back an....",
"xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"",
"xxxx5": "\u00a0\n\u00a0",
"xxxx6": "It was Christmas Eve babe\u2026",
"xxxx7": "It\u2019s xxx xxx\u2026"
}
```
Python code:
```
import json
import re
import codecs
def load():
epos_export = r'{"xxxx1": "...You don\u2019t nee...","xxxx2": "...Gu\u00e9rer...","xxxx3": "...boost.\u00a0Sit back an....","xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"","xxxx5": "\u00a0\n\u00a0","xxxx6": "It was Christmas Eve babe\u2026","xxxx7": "It\u2019s xxx xxx\u2026"}'
x = json.loads(re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, epos_export))
with open("TEST.json", "w") as file:
json.dump(x,file)
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
return buffer.decode('utf8') # '€'
except UnicodeDecodeError:
print("Could not decode buffer: %s" % buffer)
if __name__ == '__main__':
load()
```
|
2019/07/09
|
[
"https://Stackoverflow.com/questions/56955320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11506172/"
] |
The hacky approach is to remove the outer layer of encoding:
```py
import re
# Assume export is a bytes-like object
export = re.sub(b'\\\u00([89a-f][0-9a-f])', lambda m: bytes.fromhex(m.group(1).decode()), export, flags=re.IGNORECASE)
```
This matches the escaped UTF-8 bytes and replaces them with actual UTF-8 bytes . Writing the resulting bytes-like object to disk (without further decoding!) should result in a valid UTF-8 JSON file.
Of course this will break if the file contains genuine escaped unicode characters in the UTF-8 range, like `\u00e9` for an accented "e".
|
As you try to write this in a file named `TEST.json`, I will assume that this string is a part of a larger json string.
Let me use an full example:
```
js = '''{"a": "and voila!\\u00c2\\u00a0At the moment you can't use our"}'''
print(js)
{"a": "and voila!\u00c2\u00a0At the moment you can't use our"}
```
I would first load that with json:
```
x = json.loads(js)
print(x)
{'a': "and voila!Â\xa0At the moment you can't use our"}
```
Ok, this now looks like an utf-8 string that was wrongly decoded as Latin1. Let us do the reverse operation:
```
x['a'] = x['a'].encode('latin1').decode('utf8')
print(x)
print(x['a'])
{'a': "and voila!\xa0At the moment you can't use our"}
and voila! At the moment you can't use our
```
Ok, it is now fine and we can convert it back to a correct json string:
```
print(json.dumps(x))
{"a": "and voila!\\u00a0At the moment you can\'t use our"}
```
meaning a correctly encoded NO-BREAK SPACE (U+00A0)
TL/DR: what you should do is:
```
# load the string as json:
js = json.loads(request)
# identify the string values in the json - you probably know how but I don't...
...
# convert the strings:
js[...] = js[...].encode('latin1').decode('utf8')
# convert back to a json string
request = json.dumps(js)
```
|
56,955,320 |
I have a JSON file which contains text like this
```
.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...
```
My simple question is how CONVERT (not remove) these \u codes to spaces, apostrophes and e.t.c...?
**Input:** a text file with `.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...`
**Output:** `.....wax, and voila!(converted to the line break)At the moment you can't use our ...`
Python code
```
def TEST():
export= requests.get('https://sample.uk/', auth=('user', 'pass')).text
with open("TEST.json",'w') as file:
file.write(export.decode('utf8'))
```
What I have tried:
* Using .json()
* any different ways of combining .encode().decode() and e.t.c.
**Edit 1**
When I upload this file to BigQuery I have - `Â` symbol
**Bigger Sample:**
```
{
"xxxx1": "...You don\u2019t nee...",
"xxxx2": "...Gu\u00e9rer...",
"xxxx3": "...boost.\u00a0Sit back an....",
"xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"",
"xxxx5": "\u00a0\n\u00a0",
"xxxx6": "It was Christmas Eve babe\u2026",
"xxxx7": "It\u2019s xxx xxx\u2026"
}
```
Python code:
```
import json
import re
import codecs
def load():
epos_export = r'{"xxxx1": "...You don\u2019t nee...","xxxx2": "...Gu\u00e9rer...","xxxx3": "...boost.\u00a0Sit back an....","xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"","xxxx5": "\u00a0\n\u00a0","xxxx6": "It was Christmas Eve babe\u2026","xxxx7": "It\u2019s xxx xxx\u2026"}'
x = json.loads(re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, epos_export))
with open("TEST.json", "w") as file:
json.dump(x,file)
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
return buffer.decode('utf8') # '€'
except UnicodeDecodeError:
print("Could not decode buffer: %s" % buffer)
if __name__ == '__main__':
load()
```
|
2019/07/09
|
[
"https://Stackoverflow.com/questions/56955320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11506172/"
] |
I have made this crude UTF-8 unmangler, which appears to solve your messed-up encoding situation:
```
import codecs
import re
import json
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
return buffer.decode('utf8') # '€'
except UnicodeDecodeError:
print("Could not decode buffer: %s" % buffer)
```
Usage:
```
broken_json = '{"some_key": "... \\u00e2\\u0080\\u0099 w\\u0061x, and voila!\\u00c2\\u00a0\\u00c2\\u00a0At the moment you can\'t use our \\u00e2\\u0082\\u00ac ..."}'
print("Broken JSON\n", broken_json)
converted = re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, broken_json)
print("Fixed JSON\n", converted)
data = json.loads(converted)
print("Parsed data\n", data)
print("Single value\n", data['some_key'])
```
It uses regex to pick up the hex sequences from your string, converts them to individual bytes and decodes them as UTF-8.
For the sample string above (I've included the 3-byte character `€` as a test) this prints:
```
Broken JSON
{"some_key": "... \u00e2\u0080\u0099 w\u0061x, and voila!\u00c2\u00a0\u00c2\u00a0At the moment you can't use our \u00e2\u0082\u00ac ..."}
Fixed JSON
{"some_key": "... ’ wax, and voila! At the moment you can't use our € ..."}
Parsed data
{'some_key': "... ’ wax, and voila!\xa0\xa0At the moment you can't use our € ..."}
Single value
... ’ wax, and voila! At the moment you can't use our € ...
```
The `\xa0` in the "Parsed data" is caused by the way Python outputs dicts to the console, it still is the actual non-breaking space.
|
As you try to write this in a file named `TEST.json`, I will assume that this string is a part of a larger json string.
Let me use an full example:
```
js = '''{"a": "and voila!\\u00c2\\u00a0At the moment you can't use our"}'''
print(js)
{"a": "and voila!\u00c2\u00a0At the moment you can't use our"}
```
I would first load that with json:
```
x = json.loads(js)
print(x)
{'a': "and voila!Â\xa0At the moment you can't use our"}
```
Ok, this now looks like an utf-8 string that was wrongly decoded as Latin1. Let us do the reverse operation:
```
x['a'] = x['a'].encode('latin1').decode('utf8')
print(x)
print(x['a'])
{'a': "and voila!\xa0At the moment you can't use our"}
and voila! At the moment you can't use our
```
Ok, it is now fine and we can convert it back to a correct json string:
```
print(json.dumps(x))
{"a": "and voila!\\u00a0At the moment you can\'t use our"}
```
meaning a correctly encoded NO-BREAK SPACE (U+00A0)
TL/DR: what you should do is:
```
# load the string as json:
js = json.loads(request)
# identify the string values in the json - you probably know how but I don't...
...
# convert the strings:
js[...] = js[...].encode('latin1').decode('utf8')
# convert back to a json string
request = json.dumps(js)
```
|
2,209,575 |
I have a puzzling problem -- it seems like it should be so easy to do but somehow it is not working. I have an object called Player. The Manager class has four instances of Player:
```
@interface Manager
{
Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent;
}
// @property...
```
The Manager object has initPlayers and swapPlayers methods.
```
-(void) initPlayers { // this works fine
self.p1 = [[Player alloc] init];
self.p2 = [[Player alloc] init];
self.mCurrentPlayer = self.p1;
self.mCurrentOpponent = self.p2;
}
-(void) swapPlayers { // this swapping of pointer doesn't work
self.mCurrentPlayer = self.p2;
self.mCurrentOpponent = self.p1;
// When I look at the pointer in debugger, self.mCurrentPlayer is still self.p1. :-(
// I even tried first setting them to nil,
// or first releasing them (with an extra retain on assignment) to no avail
}
```
What am I missing? Thanks in advance!
|
2010/02/05
|
[
"https://Stackoverflow.com/questions/2209575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237668/"
] |
Without knowing how your accessors are set up, it will be difficult to troubleshoot the code as-is. That being said, here is how your accessors and code *should* be set up:
>
> **Manager.h**
>
>
>
```
@interface Manager
{
Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent;
}
@property (nonatomic, retain) Player *p1;
@property (nonatomic, retain) Player *p2;
@property (nonatomic, assign) Player *mCurrentPlayer;
@property (nonatomic, assign) Player *mCurrentOpponent;
@end
```
>
> **Manager.m**
>
>
>
```
-(void) initPlayers {
self.p1 = [[[Player alloc] init] autorelease];
self.p2 = [[[Player alloc] init] autorelease];
self.mCurrentPlayer = self.p1;
self.mCurrentOpponent = self.p2;
}
-(void) swapPlayers {
Player * temp = self.mCurrentPlayer;
self.mCurrentPlayer = self.mCurrentOpponent;
self.mCurrentOpponent = temp;
}
```
|
It turns out the problem was somewhere unrelated in the code and I misread the symptoms of the problem! But just for the sake of discussion, why is it necessary to have @property on multiple lines, and to use a temp variable to swap the players (as per e.James answer)?
|
800,831 |
How do I take inverse Laplace transform of $\frac{-2s+3}{s^2-2s+2}$?
I have checked my transform table and there is not a suitable case for this expression.
|
2014/05/18
|
[
"https://math.stackexchange.com/questions/800831",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/141312/"
] |
To perform the inverse Laplace transform you need to complete the square at the denominator,
$$ s^2-2s+2=(s-1)^2+1$$
so you rewrite your expression as
$$\frac{-2s+3}{(s-1)^2+1}= -2 \frac{(s-1)}{(s-1)^2+1}+\frac{(3-2)}{(s-1)^2+1}$$
now these expressions are standard on tables "exponentially decaying
sine/cosine wave. The inverse transform is then
$$e^t(-2\cos t+\sin t).$$
|
You may want to try this (slighlty) different approach:
Let $F(s)$ be the function to be inverse-Laplace transformed. Then, $F(s)$ admits the following partial fraction decomposition:
$$F(s) = \frac{A\_1}{s-s\_1} + \frac{A\_2}{s-s\_2},$$ where $s\_1 = 1-i$, $s\_2 = \overline{s}\_1 = 1+i$, are the complex roots of the denominator, $A\_1 = \lim\_{s\to s\_1} (s-s\_1) F(s) = -1+i/2$ and $A\_2 = \overline{A}\_1 = \lim\_{s\to s\_2}(s-s\_2) F(s) = -1-i/2$. Now take inverse Laplace's transform on each term to get:
$$f(t) = \mathcal{L}^{-1}[F(s)] = A\_1 e^{s\_1 t} + A\_2 e^{s\_2 t},$$ since $A\_1$ and $A\_2$ are complex conjugates as well as $s\_1$ and $s\_2$, the result is real, which you can easily prove with the help of Euler's identity: $e^{ix} = \cos{x} + i \sin{x}$.
I hope this helps.
Cheers!
|
13,695 |
I have been working for this couple of investors for around 18 months. The set up is, these two people will buy small online businesses and I will run these businesses from a single office. Currently I have 5 businesses to manage on my own.
Around a year ago, my boss decided to come up with a forfeit scheme, every time I made a mistake he wanted me to do a forfeit. These were small mistakes, such as sending somebody the wrong invoice, or missing an item off of an order. These have only happened once.
Initially the forfeits were along the line of doing some press-ups or sit-ups, etc, I wasn't bothered about this. However, my boss has been pressuring me to do worse forfeits, it gets to the point he just sits there and waits for me to agree, if I say I don't want to do a forfeit he'll say "you don't have to" so I say ok, then he says "but how are you going to make up for making a mistake", and eventually gets round to me doing a forfeit. More recently he has started to say he wants me to feel humiliated for making mistakes, and tries to get me to do humiliating forfeits.
When he first started I felt ok with it, almost as if it was a good idea. The mistakes were/are not big enough for any serious action, but they are still mistakes so a small forfeit as punishment was incentive for me to double check and take more consideration with the work.
But now, its got to the point where I feel uncomfortable, pressured into situations I really don't want to be in and its almost like my boss is making me do forfeits for his personal interest rather than to help the business.
It's distracting when I am at work, it deters my concentration, I almost feel like I'm being bullied.
Is it OK what my boss is doing?
---
The following has been added since posting this question
--------------------------------------------------------
To clarify I live in the UK.
I'm the only permanent employee here, I work here alone for about 2-3 days a week the other days one of the investors may come in for a few hours. There have been 2 or 3 temporary employees and a few contractors who I would only speak to via email/telephone calls.
It is only 1 of the 2 investors who is putting me in this situation. At one point the investor said just remember what happens at work stays at work, almost as if he didn't want me to tell the other investor or my friends.
For those of you who say the examples aren't small mistakes, I work as a sole employee for 5 businesses - I do almost everything to manage these businesses including processing sales/orders which is in the 1000s some months, dealing with all customers/clients briefing contractors/meeting up with suppliers, producing website content and promotional material, reporting on sales/marketing, purchasing, forecasting, etc, the only areas I do not really have an input in is the legal and corporate finance.
So in over 18 months, if the most serious error I made was amended by me apologizing to a customer and saying there will be a 1 day delay with half of their order, costing the company less than £7 in extra shipping fees, I do not think I have done anything majorly wrong.
The investor has also made me do forfeits when I didn't respond to emails with in a set time frame, when stock levels had been in accurate, and on one occasion the company who installed our e-commerce site had to add an update - after, one link was broken which I didn't notice so I was made to do a forfeit for each day the link was broken on the site which my boss decided was 7 days.
|
2013/08/07
|
[
"https://workplace.stackexchange.com/questions/13695",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/10218/"
] |
>
> Is it OK what my boss is doing?
>
>
>
It's not appropriate for a boss to humiliate a worker - in private or in public.
And if it's at the point where you feel concerned about being at work, then it's clearly NOT OK.
Tell your boss "No" next time, and mean it. Don't let your boss guilt you into doing something that clearly bothers you.
If it continues, quit.
|
Ask your boss to show you where in your agreement, you must be perfect? Are you being paid a perfect salary? Does your employment agreement perfectly fit with local labor laws?
When he asks how you are going to pay him back for mistakes, tell him you're not. Now, what does he plan on doing about it? Continuing to bother you with these repayments is a waste of time and by taking even more of your time to do stupid things only increases the amount of your debt. He can replace you which would be doing you a favor.
He can have a pound of flesh, but not one drop of blood.
|
13,695 |
I have been working for this couple of investors for around 18 months. The set up is, these two people will buy small online businesses and I will run these businesses from a single office. Currently I have 5 businesses to manage on my own.
Around a year ago, my boss decided to come up with a forfeit scheme, every time I made a mistake he wanted me to do a forfeit. These were small mistakes, such as sending somebody the wrong invoice, or missing an item off of an order. These have only happened once.
Initially the forfeits were along the line of doing some press-ups or sit-ups, etc, I wasn't bothered about this. However, my boss has been pressuring me to do worse forfeits, it gets to the point he just sits there and waits for me to agree, if I say I don't want to do a forfeit he'll say "you don't have to" so I say ok, then he says "but how are you going to make up for making a mistake", and eventually gets round to me doing a forfeit. More recently he has started to say he wants me to feel humiliated for making mistakes, and tries to get me to do humiliating forfeits.
When he first started I felt ok with it, almost as if it was a good idea. The mistakes were/are not big enough for any serious action, but they are still mistakes so a small forfeit as punishment was incentive for me to double check and take more consideration with the work.
But now, its got to the point where I feel uncomfortable, pressured into situations I really don't want to be in and its almost like my boss is making me do forfeits for his personal interest rather than to help the business.
It's distracting when I am at work, it deters my concentration, I almost feel like I'm being bullied.
Is it OK what my boss is doing?
---
The following has been added since posting this question
--------------------------------------------------------
To clarify I live in the UK.
I'm the only permanent employee here, I work here alone for about 2-3 days a week the other days one of the investors may come in for a few hours. There have been 2 or 3 temporary employees and a few contractors who I would only speak to via email/telephone calls.
It is only 1 of the 2 investors who is putting me in this situation. At one point the investor said just remember what happens at work stays at work, almost as if he didn't want me to tell the other investor or my friends.
For those of you who say the examples aren't small mistakes, I work as a sole employee for 5 businesses - I do almost everything to manage these businesses including processing sales/orders which is in the 1000s some months, dealing with all customers/clients briefing contractors/meeting up with suppliers, producing website content and promotional material, reporting on sales/marketing, purchasing, forecasting, etc, the only areas I do not really have an input in is the legal and corporate finance.
So in over 18 months, if the most serious error I made was amended by me apologizing to a customer and saying there will be a 1 day delay with half of their order, costing the company less than £7 in extra shipping fees, I do not think I have done anything majorly wrong.
The investor has also made me do forfeits when I didn't respond to emails with in a set time frame, when stock levels had been in accurate, and on one occasion the company who installed our e-commerce site had to add an update - after, one link was broken which I didn't notice so I was made to do a forfeit for each day the link was broken on the site which my boss decided was 7 days.
|
2013/08/07
|
[
"https://workplace.stackexchange.com/questions/13695",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/10218/"
] |
Ask your boss to show you where in your agreement, you must be perfect? Are you being paid a perfect salary? Does your employment agreement perfectly fit with local labor laws?
When he asks how you are going to pay him back for mistakes, tell him you're not. Now, what does he plan on doing about it? Continuing to bother you with these repayments is a waste of time and by taking even more of your time to do stupid things only increases the amount of your debt. He can replace you which would be doing you a favor.
He can have a pound of flesh, but not one drop of blood.
|
It seems to be a very toxic situation and i think there are concerns on your well-being here.
There are some key questions that you need to think about -
1. Firstly you should but a stop to complying with his humiliating requests and make him aware of the toll it is taking on your ability to work there and your morale.
2. Does your boss have a boss or do you have a HR department ? You need to lodge a complaint there, so that this person could be held accountable
3. Having said that, reading “Around a year ago, after I had made a few mistakes, my boss decided to come up with a forfeit scheme” and “Initially the forfeits were along the line of doing some press-ups or sit-ups, etc, I wasn't bothered about this. However, my boss has been pressuring me to do worse forfeits, it gets to the point he just sits there and waits for me to agree” it seems like there is a cultural issue at your work where
a. this type of "scheme" has acceptance,
b. employees are forced to comply.
Please think hard on whether you want to continue here and whether it is a problem only with that person or a general dysfunction of your workplace.
|
13,695 |
I have been working for this couple of investors for around 18 months. The set up is, these two people will buy small online businesses and I will run these businesses from a single office. Currently I have 5 businesses to manage on my own.
Around a year ago, my boss decided to come up with a forfeit scheme, every time I made a mistake he wanted me to do a forfeit. These were small mistakes, such as sending somebody the wrong invoice, or missing an item off of an order. These have only happened once.
Initially the forfeits were along the line of doing some press-ups or sit-ups, etc, I wasn't bothered about this. However, my boss has been pressuring me to do worse forfeits, it gets to the point he just sits there and waits for me to agree, if I say I don't want to do a forfeit he'll say "you don't have to" so I say ok, then he says "but how are you going to make up for making a mistake", and eventually gets round to me doing a forfeit. More recently he has started to say he wants me to feel humiliated for making mistakes, and tries to get me to do humiliating forfeits.
When he first started I felt ok with it, almost as if it was a good idea. The mistakes were/are not big enough for any serious action, but they are still mistakes so a small forfeit as punishment was incentive for me to double check and take more consideration with the work.
But now, its got to the point where I feel uncomfortable, pressured into situations I really don't want to be in and its almost like my boss is making me do forfeits for his personal interest rather than to help the business.
It's distracting when I am at work, it deters my concentration, I almost feel like I'm being bullied.
Is it OK what my boss is doing?
---
The following has been added since posting this question
--------------------------------------------------------
To clarify I live in the UK.
I'm the only permanent employee here, I work here alone for about 2-3 days a week the other days one of the investors may come in for a few hours. There have been 2 or 3 temporary employees and a few contractors who I would only speak to via email/telephone calls.
It is only 1 of the 2 investors who is putting me in this situation. At one point the investor said just remember what happens at work stays at work, almost as if he didn't want me to tell the other investor or my friends.
For those of you who say the examples aren't small mistakes, I work as a sole employee for 5 businesses - I do almost everything to manage these businesses including processing sales/orders which is in the 1000s some months, dealing with all customers/clients briefing contractors/meeting up with suppliers, producing website content and promotional material, reporting on sales/marketing, purchasing, forecasting, etc, the only areas I do not really have an input in is the legal and corporate finance.
So in over 18 months, if the most serious error I made was amended by me apologizing to a customer and saying there will be a 1 day delay with half of their order, costing the company less than £7 in extra shipping fees, I do not think I have done anything majorly wrong.
The investor has also made me do forfeits when I didn't respond to emails with in a set time frame, when stock levels had been in accurate, and on one occasion the company who installed our e-commerce site had to add an update - after, one link was broken which I didn't notice so I was made to do a forfeit for each day the link was broken on the site which my boss decided was 7 days.
|
2013/08/07
|
[
"https://workplace.stackexchange.com/questions/13695",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/10218/"
] |
>
> Is it OK what my boss is doing?
>
>
>
It's not appropriate for a boss to humiliate a worker - in private or in public.
And if it's at the point where you feel concerned about being at work, then it's clearly NOT OK.
Tell your boss "No" next time, and mean it. Don't let your boss guilt you into doing something that clearly bothers you.
If it continues, quit.
|
It seems to be a very toxic situation and i think there are concerns on your well-being here.
There are some key questions that you need to think about -
1. Firstly you should but a stop to complying with his humiliating requests and make him aware of the toll it is taking on your ability to work there and your morale.
2. Does your boss have a boss or do you have a HR department ? You need to lodge a complaint there, so that this person could be held accountable
3. Having said that, reading “Around a year ago, after I had made a few mistakes, my boss decided to come up with a forfeit scheme” and “Initially the forfeits were along the line of doing some press-ups or sit-ups, etc, I wasn't bothered about this. However, my boss has been pressuring me to do worse forfeits, it gets to the point he just sits there and waits for me to agree” it seems like there is a cultural issue at your work where
a. this type of "scheme" has acceptance,
b. employees are forced to comply.
Please think hard on whether you want to continue here and whether it is a problem only with that person or a general dysfunction of your workplace.
|
41,829 |
The answer to this is likely "It is not possible.", and from what I know about filesystems and storage, I would say the same thing. But, I thought I would try the great wisdom of SuperUser:
I'm looking for a NAS device that will serve the same content over USB and via SMB.
I have a device (let's call it the reader) which will read files from an external USB drive. I would like to attach a drive, but also make that drive writable across the network. The reader does not have a network port. I get that the reader considers the USB directly attached storage, so it partitions and formats it, while anything that served up the drive's content over the network (via SMB or something) is serving up file content and not a lower level storage device like the USB interface, and you'll end up with two different things having the filesystem mounted, which going to cause trouble.
|
2009/09/15
|
[
"https://superuser.com/questions/41829",
"https://superuser.com",
"https://superuser.com/users/9588/"
] |
Basically, if I read you correctly, you want a Network Attached Storage device that allows you to access the data stored on it via USB and via an SMB network share simultaneously.
To muse a bit more with you, I think it is possible. It may not actually exist out in the world (yet), but it is possible to build something that behaves this way I think.
There is [this device on newegg](http://www.newegg.com/Product/Product.aspx?Item=N82E16817180005) that seems to do what you are talking about, but judging by reviews it may not do what you want.
If you tried looking around, you might be able to find a way to repurpose a full-blown PC to both provide access to data on an internal hard-drive via both a USB connection and via SMB sharing. However, you might have to be creative with the USB side of things, as I doubt you could have the HDD available as mass storage coming from the PC, due to host/guest issues in USB. You could maybe have the HDD available over USB by using USB as a direct PC-to-PC connection system (kinda like PC-to-PC over parallel port, back in the day).
|
I've accepted sheepsimulator's answer. But I thought I would post my own just to get this out there. I've thought about this some more, and here's the only way I can imagine this working:
Have a disk enclosure that has both a USB port and an Ethernet port. There's a bit of firmware in the enclosure the runs a webserver for configuration. The device has two modes, USB mode and NAS mode. You can switch between them with the web-based configuration (so the network port is always active, but SMB file sharing is not always active). To enter NAS mode, the device does a USB disconnect on it's USB port, the mounts the filesystem on the drive itself internally and starts the process to do SMB sharing. When switching to USB mode, the device shuts down the SMB process, unmounts the filesystem, then does a USB reconnect.
Without actually trying this, it seems like this would work and not cause problems. Pretty much anything expecting to talk to a USB Mass Storage device will handle the hotplug/unplug gracefully, and most SMB clients are ok with the server going away.
A slightly different (crazier?) version of this would be more automatic. Let's say USB mode is the default. When it's not doing anything else, it defaults to USB mode. The SMB sharing process is running, but because the USB side owns the drive there isn't a filesystem actually in place (yet). When an SMB request comes in that requires actual content, do the switch from USB to NAS like a described above. Maybe it stays in NAS mode for as long as there is some activity requiring SMB to access actual files within a configurable timeout.
This would probably generate a ton of connect/disconnects for the USB side and I can imagine various PCs on the network accidentally indexing, pinging or otherwise unintentionally causing the NAS side to wakeup often.
Huh, I want this to exist for cheap, but I can't imagine it would be cheap to produce. There's a bit of coding there.
|
41,829 |
The answer to this is likely "It is not possible.", and from what I know about filesystems and storage, I would say the same thing. But, I thought I would try the great wisdom of SuperUser:
I'm looking for a NAS device that will serve the same content over USB and via SMB.
I have a device (let's call it the reader) which will read files from an external USB drive. I would like to attach a drive, but also make that drive writable across the network. The reader does not have a network port. I get that the reader considers the USB directly attached storage, so it partitions and formats it, while anything that served up the drive's content over the network (via SMB or something) is serving up file content and not a lower level storage device like the USB interface, and you'll end up with two different things having the filesystem mounted, which going to cause trouble.
|
2009/09/15
|
[
"https://superuser.com/questions/41829",
"https://superuser.com",
"https://superuser.com/users/9588/"
] |
Basically, if I read you correctly, you want a Network Attached Storage device that allows you to access the data stored on it via USB and via an SMB network share simultaneously.
To muse a bit more with you, I think it is possible. It may not actually exist out in the world (yet), but it is possible to build something that behaves this way I think.
There is [this device on newegg](http://www.newegg.com/Product/Product.aspx?Item=N82E16817180005) that seems to do what you are talking about, but judging by reviews it may not do what you want.
If you tried looking around, you might be able to find a way to repurpose a full-blown PC to both provide access to data on an internal hard-drive via both a USB connection and via SMB sharing. However, you might have to be creative with the USB side of things, as I doubt you could have the HDD available as mass storage coming from the PC, due to host/guest issues in USB. You could maybe have the HDD available over USB by using USB as a direct PC-to-PC connection system (kinda like PC-to-PC over parallel port, back in the day).
|
I dont know if you ever solved this, but have a look at this, I just ordered one, had a similar requirement to you, I want to carry a pc around with me and thats it, and need to be able to easily share the data on it like a drive , such as AV progs or Hirens disc etc with other pc's
<http://cgi.ebay.co.uk/USB-Go-Link-PC-PC-Transfer-Network-Cable-Card-Reader-/120645125445?pt=UK_Computing_CablesConnectors_RL&hash=item1c17028545>
|
41,829 |
The answer to this is likely "It is not possible.", and from what I know about filesystems and storage, I would say the same thing. But, I thought I would try the great wisdom of SuperUser:
I'm looking for a NAS device that will serve the same content over USB and via SMB.
I have a device (let's call it the reader) which will read files from an external USB drive. I would like to attach a drive, but also make that drive writable across the network. The reader does not have a network port. I get that the reader considers the USB directly attached storage, so it partitions and formats it, while anything that served up the drive's content over the network (via SMB or something) is serving up file content and not a lower level storage device like the USB interface, and you'll end up with two different things having the filesystem mounted, which going to cause trouble.
|
2009/09/15
|
[
"https://superuser.com/questions/41829",
"https://superuser.com",
"https://superuser.com/users/9588/"
] |
Basically, if I read you correctly, you want a Network Attached Storage device that allows you to access the data stored on it via USB and via an SMB network share simultaneously.
To muse a bit more with you, I think it is possible. It may not actually exist out in the world (yet), but it is possible to build something that behaves this way I think.
There is [this device on newegg](http://www.newegg.com/Product/Product.aspx?Item=N82E16817180005) that seems to do what you are talking about, but judging by reviews it may not do what you want.
If you tried looking around, you might be able to find a way to repurpose a full-blown PC to both provide access to data on an internal hard-drive via both a USB connection and via SMB sharing. However, you might have to be creative with the USB side of things, as I doubt you could have the HDD available as mass storage coming from the PC, due to host/guest issues in USB. You could maybe have the HDD available over USB by using USB as a direct PC-to-PC connection system (kinda like PC-to-PC over parallel port, back in the day).
|
It is not possiblwe. USB disk file-systems are managed by a host computer which is aware of blocks, allocations, which files are open, where they are, etc. It is just a block device.
A NAS on the other hand maintains internal awareness of all of these factors and they won’t match the awareness of the computer that has attached the disk via a USB port.
SANS do this sort of thing, but in different volumes or partitions. iSCSI is the SAN equivalent of USB.
|
41,829 |
The answer to this is likely "It is not possible.", and from what I know about filesystems and storage, I would say the same thing. But, I thought I would try the great wisdom of SuperUser:
I'm looking for a NAS device that will serve the same content over USB and via SMB.
I have a device (let's call it the reader) which will read files from an external USB drive. I would like to attach a drive, but also make that drive writable across the network. The reader does not have a network port. I get that the reader considers the USB directly attached storage, so it partitions and formats it, while anything that served up the drive's content over the network (via SMB or something) is serving up file content and not a lower level storage device like the USB interface, and you'll end up with two different things having the filesystem mounted, which going to cause trouble.
|
2009/09/15
|
[
"https://superuser.com/questions/41829",
"https://superuser.com",
"https://superuser.com/users/9588/"
] |
I dont know if you ever solved this, but have a look at this, I just ordered one, had a similar requirement to you, I want to carry a pc around with me and thats it, and need to be able to easily share the data on it like a drive , such as AV progs or Hirens disc etc with other pc's
<http://cgi.ebay.co.uk/USB-Go-Link-PC-PC-Transfer-Network-Cable-Card-Reader-/120645125445?pt=UK_Computing_CablesConnectors_RL&hash=item1c17028545>
|
I've accepted sheepsimulator's answer. But I thought I would post my own just to get this out there. I've thought about this some more, and here's the only way I can imagine this working:
Have a disk enclosure that has both a USB port and an Ethernet port. There's a bit of firmware in the enclosure the runs a webserver for configuration. The device has two modes, USB mode and NAS mode. You can switch between them with the web-based configuration (so the network port is always active, but SMB file sharing is not always active). To enter NAS mode, the device does a USB disconnect on it's USB port, the mounts the filesystem on the drive itself internally and starts the process to do SMB sharing. When switching to USB mode, the device shuts down the SMB process, unmounts the filesystem, then does a USB reconnect.
Without actually trying this, it seems like this would work and not cause problems. Pretty much anything expecting to talk to a USB Mass Storage device will handle the hotplug/unplug gracefully, and most SMB clients are ok with the server going away.
A slightly different (crazier?) version of this would be more automatic. Let's say USB mode is the default. When it's not doing anything else, it defaults to USB mode. The SMB sharing process is running, but because the USB side owns the drive there isn't a filesystem actually in place (yet). When an SMB request comes in that requires actual content, do the switch from USB to NAS like a described above. Maybe it stays in NAS mode for as long as there is some activity requiring SMB to access actual files within a configurable timeout.
This would probably generate a ton of connect/disconnects for the USB side and I can imagine various PCs on the network accidentally indexing, pinging or otherwise unintentionally causing the NAS side to wakeup often.
Huh, I want this to exist for cheap, but I can't imagine it would be cheap to produce. There's a bit of coding there.
|
41,829 |
The answer to this is likely "It is not possible.", and from what I know about filesystems and storage, I would say the same thing. But, I thought I would try the great wisdom of SuperUser:
I'm looking for a NAS device that will serve the same content over USB and via SMB.
I have a device (let's call it the reader) which will read files from an external USB drive. I would like to attach a drive, but also make that drive writable across the network. The reader does not have a network port. I get that the reader considers the USB directly attached storage, so it partitions and formats it, while anything that served up the drive's content over the network (via SMB or something) is serving up file content and not a lower level storage device like the USB interface, and you'll end up with two different things having the filesystem mounted, which going to cause trouble.
|
2009/09/15
|
[
"https://superuser.com/questions/41829",
"https://superuser.com",
"https://superuser.com/users/9588/"
] |
I dont know if you ever solved this, but have a look at this, I just ordered one, had a similar requirement to you, I want to carry a pc around with me and thats it, and need to be able to easily share the data on it like a drive , such as AV progs or Hirens disc etc with other pc's
<http://cgi.ebay.co.uk/USB-Go-Link-PC-PC-Transfer-Network-Cable-Card-Reader-/120645125445?pt=UK_Computing_CablesConnectors_RL&hash=item1c17028545>
|
It is not possiblwe. USB disk file-systems are managed by a host computer which is aware of blocks, allocations, which files are open, where they are, etc. It is just a block device.
A NAS on the other hand maintains internal awareness of all of these factors and they won’t match the awareness of the computer that has attached the disk via a USB port.
SANS do this sort of thing, but in different volumes or partitions. iSCSI is the SAN equivalent of USB.
|
1,959,140 |
If I am given two 3-D points of a cube,how do I find the volume of that Cube?where $(x\_1, y\_1, z\_1)$ is the co-ordinate of one corner and $(x\_2, y\_2, z\_2)$ is the co-ordinate of the opposite corner.
|
2016/10/08
|
[
"https://math.stackexchange.com/questions/1959140",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/374055/"
] |
We can solve the system in the following way (though I'm not sure if it is "reasonable") :
We have
$$\sqrt y+\sqrt z-\sqrt x=\frac{a}{\sqrt x}\tag1$$
$$\sqrt z+\sqrt x-\sqrt y=\frac{b}{\sqrt y}\tag2$$
$$\sqrt x+\sqrt y-\sqrt z=\frac{c}{\sqrt z}\tag3$$
From $(1)$,
$$\sqrt z=\sqrt x-\sqrt y+\frac{a}{\sqrt x}\tag4$$
From $(2)(4)$,
$$\sqrt x-\sqrt y+\frac{a}{\sqrt x}+\sqrt x-\sqrt y=\frac{b}{\sqrt y},$$
i.e.
$$2\sqrt x-2\sqrt y+\frac{a}{\sqrt x}-\frac{b}{\sqrt y}=0$$
Multiplying the both sides by $\sqrt{xy}$ gives
$$2x\sqrt y-2y\sqrt x+a\sqrt y-b\sqrt x=0,$$
i.e.
$$y=\frac{2x\sqrt y+a\sqrt y-b\sqrt x}{2\sqrt x}\tag5$$
From $(3)(4)$,
$$\sqrt x+\sqrt y-\left(\sqrt x-\sqrt y+\frac{a}{\sqrt x}\right)=\frac{c}{\sqrt x-\sqrt y+\frac{a}{\sqrt x}},$$
i.e.
$$\frac{2\sqrt{xy}-a}{\sqrt x}=\frac{c\sqrt x}{x-\sqrt{xy}+a}$$
Multiplying the both sides by $\sqrt x\ (x-\sqrt{xy}+a)$ gives
$$2x\sqrt{xy}-2xy+3a\sqrt{xy}-ax-a^2=cx,$$
i.e.
$$y=\frac{2x\sqrt{xy}+3a\sqrt{xy}-ax-a^2-cx}{2x}\tag6$$
From $(5)(6)$,
$$\frac{2x\sqrt y+a\sqrt y-b\sqrt x}{2\sqrt x}=\frac{2x\sqrt{xy}+3a\sqrt{xy}-ax-a^2-cx}{2x},$$
i.e.
$$\sqrt y=\frac{a^2+(a-b+c)x}{2a\sqrt x}\tag7$$
From $(5)(7)$,
$$\left(\frac{a^2+(a-b+c)x}{2a\sqrt x}\right)^2=\frac{(2x+a)\frac{a^2+(a-b+c)x}{2a\sqrt x}-b\sqrt x}{2\sqrt x},$$
i.e.
$$\frac{(a^2+(a-b+c)x)^2}{4a^2x}=\frac{(2x+a)(a^2+(a-b+c)x)-2abx}{4ax}$$
Multiplying the both sides by $4a^2x$ gives
$$(a^2+(a-b+c)x)^2=a((2x+a)(a^2+(a-b+c)x)-2abx),$$
i.e.
$$x((a^2-b^2+2bc-c^2)x+a^3-a^2b-a^2c)=0$$
Finally, from $(7)(4)$,
$$\color{red}{x=\frac{a^2(b+c-a)}{(a+b-c)(c+a-b)},\quad y=\frac{b^2(c+a-b)}{(b+c-a)(a+b-c)},\quad z=\frac{c^2(a+b-c)}{(b+c-a)(c+a-b)}}$$
|
Here are some ideas which, with some hindsight, save you the long computations.
Notice that your system of equations is cyclic in the variables (x,y,z) and (a,b,c). I.e. the next equation follows from the previous one by shifting all variables by one position ($x \to y$ and simultaneoulsy $a\to b$ etc.), where the last variable becomes the first. This calls for a solution which is also cyclic, i.e. once you have found
$x=F(a,b,c)$, then $y=F(b,c,a)$ and $z = F(c,a,b)$.
Declare an unkown function $f$ and cylic $g,h$, i.e. $f=f(a,b,c)$, then $g=f(b,c,a)$ and $h = f(c,a,b)$.
Now you don't loose generality in writing your proposed solution as
$$ x = a^2 \frac{{f}}{{g} {h}}$$
which entails
$$ y = b^2 \frac{{g}}{{h} {f}} \quad ; \quad z = c^2 \frac{{h}}{{f} {g}}$$
Then your overall cyclic nature of $x,y,z$ is given.
Of course, here is where the hindsight came in. Since if you don't have a clue about the structure of the solution (see mathlove's answer), then you probably wouldn't choose such an ansatz. However, on plugging it into your equations things looks nice, since you get
$$
gh = b g + ch - af\\
hf = - b g + ch + af \\
fg = bg - ch + af
$$
Again, this system is cyclic.
From the structure of these equations, $f,g,h$ can be chosen as a weigted sum of the constants $a,b,c$. Since the system is cyclic, we need to do this only for one equation. With unknown $A,B,C$, write $f = A a+ Bb + Cc$, then $g = A b+ Bc + Ca$, and $h = A c+ Ba + Cb$. The first equation is
$$
(A b+ Bc + Ca)(A c+ Ba + Cb) - b (A b+ Bc + Ca) - c(A c+ Ba + Cb) + a(A a+ Bb + Cc) = 0
$$
Sorting gives
$$
a^2(BC+A) + b^2(AC-A)+c^2(AB-A) + ab(AB+C^2-C+B) +bc(A^2+BC-B-C) + ac(AC+B^2-B+C) =0
$$
All the coefficients must vanish.
$AB-A = 0$ gives $B=1$, then $AC-A = 0$ gives $C=1$, $BC+A = 0$ gives $A= -1$.
Hence $A=-1$, $B=1$, $C=1$ and indeed all coefficients vanish.
This gives immediately the final solution.
The "calculation" part only consisted in the very easy determining of $A,B,C$.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Well, if you don't use SSL, you will always be at a higher risk for someone trying to sniff your passwords. You probably just need to evaluate the risk factor of your site.
Also remember that even having SSL does not guarentee that your data is safe. It is really all in how you code it to make sure you provide the extra protection to your site.
I would suggest using a one way password encryption algorythm and validate that way.
Also, you can get SSL certificates really cheap, I have used Geotrust before and got a certification for 250.00. I am sure there are those out there that are cheaper.
|
Plain HTTP is vulnerable to sniffing. If you don't want to buy SSL certificates, you can use self-signed certificates and ask your clients to trust that certificate to circumvent the warning shown by the browser (as your authenticated users are just a few known admins, this approach makes perfect sense).
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
In the scenario you describe regular users would be exposed to session hijacking and all their information would also be transferred "in the clear". Unless you use a trusted CA the administrators might be exposed to a Man-in-the-middle attack.
Instead of a self-signed cert you might want to consider using a certificate from [CAcert](http://www.cacert.org/) and installing their root certs in the admin's browser.
|
Plain HTTP is vulnerable to sniffing. If you don't want to buy SSL certificates, you can use self-signed certificates and ask your clients to trust that certificate to circumvent the warning shown by the browser (as your authenticated users are just a few known admins, this approach makes perfect sense).
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Well, if you don't use SSL, you will always be at a higher risk for someone trying to sniff your passwords. You probably just need to evaluate the risk factor of your site.
Also remember that even having SSL does not guarentee that your data is safe. It is really all in how you code it to make sure you provide the extra protection to your site.
I would suggest using a one way password encryption algorythm and validate that way.
Also, you can get SSL certificates really cheap, I have used Geotrust before and got a certification for 250.00. I am sure there are those out there that are cheaper.
|
In the scenario you describe regular users would be exposed to session hijacking and all their information would also be transferred "in the clear". Unless you use a trusted CA the administrators might be exposed to a Man-in-the-middle attack.
Instead of a self-signed cert you might want to consider using a certificate from [CAcert](http://www.cacert.org/) and installing their root certs in the admin's browser.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Since only your admins will be using the secure session, just use a self-signed certificate. It's not the best user experience, but it's better to keep that information secure.
|
In the scenario you describe regular users would be exposed to session hijacking and all their information would also be transferred "in the clear". Unless you use a trusted CA the administrators might be exposed to a Man-in-the-middle attack.
Instead of a self-signed cert you might want to consider using a certificate from [CAcert](http://www.cacert.org/) and installing their root certs in the admin's browser.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Since only your admins will be using the secure session, just use a self-signed certificate. It's not the best user experience, but it's better to keep that information secure.
|
Use HTTPS with a free certificate. [StartCom](http://cert.startcom.org/) is free, and included in by Firefox browsers; since only your administrators will be logging in, they can easily import the CA if they want to use IE.
Don't skimp on security. Anecdotally, I have seen websites that sound similar to yours defaced just for kicks. It's something worth taking pains to avoid.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Since only your admins will be using the secure session, just use a self-signed certificate. It's not the best user experience, but it's better to keep that information secure.
|
Plain HTTP is vulnerable to sniffing. If you don't want to buy SSL certificates, you can use self-signed certificates and ask your clients to trust that certificate to circumvent the warning shown by the browser (as your authenticated users are just a few known admins, this approach makes perfect sense).
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Use HTTPS with a free certificate. [StartCom](http://cert.startcom.org/) is free, and included in by Firefox browsers; since only your administrators will be logging in, they can easily import the CA if they want to use IE.
Don't skimp on security. Anecdotally, I have seen websites that sound similar to yours defaced just for kicks. It's something worth taking pains to avoid.
|
Realistically, it's much more likely that one of the computers used to access the website will be compromised by a keylogger than the HTTP connection will be sniffed.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Well, if you don't use SSL, you will always be at a higher risk for someone trying to sniff your passwords. You probably just need to evaluate the risk factor of your site.
Also remember that even having SSL does not guarentee that your data is safe. It is really all in how you code it to make sure you provide the extra protection to your site.
I would suggest using a one way password encryption algorythm and validate that way.
Also, you can get SSL certificates really cheap, I have used Geotrust before and got a certification for 250.00. I am sure there are those out there that are cheaper.
|
Use HTTPS with a free certificate. [StartCom](http://cert.startcom.org/) is free, and included in by Firefox browsers; since only your administrators will be logging in, they can easily import the CA if they want to use IE.
Don't skimp on security. Anecdotally, I have seen websites that sound similar to yours defaced just for kicks. It's something worth taking pains to avoid.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Since only your admins will be using the secure session, just use a self-signed certificate. It's not the best user experience, but it's better to keep that information secure.
|
Realistically, it's much more likely that one of the computers used to access the website will be compromised by a keylogger than the HTTP connection will be sniffed.
|
878,520 |
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses.
How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108893/"
] |
Use HTTPS with a free certificate. [StartCom](http://cert.startcom.org/) is free, and included in by Firefox browsers; since only your administrators will be logging in, they can easily import the CA if they want to use IE.
Don't skimp on security. Anecdotally, I have seen websites that sound similar to yours defaced just for kicks. It's something worth taking pains to avoid.
|
Plain HTTP is vulnerable to sniffing. If you don't want to buy SSL certificates, you can use self-signed certificates and ask your clients to trust that certificate to circumvent the warning shown by the browser (as your authenticated users are just a few known admins, this approach makes perfect sense).
|
226,735 |
I am looking at establish a circuit allowing to detect when one or two wire are cut such as a tamper system. When the wire are cut it should signal this a GPIO.
I suppose I need to use a transistor connected to GPIO but I have a bit some difficulty to see how.
|
2016/04/06
|
[
"https://electronics.stackexchange.com/questions/226735",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/104309/"
] |

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fA8UqT.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
*Figure 1. GPIO normally pulled low by tamper loop. Cutting loop causes GPIO to be pulled high by R1.*
C1 will help eliminate any noise on a long tamper loop.
|
An alternative to detecting change in voltage on the GPIO pin would be to use a dedicated [current loop](https://en.wikipedia.org/wiki/Current_loop) controller. There exists many [4–20mA](https://electronics.stackexchange.com/tags/4-20ma/info) control circuits that will have a indicator pin for when there is no current flowing which you can monitor.
|
226,735 |
I am looking at establish a circuit allowing to detect when one or two wire are cut such as a tamper system. When the wire are cut it should signal this a GPIO.
I suppose I need to use a transistor connected to GPIO but I have a bit some difficulty to see how.
|
2016/04/06
|
[
"https://electronics.stackexchange.com/questions/226735",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/104309/"
] |

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fA8UqT.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
*Figure 1. GPIO normally pulled low by tamper loop. Cutting loop causes GPIO to be pulled high by R1.*
C1 will help eliminate any noise on a long tamper loop.
|
Pull up the GPIO externally to HIGH. Configure a cheap uC to trigger an interrupt when the pin value changes from HIGH->LOW.When you enter the ISR,you'l know that your circuit was tampered/cut.
If you want to go a little further,you could use an [Event Monitor](http://www.nxp.com/documents/data_sheet/PCF2127.pdf) to capture such an event for you and log the time when it occurred.
Note: The value of the wire must remain at a known value and not change/toggle. That is always HIGH. Or if you need to detect a LOW->HIGH,you can configure appropriately.
|
Subsets and Splits
Train Questions 500-600
This query retrieves a sample of questions with lengths between 500 and 600 characters, which offers basic filtering and limited insight into the dataset's contents.
Virus Queries and Responses
This query retrieves a limited set of records where the question or response contains the word "virus," offering basic filtering but limited analytical value.