qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
50,256,184
This is just a small portion of the data frame I am working with: ``` id drug start stop dose unit route 2010003 Amlodipine 2009-02-04 2009-11-19 1.5 mg Oral 2010003 Amlodipine 2009-11-19 2010-01-11 1.5 mg Oral 2010004 Cefprozil 2004-03-12 2004-03-19 175 mg Oral 2010004 Clobazam 2002-12-30 2003-01-01 5 mg Oral ``` I have a Stata `do` file, which shows what I am trying to do: ``` replace class = "ACE Inhibitor" if strmatch(upper(drug), "CAPTOPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRILAT*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "FOSINOPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "LISINOPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "RAMIPRIL*") replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE*") replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE/BENZOYL PEROXIDE*") replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE*") replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE/CLINDAMYCIN*") replace class = "Acne Medication" if strmatch(upper(drug), "ISOTRETINOIN*") replace class = "Acne Medication" if strmatch(upper(drug), "ERYTHROMYCIN/TRETINOIN*") replace class = "Acne Medication/Acute Promyelocytic Leukemia Medication" if strmatch(upper(drug), "TRETINOIN*") replace class = "Alpha Agonist" if strmatch(upper(drug), "XYLOMETAZOLINE*") replace class = "Alpha Blocker" if strmatch(upper(drug), "DOXAZOSIN*") replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENOXYBENZAMINE*") replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENTOLAMINE*") replace class = "Alpha Blocker" if strmatch(upper(drug), "PRAZOSIN*") replace class = "Alpha Blocker" if strmatch(upper(drug), "TAMSULOSIN*") replace class = "Alpha Blocker" if strmatch(upper(drug), "TERAZOSIN*") replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "CARVEDILOL*") replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "LABETALOL*") replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "PHENYLEPHRINE*") replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "MIDODRINE*") replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "CLONIDINE*") replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "DEXMEDETOMIDINE*") replace class = "Anaesthetic, general" if strmatch(upper(drug), "KETAMINE*") replace class = "Anaesthetic, general" if strmatch(upper(drug), "THIOPENTAL*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "BENZOCAINE*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE/FENTANYL*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "TETRACAINE*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "XYLOCAINE*") replace class = "Anaesthetic, local/Antiarrythmic" if strmatch(upper(drug), "LIDOCAINE*") replace class = "Anaesthetic, local/Antiseptic" if strmatch(upper(drug), "HEXYLRESORCINOL*") replace class = "Anaesthetic, topical" if strmatch(upper(drug), "LIDOCAINE/PRILOCAINE*") replace class = "Anaesthetic, topical" if strmatch(upper(drug), "PROPARACAINE*") replace class = "Analgesic" if strmatch(upper(drug), "ACETAMINOPHEN*") replace class = "Analgesic" if strmatch(upper(drug), "BELLADONNA & OPIUM SUPPOSITORY*") ``` I want to do the same classification in R but I do not know Stata. Note that drugs can have more than one `class`. Any advice and help would be greatly appreciated.
2018/05/09
[ "https://Stackoverflow.com/questions/50256184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Change the code with: ``` [Unit] Description=Atlassian Bamboo Agent After=syslog.target network.target [Service] Type=forking User=apps Group=apps ExecStart=/apps/bamboo-agent/bin/bamboo-agent.sh start ExecStop=/apps/bamboo-agent/bin/bamboo-agent.sh stop [Install] WantedBy=multi-user.target ``` Then reload and start it (as root or using sudo) ``` systemctl daemon-reload systemctl start bamboo-agent ``` Res: <https://community.atlassian.com/t5/Bamboo-questions/How-to-I-install-bamboo-agent-as-a-daemon-under-Linux/qaq-p/393880>
In recent version of bamboo it doesn't need to create service config files manually. But unfortunately it doesn't well documented on [bamboo documents](https://confluence.atlassian.com/display/BAMBOO/Bamboo+documentation). After you have installed bamboo agent and approve the agent on bamboo admin panel (see @DimiDak answer on <https://stackoverflow.com/a/55137681/6463720>): 1. Install bamboo agent service ``` YOUR/PATH/TO/bamboo-agent-home/bin/bamboo-agent.sh install ``` 2. Enable the service ``` systemctl enable bamboo-agent ``` 3. Start it ``` systemctl start bamboo-agent ```
50,256,184
This is just a small portion of the data frame I am working with: ``` id drug start stop dose unit route 2010003 Amlodipine 2009-02-04 2009-11-19 1.5 mg Oral 2010003 Amlodipine 2009-11-19 2010-01-11 1.5 mg Oral 2010004 Cefprozil 2004-03-12 2004-03-19 175 mg Oral 2010004 Clobazam 2002-12-30 2003-01-01 5 mg Oral ``` I have a Stata `do` file, which shows what I am trying to do: ``` replace class = "ACE Inhibitor" if strmatch(upper(drug), "CAPTOPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRILAT*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "FOSINOPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "LISINOPRIL*") replace class = "ACE Inhibitor" if strmatch(upper(drug), "RAMIPRIL*") replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE*") replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE/BENZOYL PEROXIDE*") replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE*") replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE/CLINDAMYCIN*") replace class = "Acne Medication" if strmatch(upper(drug), "ISOTRETINOIN*") replace class = "Acne Medication" if strmatch(upper(drug), "ERYTHROMYCIN/TRETINOIN*") replace class = "Acne Medication/Acute Promyelocytic Leukemia Medication" if strmatch(upper(drug), "TRETINOIN*") replace class = "Alpha Agonist" if strmatch(upper(drug), "XYLOMETAZOLINE*") replace class = "Alpha Blocker" if strmatch(upper(drug), "DOXAZOSIN*") replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENOXYBENZAMINE*") replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENTOLAMINE*") replace class = "Alpha Blocker" if strmatch(upper(drug), "PRAZOSIN*") replace class = "Alpha Blocker" if strmatch(upper(drug), "TAMSULOSIN*") replace class = "Alpha Blocker" if strmatch(upper(drug), "TERAZOSIN*") replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "CARVEDILOL*") replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "LABETALOL*") replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "PHENYLEPHRINE*") replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "MIDODRINE*") replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "CLONIDINE*") replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "DEXMEDETOMIDINE*") replace class = "Anaesthetic, general" if strmatch(upper(drug), "KETAMINE*") replace class = "Anaesthetic, general" if strmatch(upper(drug), "THIOPENTAL*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "BENZOCAINE*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE/FENTANYL*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "TETRACAINE*") replace class = "Anaesthetic, local" if strmatch(upper(drug), "XYLOCAINE*") replace class = "Anaesthetic, local/Antiarrythmic" if strmatch(upper(drug), "LIDOCAINE*") replace class = "Anaesthetic, local/Antiseptic" if strmatch(upper(drug), "HEXYLRESORCINOL*") replace class = "Anaesthetic, topical" if strmatch(upper(drug), "LIDOCAINE/PRILOCAINE*") replace class = "Anaesthetic, topical" if strmatch(upper(drug), "PROPARACAINE*") replace class = "Analgesic" if strmatch(upper(drug), "ACETAMINOPHEN*") replace class = "Analgesic" if strmatch(upper(drug), "BELLADONNA & OPIUM SUPPOSITORY*") ``` I want to do the same classification in R but I do not know Stata. Note that drugs can have more than one `class`. Any advice and help would be greatly appreciated.
2018/05/09
[ "https://Stackoverflow.com/questions/50256184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Change the code with: ``` [Unit] Description=Atlassian Bamboo Agent After=syslog.target network.target [Service] Type=forking User=apps Group=apps ExecStart=/apps/bamboo-agent/bin/bamboo-agent.sh start ExecStop=/apps/bamboo-agent/bin/bamboo-agent.sh stop [Install] WantedBy=multi-user.target ``` Then reload and start it (as root or using sudo) ``` systemctl daemon-reload systemctl start bamboo-agent ``` Res: <https://community.atlassian.com/t5/Bamboo-questions/How-to-I-install-bamboo-agent-as-a-daemon-under-Linux/qaq-p/393880>
The complete guide for bamboo 8.1.3 is the following, Bamboo DC/server must be running and accessible by the agent, we are also using remote agent token instead of authorization(RHEL 8 - jdk already installed): ``` $ sudo useradd --create-home -c "Bamboo Agent role account" bamboo-agent # define a password for bamboo-agent user if you want $ sudo su - bamboo-agent # get the jar installer from server $ wget http://<your-bamboo-server/DC>:<your-port>/agentServer/agentInstaller/atlassian-bamboo-agent-installer-8.1.3.jar # logout and become root again $ exit # install the software in the bamboo-home dir $ sudo java -Dbamboo.home=/home/bamboo-agent -jar /home/bamboo-agent/atlassian-bamboo-agent-installer-8.1.3.jar http://<your-bamboo-server/DC>:<your-port>/agentServer/ -t <your-token> install # install the daemon for systemd $ sudo /home/bamboo-agent/bin/bamboo-agent.sh install # the installer will create files as root, so change the owner and the group $ sudo chown -R bamboo-agent: /home/bamboo-agent/ # Change the user from the daemon $ sudo sed -i '/^Type=.*/a User=bamboo-agent\nGroup=bamboo-agent' /etc/systemd/system/bamboo-agent.service $ sudo systemctl daemon-reload $ sudo systemctl start bamboo-agent ``` Now you should be able to see the agent registered in the server. If not, login as the user(in our case bamboo-agent) and check the logs in the home dir. /JGG
2,014,099
i am trying to use velocity framework on google app engine. i wrote a small program with a main method and tried running it locally. i get the following exception : ``` Exception in thread "main" org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.ServletLogChute with the current runtime configuration. at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206) at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255) at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795) at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250) at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:107) at Main.main(Main.java:10) Caused by: java.lang.UnsupportedOperationException: Could not retrieve ServletContext from application attributes at org.apache.velocity.runtime.log.ServletLogChute.init(ServletLogChute.java:73) at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157) ... 5 more ``` Here is my program: ``` import java.io.StringWriter; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; public class Main { public static void main(String[] args) throws Exception{ /* first, get and initialize an engine */ VelocityEngine ve = new VelocityEngine(); ve.init(); /* next, get the Template */ Template t = ve.getTemplate( "helloworld.vm" ); /* create a context and add data */ VelocityContext context = new VelocityContext(); context.put("name", "World"); /* now render the template into a StringWriter */ StringWriter writer = new StringWriter(); t.merge( context, writer ); /* show the World */ System.out.println( writer.toString() ); } } ``` the same program runs perfectly fine on a normal eclipse project. what could be the problem?
2010/01/06
[ "https://Stackoverflow.com/questions/2014099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122466/" ]
Seems to only be the `ServletLogChute` class that requires the `ServletContext`, Velocity itself can work entirely standalone from a Servlet environment. Since you obviously don't have a servelt log, try adding the following before you call `ve.init()`: ``` ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute"); ``` ...or [check here if you have specific logging requirements](http://velocity.apache.org/engine/releases/velocity-1.6.2/developer-guide.html#Configuring_Logging).
This may not be the end of the world and story, but there's a list of GAE compatible software: <http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine> and I didn't find Velocity in it. It's possible people just forgot to test and include it in the list, but it's also possible Velocity brings some API with it that doesn't play nicely with GAE.
2,014,099
i am trying to use velocity framework on google app engine. i wrote a small program with a main method and tried running it locally. i get the following exception : ``` Exception in thread "main" org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.ServletLogChute with the current runtime configuration. at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206) at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255) at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795) at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250) at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:107) at Main.main(Main.java:10) Caused by: java.lang.UnsupportedOperationException: Could not retrieve ServletContext from application attributes at org.apache.velocity.runtime.log.ServletLogChute.init(ServletLogChute.java:73) at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157) ... 5 more ``` Here is my program: ``` import java.io.StringWriter; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; public class Main { public static void main(String[] args) throws Exception{ /* first, get and initialize an engine */ VelocityEngine ve = new VelocityEngine(); ve.init(); /* next, get the Template */ Template t = ve.getTemplate( "helloworld.vm" ); /* create a context and add data */ VelocityContext context = new VelocityContext(); context.put("name", "World"); /* now render the template into a StringWriter */ StringWriter writer = new StringWriter(); t.merge( context, writer ); /* show the World */ System.out.println( writer.toString() ); } } ``` the same program runs perfectly fine on a normal eclipse project. what could be the problem?
2010/01/06
[ "https://Stackoverflow.com/questions/2014099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122466/" ]
Seems to only be the `ServletLogChute` class that requires the `ServletContext`, Velocity itself can work entirely standalone from a Servlet environment. Since you obviously don't have a servelt log, try adding the following before you call `ve.init()`: ``` ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute"); ``` ...or [check here if you have specific logging requirements](http://velocity.apache.org/engine/releases/velocity-1.6.2/developer-guide.html#Configuring_Logging).
Velocity can be definitively made to run on GAE/J. [Apache Click](http://click.apache.org/) Framework that is using Velocity as it's template engine, works without a problem on GAE/J. It needs of course a [different configuration](http://click.apache.org/docs/extras-api/org/apache/click/extras/gae/GoogleAppEngineListener.html) than usual since GAE/J is a constraint environment, but nevertheless, it works.
204,711
We were migrating from [Java 6](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_6_.28December_11.2C_2006.29) to [Java 7](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29). The project is behind schedule and risks being dropped, in which case it will continue to use Java 6. What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, [Java 2D](http://en.wikipedia.org/wiki/Java_2D)/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use. [I am going through many sites like [Oracle adoption guide](http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/), bug database, [questions](https://stackoverflow.com/questions/741082/what-differences-will-java-7-have-from-java-6-and-what-will-it-mean-to-us-java?rq=1) on Stack Overflow]. Update: Thanks for the answers. We rescheduled the update to next release. Closest we got was security. Accepting the highest voted answer.
2013/07/13
[ "https://softwareengineering.stackexchange.com/questions/204711", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/3005/" ]
In general, there are a number of fairly broad changes to make things easier on the programmer. Your manager might not care too much about such things, but making programmers spend less time thinking about boilerplate code, and thus have more time to think about the actual goal of what they're implementing, should increase efficiency, decrease bugs, etc., which can be a **very** powerful argument. [Oracle has a fairly extensive list of changes](http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html), but it's rather lengthy, so I'll summarize as much as possible. Language features include: * [Less boilerplate on Generics.](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html) The code `Map<String, String> myMap = new HashMap<String, String>();` can be reduced to `Map<String, String> myMap = new HashMap<>()`. The compiler can infer the Generic types needed on the right side from the left, so your code gets a little shorter and quicker to read. * [Strings work in switch statements now](http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html), using the semantics of the `.equals()` method instead of `==`. * [Automatic resource management using try-with-resources.](http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html) This makes code cleaner, but also has an advantage over old-style try/finally-based code. If an exception is thrown in the try statement, and then another is thrown while closing, code which uses traditional try/finally statements will completely lose the original exception, and only pass up the one which was thrown in the finally block. In a try-with-resources statement, the runtime will suppress the exception that the close() calls threw, and bubble the original exception up the stack, under the assumption that this original exception is the one that caused all the problems in the first place. Additionally, instead of abandoning the other exception to the garbage collector, this suppression allows the close-thrown exceptions to be retrieved using `Throwable.getSuppressed`. * Numeric literals can be made easier to read. [All numeric literals allow underscores](http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html), so things like `int n = 1000000000` can be made into a much more readable `int n = 1_000_000_000`, which is much easier to parse as being one billion, and harder to type wrongly without noticing. Also, [binary literals are allowed](http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html) in the form `0b10110101`, making code that works with bit-fields a little nicer to read. * [Handling multiple exception types int the same catch statement](http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html) can be done, reducing duplicating code, and potentially making it easier to refactor later. Every one of these changes is something your manager might not directly care about, but they make it a little bit easier to write correct code without as much effort and thought, freeing your mind to focus a little more on the actual logic you're trying to implement, and they also make it a little easier to read code later, making debugging a little faster. On the API side, a number of API updates have also occurred: * [Security-wise](http://docs.oracle.com/javase/7/docs/technotes/guides/security/enhancements-7.html), several encryption methods have been added/deprecated, as crypto moves ever forward. * [File IO](http://docs.oracle.com/javase/7/docs/technotes/guides/io/enhancements.html#7) has been changed, ([this might be a better link, though](http://docs.oracle.com/javase/tutorial/essential/io/fileio.html) ) adding some better abstraction in a number of places. I haven't personally dived into the new IO stuff, but it looks like a very useful overhaul, making it much easier to work with the filesystem without quite as much pain. * [Unicode Support](http://docs.oracle.com/javase/7/docs/technotes/guides/intl/enhancements.7.html) is up to Unicode 6.0, along with a number of other internationalization enhancements. * [Java2D](http://docs.oracle.com/javase/7/docs/technotes/guides/2d/enhancements70.html), which you mentioned in your question, has been improved. Better Linux font support, better X11 rendering on modern machines, and handling of Tibetan scripts.
[try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) is a feature that's worth upgrading to Java 7 for, all on it's own. Resource leaks / memory leaks are a big risk in Java development and TWR reduces that risk significantly. I'll add the that new [NIO.2](http://docs.oracle.com/javase/tutorial/essential/io/fileio.html) File abstraction and Asynchronous capabilities are also worth moving to if your application has File/Networking I/O features.
204,711
We were migrating from [Java 6](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_6_.28December_11.2C_2006.29) to [Java 7](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29). The project is behind schedule and risks being dropped, in which case it will continue to use Java 6. What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, [Java 2D](http://en.wikipedia.org/wiki/Java_2D)/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use. [I am going through many sites like [Oracle adoption guide](http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/), bug database, [questions](https://stackoverflow.com/questions/741082/what-differences-will-java-7-have-from-java-6-and-what-will-it-mean-to-us-java?rq=1) on Stack Overflow]. Update: Thanks for the answers. We rescheduled the update to next release. Closest we got was security. Accepting the highest voted answer.
2013/07/13
[ "https://softwareengineering.stackexchange.com/questions/204711", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/3005/" ]
Java 6 has [reached EOL in February this year](http://www.oracle.com/technetwork/java/javase/eol-135779.html#Java6-end-public-updates) and will no longer receive public updates (including security) unless you buy very expensive enterprise support. That should be all the reason needed. Besides, overwhelming evidence suggests that backwards compatibility for Java runtimes is excellent. Chances are that you just have to replace the Java 6 installations with Java 7 and all applications will just continue to work without any problems. Of course this is not guaranteed and extensive tests are recommended to confirm that there will indeed be no problems.
[try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) is a feature that's worth upgrading to Java 7 for, all on it's own. Resource leaks / memory leaks are a big risk in Java development and TWR reduces that risk significantly. I'll add the that new [NIO.2](http://docs.oracle.com/javase/tutorial/essential/io/fileio.html) File abstraction and Asynchronous capabilities are also worth moving to if your application has File/Networking I/O features.
204,711
We were migrating from [Java 6](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_6_.28December_11.2C_2006.29) to [Java 7](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29). The project is behind schedule and risks being dropped, in which case it will continue to use Java 6. What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, [Java 2D](http://en.wikipedia.org/wiki/Java_2D)/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use. [I am going through many sites like [Oracle adoption guide](http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/), bug database, [questions](https://stackoverflow.com/questions/741082/what-differences-will-java-7-have-from-java-6-and-what-will-it-mean-to-us-java?rq=1) on Stack Overflow]. Update: Thanks for the answers. We rescheduled the update to next release. Closest we got was security. Accepting the highest voted answer.
2013/07/13
[ "https://softwareengineering.stackexchange.com/questions/204711", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/3005/" ]
Java 6 has [reached EOL in February this year](http://www.oracle.com/technetwork/java/javase/eol-135779.html#Java6-end-public-updates) and will no longer receive public updates (including security) unless you buy very expensive enterprise support. That should be all the reason needed. Besides, overwhelming evidence suggests that backwards compatibility for Java runtimes is excellent. Chances are that you just have to replace the Java 6 installations with Java 7 and all applications will just continue to work without any problems. Of course this is not guaranteed and extensive tests are recommended to confirm that there will indeed be no problems.
In general, there are a number of fairly broad changes to make things easier on the programmer. Your manager might not care too much about such things, but making programmers spend less time thinking about boilerplate code, and thus have more time to think about the actual goal of what they're implementing, should increase efficiency, decrease bugs, etc., which can be a **very** powerful argument. [Oracle has a fairly extensive list of changes](http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html), but it's rather lengthy, so I'll summarize as much as possible. Language features include: * [Less boilerplate on Generics.](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html) The code `Map<String, String> myMap = new HashMap<String, String>();` can be reduced to `Map<String, String> myMap = new HashMap<>()`. The compiler can infer the Generic types needed on the right side from the left, so your code gets a little shorter and quicker to read. * [Strings work in switch statements now](http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html), using the semantics of the `.equals()` method instead of `==`. * [Automatic resource management using try-with-resources.](http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html) This makes code cleaner, but also has an advantage over old-style try/finally-based code. If an exception is thrown in the try statement, and then another is thrown while closing, code which uses traditional try/finally statements will completely lose the original exception, and only pass up the one which was thrown in the finally block. In a try-with-resources statement, the runtime will suppress the exception that the close() calls threw, and bubble the original exception up the stack, under the assumption that this original exception is the one that caused all the problems in the first place. Additionally, instead of abandoning the other exception to the garbage collector, this suppression allows the close-thrown exceptions to be retrieved using `Throwable.getSuppressed`. * Numeric literals can be made easier to read. [All numeric literals allow underscores](http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html), so things like `int n = 1000000000` can be made into a much more readable `int n = 1_000_000_000`, which is much easier to parse as being one billion, and harder to type wrongly without noticing. Also, [binary literals are allowed](http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html) in the form `0b10110101`, making code that works with bit-fields a little nicer to read. * [Handling multiple exception types int the same catch statement](http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html) can be done, reducing duplicating code, and potentially making it easier to refactor later. Every one of these changes is something your manager might not directly care about, but they make it a little bit easier to write correct code without as much effort and thought, freeing your mind to focus a little more on the actual logic you're trying to implement, and they also make it a little easier to read code later, making debugging a little faster. On the API side, a number of API updates have also occurred: * [Security-wise](http://docs.oracle.com/javase/7/docs/technotes/guides/security/enhancements-7.html), several encryption methods have been added/deprecated, as crypto moves ever forward. * [File IO](http://docs.oracle.com/javase/7/docs/technotes/guides/io/enhancements.html#7) has been changed, ([this might be a better link, though](http://docs.oracle.com/javase/tutorial/essential/io/fileio.html) ) adding some better abstraction in a number of places. I haven't personally dived into the new IO stuff, but it looks like a very useful overhaul, making it much easier to work with the filesystem without quite as much pain. * [Unicode Support](http://docs.oracle.com/javase/7/docs/technotes/guides/intl/enhancements.7.html) is up to Unicode 6.0, along with a number of other internationalization enhancements. * [Java2D](http://docs.oracle.com/javase/7/docs/technotes/guides/2d/enhancements70.html), which you mentioned in your question, has been improved. Better Linux font support, better X11 rendering on modern machines, and handling of Tibetan scripts.
204,711
We were migrating from [Java 6](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_6_.28December_11.2C_2006.29) to [Java 7](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29). The project is behind schedule and risks being dropped, in which case it will continue to use Java 6. What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, [Java 2D](http://en.wikipedia.org/wiki/Java_2D)/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use. [I am going through many sites like [Oracle adoption guide](http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/), bug database, [questions](https://stackoverflow.com/questions/741082/what-differences-will-java-7-have-from-java-6-and-what-will-it-mean-to-us-java?rq=1) on Stack Overflow]. Update: Thanks for the answers. We rescheduled the update to next release. Closest we got was security. Accepting the highest voted answer.
2013/07/13
[ "https://softwareengineering.stackexchange.com/questions/204711", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/3005/" ]
In general, there are a number of fairly broad changes to make things easier on the programmer. Your manager might not care too much about such things, but making programmers spend less time thinking about boilerplate code, and thus have more time to think about the actual goal of what they're implementing, should increase efficiency, decrease bugs, etc., which can be a **very** powerful argument. [Oracle has a fairly extensive list of changes](http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html), but it's rather lengthy, so I'll summarize as much as possible. Language features include: * [Less boilerplate on Generics.](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html) The code `Map<String, String> myMap = new HashMap<String, String>();` can be reduced to `Map<String, String> myMap = new HashMap<>()`. The compiler can infer the Generic types needed on the right side from the left, so your code gets a little shorter and quicker to read. * [Strings work in switch statements now](http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html), using the semantics of the `.equals()` method instead of `==`. * [Automatic resource management using try-with-resources.](http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html) This makes code cleaner, but also has an advantage over old-style try/finally-based code. If an exception is thrown in the try statement, and then another is thrown while closing, code which uses traditional try/finally statements will completely lose the original exception, and only pass up the one which was thrown in the finally block. In a try-with-resources statement, the runtime will suppress the exception that the close() calls threw, and bubble the original exception up the stack, under the assumption that this original exception is the one that caused all the problems in the first place. Additionally, instead of abandoning the other exception to the garbage collector, this suppression allows the close-thrown exceptions to be retrieved using `Throwable.getSuppressed`. * Numeric literals can be made easier to read. [All numeric literals allow underscores](http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html), so things like `int n = 1000000000` can be made into a much more readable `int n = 1_000_000_000`, which is much easier to parse as being one billion, and harder to type wrongly without noticing. Also, [binary literals are allowed](http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html) in the form `0b10110101`, making code that works with bit-fields a little nicer to read. * [Handling multiple exception types int the same catch statement](http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html) can be done, reducing duplicating code, and potentially making it easier to refactor later. Every one of these changes is something your manager might not directly care about, but they make it a little bit easier to write correct code without as much effort and thought, freeing your mind to focus a little more on the actual logic you're trying to implement, and they also make it a little easier to read code later, making debugging a little faster. On the API side, a number of API updates have also occurred: * [Security-wise](http://docs.oracle.com/javase/7/docs/technotes/guides/security/enhancements-7.html), several encryption methods have been added/deprecated, as crypto moves ever forward. * [File IO](http://docs.oracle.com/javase/7/docs/technotes/guides/io/enhancements.html#7) has been changed, ([this might be a better link, though](http://docs.oracle.com/javase/tutorial/essential/io/fileio.html) ) adding some better abstraction in a number of places. I haven't personally dived into the new IO stuff, but it looks like a very useful overhaul, making it much easier to work with the filesystem without quite as much pain. * [Unicode Support](http://docs.oracle.com/javase/7/docs/technotes/guides/intl/enhancements.7.html) is up to Unicode 6.0, along with a number of other internationalization enhancements. * [Java2D](http://docs.oracle.com/javase/7/docs/technotes/guides/2d/enhancements70.html), which you mentioned in your question, has been improved. Better Linux font support, better X11 rendering on modern machines, and handling of Tibetan scripts.
There may be a reason why you should *not* switch to Java 7: If you have to use Oracle's VM and your software either runs on embedded hardware or you will distribute it with embedded hardware: Oracle changed the JRE's license so that it's *not* licensed if above conditions are met; you'll need to *buy* a Java SE embedded license. See [What does "general purpose system" mean for Java SE Embedded?](https://softwareengineering.stackexchange.com/q/166798/32523)
204,711
We were migrating from [Java 6](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_6_.28December_11.2C_2006.29) to [Java 7](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29). The project is behind schedule and risks being dropped, in which case it will continue to use Java 6. What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, [Java 2D](http://en.wikipedia.org/wiki/Java_2D)/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use. [I am going through many sites like [Oracle adoption guide](http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/), bug database, [questions](https://stackoverflow.com/questions/741082/what-differences-will-java-7-have-from-java-6-and-what-will-it-mean-to-us-java?rq=1) on Stack Overflow]. Update: Thanks for the answers. We rescheduled the update to next release. Closest we got was security. Accepting the highest voted answer.
2013/07/13
[ "https://softwareengineering.stackexchange.com/questions/204711", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/3005/" ]
Java 6 has [reached EOL in February this year](http://www.oracle.com/technetwork/java/javase/eol-135779.html#Java6-end-public-updates) and will no longer receive public updates (including security) unless you buy very expensive enterprise support. That should be all the reason needed. Besides, overwhelming evidence suggests that backwards compatibility for Java runtimes is excellent. Chances are that you just have to replace the Java 6 installations with Java 7 and all applications will just continue to work without any problems. Of course this is not guaranteed and extensive tests are recommended to confirm that there will indeed be no problems.
There may be a reason why you should *not* switch to Java 7: If you have to use Oracle's VM and your software either runs on embedded hardware or you will distribute it with embedded hardware: Oracle changed the JRE's license so that it's *not* licensed if above conditions are met; you'll need to *buy* a Java SE embedded license. See [What does "general purpose system" mean for Java SE Embedded?](https://softwareengineering.stackexchange.com/q/166798/32523)
1,791,622
Ok, we have two expressions: > > $30x + 1500$ > > $19x + 9000$ > > > The first thing to note is, the first expression is $100\%$ and the second expression is $0\%$. The second thing is to note in all of this is, $x$ is infinite in these expressions. Ok, my main question is where would $23x + 15590$ go in the range as a percent? and how do you prove this? I don't know how but I'll accept any answer that makes sense. Bearing in mind $x$ is infinite, how? Thank you though, I look forward to your answers. EDIT: Hello guys, I apologize if that didn't make any sense. I meant in terms of this: [link](https://math.stackexchange.com/questions/51509/how-to-calculate-percentage-of-value-inside-arbitrary-range)
2016/05/19
[ "https://math.stackexchange.com/questions/1791622", "https://math.stackexchange.com", "https://math.stackexchange.com/users/339400/" ]
I guess you mean three values linearly dependent on $x$, say $f(x), g(x), h(x),$ the third one falling between the former two for $x$ big enough; and you are asking about an asymptotic value of the proportion $$\frac{h-f}{g-f}$$ as $x$ grows to infinity. That is $$\begin{align} \lim\_{x\to\infty}\frac{(23x+15590)-(19x+9000)}{(30x+1500)-(19x+9000)} & = \lim\_{x\to\infty}\frac{4x+6590}{11x-7500} \\ & = \lim\_{x\to\infty}\frac{4+6590/x}{11-7500/x} \\ & = \frac{4+0}{11-0} \\ & = \frac 4{11} \\ & \approx 0,363636 \\ & \approx 36.4\% \end{align}$$ For example, here are some values of the fraction defined above: for $x=10^3\ \,$ it is $\approx 3.025714286$, for $x=10^4\ \,$ it is $\approx 0.454536586$, for $x=10^8\ \,$ it is $\approx 0.363644834$ and for $x=10^{10}$ it is $\approx 0.363636448$. But please note that the limit value as $x$ grows to infinity is **not** the same as a 'proportion of infinite values'! The former exists and can be calculated, the latter simply does not exist, is undefined.
Your objects are algebraic expressions. Among the possible interpretations are linear functions and straight lines in the plane. Interpreting them as linear functions would look like this: $$ f(x) = 30x + 1500 \\ g(x) = 19x + 9000 \\ h(x) = 23x + 15590 $$ The only thing that makes remotely sense to me is that you have some interpolation problem. $$ \phi(1) = f \\ \phi(0) = g \\ \phi(\lambda) = h $$ where $\phi$ is a map that maps a parameter $\lambda$ to some linear function. E.g. $$ \phi(\lambda) = \lambda f + (1-\lambda) g $$ would be such an interpolation. Alas your $h$ is probably not within the reachable functions of the above $\phi$. Let us check it: $$ \phi(\lambda) = \lambda(30x + 1500) + (1-\lambda)(19x +9000) \\ = (11 \lambda + 19) x + (9000 - 7500 \lambda) $$ comparison with $h$ gives the conditions $$ 11 \lambda + 19 = 23 \\ 9000 - 7500 \lambda = 15590 $$ or $$ \lambda = 4/11 > 0 \\ \lambda = -6590/7500 < 0 $$ so there is no $\lambda \in \mathbb{R}$ which would result in $\phi(\lambda) = h$.
662,190
I try to Check the latest Firefox and want to get all hashes in one TXT file. What I try to do is: ``` sha1sum firefox.tar.gz > sha.txt ``` and I try also: ``` md5sum firefox.tar.gz > sha.txt | sha1sum firefox.tar.gz > sha.txt | sha512sum firefox.tar.gz > sha.txt ``` but only the last in this case the sha512 is printed to the sha.txt. What am I doing wrong? Please can someone out there help me with this?
2015/08/16
[ "https://askubuntu.com/questions/662190", "https://askubuntu.com", "https://askubuntu.com/users/268803/" ]
You need to use the append redirector `>>` instead of `>` for the subsequent commands e.g. ``` sha1sum zeromq-4.1.2.tar.gz > sha.txt md5sum zeromq-4.1.2.tar.gz >> sha.txt sha512sum zeromq-4.1.2.tar.gz >> sha.txt ``` See the `Appending Redirected Output` section of the bash manual page (`man bash`).
The `>` redirector writes the command's output (`stdout`, not `stderr` - you use `2>` for that) to the file specified after it. If it already exists, the file will get overwritten. This behaviour is useful for the first of your commands: if there's an existing file, it should get deleted and replaced with the new one. However, as you need to append all further outputs instead of replacing the previous ones, you need to use the append-redirector `>>`. This will create a file if it does not exist yet, but *appends* the redirected output to the file, if it already exists. --- And please do not use the pipe `|` to write multiple commands in one line, which would redirect the first command's output (`stdout`) to the second command's input (`stdin`). You can use the semicolon (`;`) to just tell bash to execute one command after the other, as if it was a script file. If a command fails (return code is not 0), the remaining commands still get executed. Or you may chose the logic operators AND (`&&`) or OR (`||`): If you use `&&` to connect two commands, the second one will *only* be executed, *if the first one succeeds* (return code is 0). If it fails, none of the following commands will run. The `||` however *only* runs the second command *if the first one failed* (return code is not 0)! So in your case I would recommend you to use the semicolon: ``` md5sum firefox.tar.gz > sha.txt ; sha1sum firefox.tar.gz >> sha.txt ; sha512sum firefox.tar.gz >> sha.txt ```
662,190
I try to Check the latest Firefox and want to get all hashes in one TXT file. What I try to do is: ``` sha1sum firefox.tar.gz > sha.txt ``` and I try also: ``` md5sum firefox.tar.gz > sha.txt | sha1sum firefox.tar.gz > sha.txt | sha512sum firefox.tar.gz > sha.txt ``` but only the last in this case the sha512 is printed to the sha.txt. What am I doing wrong? Please can someone out there help me with this?
2015/08/16
[ "https://askubuntu.com/questions/662190", "https://askubuntu.com", "https://askubuntu.com/users/268803/" ]
As others have already pointed out the difference between `>` (overwrite) and `>>` (append) redirection operators, i am going to give couple of solutions. 1. You can use the command grouping `{}` feature of `bash` to send the output of all the commands in a single file : ``` { sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ;} >checksum.txt ``` 2. Alternately you can run the commands in a subshell `()` : ``` ( sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ) >checksum.txt ```
You need to use the append redirector `>>` instead of `>` for the subsequent commands e.g. ``` sha1sum zeromq-4.1.2.tar.gz > sha.txt md5sum zeromq-4.1.2.tar.gz >> sha.txt sha512sum zeromq-4.1.2.tar.gz >> sha.txt ``` See the `Appending Redirected Output` section of the bash manual page (`man bash`).
662,190
I try to Check the latest Firefox and want to get all hashes in one TXT file. What I try to do is: ``` sha1sum firefox.tar.gz > sha.txt ``` and I try also: ``` md5sum firefox.tar.gz > sha.txt | sha1sum firefox.tar.gz > sha.txt | sha512sum firefox.tar.gz > sha.txt ``` but only the last in this case the sha512 is printed to the sha.txt. What am I doing wrong? Please can someone out there help me with this?
2015/08/16
[ "https://askubuntu.com/questions/662190", "https://askubuntu.com", "https://askubuntu.com/users/268803/" ]
As others have already pointed out the difference between `>` (overwrite) and `>>` (append) redirection operators, i am going to give couple of solutions. 1. You can use the command grouping `{}` feature of `bash` to send the output of all the commands in a single file : ``` { sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ;} >checksum.txt ``` 2. Alternately you can run the commands in a subshell `()` : ``` ( sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ) >checksum.txt ```
The `>` redirector writes the command's output (`stdout`, not `stderr` - you use `2>` for that) to the file specified after it. If it already exists, the file will get overwritten. This behaviour is useful for the first of your commands: if there's an existing file, it should get deleted and replaced with the new one. However, as you need to append all further outputs instead of replacing the previous ones, you need to use the append-redirector `>>`. This will create a file if it does not exist yet, but *appends* the redirected output to the file, if it already exists. --- And please do not use the pipe `|` to write multiple commands in one line, which would redirect the first command's output (`stdout`) to the second command's input (`stdin`). You can use the semicolon (`;`) to just tell bash to execute one command after the other, as if it was a script file. If a command fails (return code is not 0), the remaining commands still get executed. Or you may chose the logic operators AND (`&&`) or OR (`||`): If you use `&&` to connect two commands, the second one will *only* be executed, *if the first one succeeds* (return code is 0). If it fails, none of the following commands will run. The `||` however *only* runs the second command *if the first one failed* (return code is not 0)! So in your case I would recommend you to use the semicolon: ``` md5sum firefox.tar.gz > sha.txt ; sha1sum firefox.tar.gz >> sha.txt ; sha512sum firefox.tar.gz >> sha.txt ```
12,101
I have a Flex 3000 connected via RG-11 coax to a inverted V fan dipole tuned for 40m and 20m on my roof. I have an "ugly" balun up on the mast by the antenna. I further have the feed-line going into a lightning suppressor where the line enters into the house and is connected to my 8 foot ground rod. I realize that my coax is not 50ohm (it's 75ohm) but I'm operating at 80, 40, and 20m. My SWR is 1.1 on 40m and 1.4 on 20m and my ATU takes care of the rest. My understanding is that this should not be much of a factor on HF. In fact this coax is plenum rated so it has the extra shielding as well so it's very well guarded from external interference. Unless of course that extra shielding is having the reverse effect allowing even more RFI to flow down the shielding as it's acting as a fantastic antenna. Hence why I'm trying to do what I'll explain next... I'm trying to reduce various RFI on 80m and 40m (some 20m) coming into my shack (and also eliminate RFI going out to various devices by my transmissions) but have not had much success. I'm trying to use ferrite cores to help reduce some of this... I have these Fair-Rite ferrite cores from www.mouser.ca... [Mouser Link](https://www.mouser.ca/ProductDetail/Fair-Rite/2631803802?qs=%2Fha2pyFadui69ZHDvBYwaNp1oYkvVAjIv5TPhphggYvPCnPIGmFbbQ%3D%3D) Which should be these specific cores on the Fair-Rite Site... [Fair-Rite Link](https://www.fair-rite.com/product/round-cable-emi-suppression-cores-2631803802/) My understanding is that these are the #31 material as mentioned in numerous documents, not the least of which is Jim Brown's (K9YC) Guide to RFI, Ferrites, Baluns, and Audio Interfacing (often times noted as the "Bible" of RFI finding and reduction)... I've played with these toroid cores on an off for the past 3 years. I keep coming back to them as I'm hoping to reduce the RFI in my shack. However each time I've tried to use these cores, they've made exactly zero difference. For example I have a known source of RFI which is a birdie caused by my main 27" monitor (an Apple model). I see this birdie on 80m. I've tried wrapping the power cord multiple times and no luck. Zero effect. However this is just a birdie so I can deal with it. Another example is when I'm transmitting I hear the RFI over my speakers in the shack. This is a Logitech 5500 system. It all works from a main sub woofer that all the speakers then connect too. I've disconnected all the speakers and still get the RFI through the main woofer. I've wrapped the power cord of the woofer about a dozen times through two cores each. Zero difference on the RFI leaking into the speaker. As mentioned I use a Flex 3000 so having a PC and a speaker is essential. Again I can get around this and use wireless headphones but it's not ideal. I've also tried a Bifilar choke as detailed in a presentation PDF from K9YC again starting on page 45 here <https://www.qsl.net/w/wa3mej//Articles/K9YC/CoaxChokesPPT.pdf> I have a picture of the one I've made... [![My Bifilar Choke wound with #14 THHN wire](https://i.stack.imgur.com/MVgrg.jpg)](https://i.stack.imgur.com/MVgrg.jpg) This was done with #14 THHN wire as detailed in the presentation above on page 47. This was connected to my feed-line on one end and the other end went straight into my flex-3000. I have various other sources within my house that I'm attempting to deal with but I'm trying to mitigate a few of them with cores. But the cores just seem to make absolutely no difference. Either I've got the wrong cores or I'm missing something and am not doing it correctly? I bought these things and I would've thought I would have at least seen marginal improvements but so far they've been useless. Any suggestions on what I'm missing? **UPDATE 1** Here's some pictures of my antenna setup and my ugly balun. Obviously the height of the antenna is not ideal but this is up on the second floor. I've since added a vertical dipole (Comet 250B) which is not shown. As you can see the balun has coax seal all over it so I'll have to pull all that off and switch out the balun for my ferrite choke. I notice in the pictures that the coax seems to be drooping on my balun which I didn't notice earlier. Could this also be a factor? I've also included a picture of my new ground setup... [![Antenna Setup](https://i.stack.imgur.com/0PmlC.jpg)](https://i.stack.imgur.com/0PmlC.jpg) Antenna Setup [![Ugly Balun](https://i.stack.imgur.com/erWei.jpg)](https://i.stack.imgur.com/erWei.jpg) Ugly Balun [![New Ground Setup](https://i.stack.imgur.com/E8ae9.jpg)](https://i.stack.imgur.com/E8ae9.jpg) New Ground Setup **Update 2** I've tried to make a quick and dirty version of the RFI detector that Phil Frost - W8II has pointed out. This is based not he link provided in the first answer below. Here's a couple of pictures of my detector. It include the snap on ferrite with 10 turns of wire through into a breadboard where I just plugged in the components for now. I'm using a 101 nf cap (I assume that it is nF as there is only the number on it) and a 47 Ω and 100 Ω resistor. You'll see a red LED. I don't have any diodes handy at the moment but have them on order. I thought I would try the LED to see if it would work. Unfortunately I don't get any reading on my multimeter. I have it set to 200mA and I put the ferrite beside my feed line. It just reads 00.0 all the time when I transmit. I'm not sure if that's good as I don't have any common mode current, or more likely I've done the detector wrong. Here is a picture of my detector and my multimeter. [![Detector](https://i.stack.imgur.com/cA7yZ.jpg)](https://i.stack.imgur.com/cA7yZ.jpg) Detector [![Multimeter](https://i.stack.imgur.com/GD9uZ.jpg)](https://i.stack.imgur.com/GD9uZ.jpg) Multimeter
2018/10/25
[ "https://ham.stackexchange.com/questions/12101", "https://ham.stackexchange.com", "https://ham.stackexchange.com/users/13444/" ]
That does look like a fine core to use, and the photo of your construction looks good. Your coax isn't causing any problems with noise. Try putting the choke at the *feedpoint*, not at the *radio*, in lieu of the ugly balun you have now. A choke at the radio will do little since the coax shield, connector, and enclosure of the radio already form a continuous shield around all the receiving circuitry. The objective with the balun is to [eliminate common-mode current on the feedline](https://ham.stackexchange.com/questions/538/using-a-balun-with-a-resonant-dipole). A feedline with common-mode current is part of the radiating and receiving antenna, and since it runs into the shack it's close to all kinds of noise generating electronics. A functional balun suppresses common-mode current on the feedline so only the antenna, which is farther away from noise sources, is the only part radiating or receiving. Often this reduces RFI. Ugly baluns can be ineffective. Since they are a purely reactive impedance they can't dissipate noise power, only redirect it. In some cases the reactance of the ugly balun combines with the common-mode reactance of the feedline or tower to make a resonant circuit which is worse than no balun. A properly selected ferrite on the other hand has a significant resistive component to its impedance, and thus works in all cases as it can convert noise power to heat. Fixing RFI problems like you describe can be difficult if you don't know what's working and what isn't. If you aren't certain that feedline common-mode problems have been eliminated, trying to fix a noise source by putting ferrites around it is a futile exercise since all the wiring in your home is part of the antenna. So I suggest you [measure the common-mode current](https://ham.stackexchange.com/q/1271/218) with the ugly balun, and then with the ferrite choke. You might try different ferrite choke designs to find one that works well. The number of turns, core material, and core geometry make a difference. The [K9YC presentation you referenced](https://www.qsl.net/w/wa3mej//Articles/K9YC/CoaxChokesPPT.pdf) discusses it in some detail. [G3TXQ also has some good data](http://www.karinya.net/g3txq/chokes/). You can use these resources as a starting point for a design and then confirm the results with measurement. Only after confirming feedline common-mode issues are resolved, go around the house and identify noise sources. Putting ferrites on the cables leaving a noisy device eliminates the "antenna" they use to radiate noise.
In addition to everything Phil wrote, a possible "quick fix" might result if you wrap several turns of every cable between the radio and the PC through a ferrite toroid. I have encountered several cases of RFI resulting from ground loops and other mismatches between pieces of connected equipment. You may need to "divide and conquer" the total, complex problem of multiple conductors and their interactions into multiple, simpler problems. For example, what happens if you replace the Flex+PC with a standalone rig operating off a battery? Eliminating conductors and their interactions, one by one, may be the only way to identify the culprit. My dad and Elemer, K1DXB (SK), suffered terrific RFI until he replaced his metal desk with a wooden unit. Apparently, the conductive desk created troublesome coupling paths!
12,101
I have a Flex 3000 connected via RG-11 coax to a inverted V fan dipole tuned for 40m and 20m on my roof. I have an "ugly" balun up on the mast by the antenna. I further have the feed-line going into a lightning suppressor where the line enters into the house and is connected to my 8 foot ground rod. I realize that my coax is not 50ohm (it's 75ohm) but I'm operating at 80, 40, and 20m. My SWR is 1.1 on 40m and 1.4 on 20m and my ATU takes care of the rest. My understanding is that this should not be much of a factor on HF. In fact this coax is plenum rated so it has the extra shielding as well so it's very well guarded from external interference. Unless of course that extra shielding is having the reverse effect allowing even more RFI to flow down the shielding as it's acting as a fantastic antenna. Hence why I'm trying to do what I'll explain next... I'm trying to reduce various RFI on 80m and 40m (some 20m) coming into my shack (and also eliminate RFI going out to various devices by my transmissions) but have not had much success. I'm trying to use ferrite cores to help reduce some of this... I have these Fair-Rite ferrite cores from www.mouser.ca... [Mouser Link](https://www.mouser.ca/ProductDetail/Fair-Rite/2631803802?qs=%2Fha2pyFadui69ZHDvBYwaNp1oYkvVAjIv5TPhphggYvPCnPIGmFbbQ%3D%3D) Which should be these specific cores on the Fair-Rite Site... [Fair-Rite Link](https://www.fair-rite.com/product/round-cable-emi-suppression-cores-2631803802/) My understanding is that these are the #31 material as mentioned in numerous documents, not the least of which is Jim Brown's (K9YC) Guide to RFI, Ferrites, Baluns, and Audio Interfacing (often times noted as the "Bible" of RFI finding and reduction)... I've played with these toroid cores on an off for the past 3 years. I keep coming back to them as I'm hoping to reduce the RFI in my shack. However each time I've tried to use these cores, they've made exactly zero difference. For example I have a known source of RFI which is a birdie caused by my main 27" monitor (an Apple model). I see this birdie on 80m. I've tried wrapping the power cord multiple times and no luck. Zero effect. However this is just a birdie so I can deal with it. Another example is when I'm transmitting I hear the RFI over my speakers in the shack. This is a Logitech 5500 system. It all works from a main sub woofer that all the speakers then connect too. I've disconnected all the speakers and still get the RFI through the main woofer. I've wrapped the power cord of the woofer about a dozen times through two cores each. Zero difference on the RFI leaking into the speaker. As mentioned I use a Flex 3000 so having a PC and a speaker is essential. Again I can get around this and use wireless headphones but it's not ideal. I've also tried a Bifilar choke as detailed in a presentation PDF from K9YC again starting on page 45 here <https://www.qsl.net/w/wa3mej//Articles/K9YC/CoaxChokesPPT.pdf> I have a picture of the one I've made... [![My Bifilar Choke wound with #14 THHN wire](https://i.stack.imgur.com/MVgrg.jpg)](https://i.stack.imgur.com/MVgrg.jpg) This was done with #14 THHN wire as detailed in the presentation above on page 47. This was connected to my feed-line on one end and the other end went straight into my flex-3000. I have various other sources within my house that I'm attempting to deal with but I'm trying to mitigate a few of them with cores. But the cores just seem to make absolutely no difference. Either I've got the wrong cores or I'm missing something and am not doing it correctly? I bought these things and I would've thought I would have at least seen marginal improvements but so far they've been useless. Any suggestions on what I'm missing? **UPDATE 1** Here's some pictures of my antenna setup and my ugly balun. Obviously the height of the antenna is not ideal but this is up on the second floor. I've since added a vertical dipole (Comet 250B) which is not shown. As you can see the balun has coax seal all over it so I'll have to pull all that off and switch out the balun for my ferrite choke. I notice in the pictures that the coax seems to be drooping on my balun which I didn't notice earlier. Could this also be a factor? I've also included a picture of my new ground setup... [![Antenna Setup](https://i.stack.imgur.com/0PmlC.jpg)](https://i.stack.imgur.com/0PmlC.jpg) Antenna Setup [![Ugly Balun](https://i.stack.imgur.com/erWei.jpg)](https://i.stack.imgur.com/erWei.jpg) Ugly Balun [![New Ground Setup](https://i.stack.imgur.com/E8ae9.jpg)](https://i.stack.imgur.com/E8ae9.jpg) New Ground Setup **Update 2** I've tried to make a quick and dirty version of the RFI detector that Phil Frost - W8II has pointed out. This is based not he link provided in the first answer below. Here's a couple of pictures of my detector. It include the snap on ferrite with 10 turns of wire through into a breadboard where I just plugged in the components for now. I'm using a 101 nf cap (I assume that it is nF as there is only the number on it) and a 47 Ω and 100 Ω resistor. You'll see a red LED. I don't have any diodes handy at the moment but have them on order. I thought I would try the LED to see if it would work. Unfortunately I don't get any reading on my multimeter. I have it set to 200mA and I put the ferrite beside my feed line. It just reads 00.0 all the time when I transmit. I'm not sure if that's good as I don't have any common mode current, or more likely I've done the detector wrong. Here is a picture of my detector and my multimeter. [![Detector](https://i.stack.imgur.com/cA7yZ.jpg)](https://i.stack.imgur.com/cA7yZ.jpg) Detector [![Multimeter](https://i.stack.imgur.com/GD9uZ.jpg)](https://i.stack.imgur.com/GD9uZ.jpg) Multimeter
2018/10/25
[ "https://ham.stackexchange.com/questions/12101", "https://ham.stackexchange.com", "https://ham.stackexchange.com/users/13444/" ]
The answers here are excellent and I have little to add other than to emphasise / RFI problems are hard / Consider the case of the RFI problem discussed in Electronics Stack Exchange ( <https://electronics.stackexchange.com/questions/402021/how-do-i-specify-a-low-rfi-led-driver/402029#402029> ). Everything has been ferrited to death (5000 ohm common mode chokes surrounding all wires connected to the source and the receiver) and yet S9-11 noise levels appear across multiple bands when the device operates. A tiny little transformer, being fed an unfiltered sawtooth current, is radiating enough to make it 30 feet to the properly-choked receiving antenna, ruining several bands. The fix is to replace the offending device. Sometimes you do everything "right" and it still just is not enough.
In addition to everything Phil wrote, a possible "quick fix" might result if you wrap several turns of every cable between the radio and the PC through a ferrite toroid. I have encountered several cases of RFI resulting from ground loops and other mismatches between pieces of connected equipment. You may need to "divide and conquer" the total, complex problem of multiple conductors and their interactions into multiple, simpler problems. For example, what happens if you replace the Flex+PC with a standalone rig operating off a battery? Eliminating conductors and their interactions, one by one, may be the only way to identify the culprit. My dad and Elemer, K1DXB (SK), suffered terrific RFI until he replaced his metal desk with a wooden unit. Apparently, the conductive desk created troublesome coupling paths!
30,515,377
I am writing a c++ code for a Monte Carlo simulation. As such, I need to generate many numbers uniformly distributed between [0,1). I included the following code taken from [here](http://www.cplusplus.com/reference/random/uniform_real_distribution/) to generate my numbers: ``` // uniform_real_distribution #include <iostream> #include <random> std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0,1.0); int main() { double number = distribution(generator); //rnd number uniformly distributed between [0,1) return 0; } ``` So every time I need a new number, I just call `distribution(generator)`. I run my Monte Carlo simulation to get many sample results. The results should be normally distributed around the real mean (that is unknown). When I run a chi-square goodness-of-fit test to check if they are normally distributed, my sample results do not pass the test sometimes. The key word here is "sometimes", so this made me think that I called `distribution(generator)` too many times and in the end I lost randomness of the generated numbers. I am talking about 10^11 numbers generated in each simulation. Could it be possible? What if I reset the distribution with `distribution.reset()` before I call it? Would that solve my problem? Thanks for any suggestion you may have.
2015/05/28
[ "https://Stackoverflow.com/questions/30515377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950486/" ]
If a random number generator doesn't fail a test sometimes, then the test is too weak. For example, if a test has a 99% degree of confidence, a perfect random number generator should be expected to fail it about 1% of the time. For example, consider a perfectly fair coin. If you flip it 1,000 times, you will get on average 500 heads. If you want to use this as a test for randomness, you compute the range of values that a fair coin will fall within some percentage of the time. Then you make sure your random number generator doesn't fail the test more often than expected. Your testing methodology -- expecting a random number generator to pass every test every time -- only works if your tests are *very* weak. That would allow poor random number generators to pass too often and is not a good testing methodology. True story: A random number generator that I implemented was rigorously tested by [an independent testing lab](http://www.tstglobal.com/services/igaming/). They subjected it to 100 tests, each using millions of samples and testing for various properties. Each test had a 99% degree of confidence. The RNG failed 3 tests, which was within the expected range, and so passed the testing portion of the certification. That an RNG passes these extremely rigorous tests the vast majority of the time demonstrates that it's a very, very good RNG, perhaps perfect. It's hard to write a broken RNG that passes any of these tests ever. You need to compute the probability that a perfect RNG will fail your test and then see if your RNG shows a failure rate close to that expected.
The random generator algorithm used by STL is not specified in the standard, so you cannot know for sure how long the random sequence is without knowing what random number generation algorithm has been used. Its probably one of a small set of know to be good and fast generators like Mersenne twister or CMWC. There are many ways that random number generators are rated, but in your question I think you want to know the period - how long until the numbers repeat. The period will also depend on the initial conditions. A good standard CMWC generator, CMWC 4096 has a period of 2^131104. A standard Mersenne generator, MT19937 has a period of 2^19937. But all bets are off if the STL implementation you are using uses a poorly chosen algorithm. Reseeding before every call, or even frequently will, especially if the seeds are not well chosen, will ruin the statistical properties of the generator. You're usually best off just seeding it once, and calling it from there.
30,515,377
I am writing a c++ code for a Monte Carlo simulation. As such, I need to generate many numbers uniformly distributed between [0,1). I included the following code taken from [here](http://www.cplusplus.com/reference/random/uniform_real_distribution/) to generate my numbers: ``` // uniform_real_distribution #include <iostream> #include <random> std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0,1.0); int main() { double number = distribution(generator); //rnd number uniformly distributed between [0,1) return 0; } ``` So every time I need a new number, I just call `distribution(generator)`. I run my Monte Carlo simulation to get many sample results. The results should be normally distributed around the real mean (that is unknown). When I run a chi-square goodness-of-fit test to check if they are normally distributed, my sample results do not pass the test sometimes. The key word here is "sometimes", so this made me think that I called `distribution(generator)` too many times and in the end I lost randomness of the generated numbers. I am talking about 10^11 numbers generated in each simulation. Could it be possible? What if I reset the distribution with `distribution.reset()` before I call it? Would that solve my problem? Thanks for any suggestion you may have.
2015/05/28
[ "https://Stackoverflow.com/questions/30515377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950486/" ]
The random generator algorithm used by STL is not specified in the standard, so you cannot know for sure how long the random sequence is without knowing what random number generation algorithm has been used. Its probably one of a small set of know to be good and fast generators like Mersenne twister or CMWC. There are many ways that random number generators are rated, but in your question I think you want to know the period - how long until the numbers repeat. The period will also depend on the initial conditions. A good standard CMWC generator, CMWC 4096 has a period of 2^131104. A standard Mersenne generator, MT19937 has a period of 2^19937. But all bets are off if the STL implementation you are using uses a poorly chosen algorithm. Reseeding before every call, or even frequently will, especially if the seeds are not well chosen, will ruin the statistical properties of the generator. You're usually best off just seeding it once, and calling it from there.
Note that the strongness of your random sequence depends on the generator, not on the distribution. About the `default_random_engine` [the reference](http://www.cplusplus.com/reference/random/default_random_engine/) says "*a generator that provides at least acceptable engine behavior for relatively casual, inexpert, and/or lightweight use*"... probably not what you want. As suggested, you can replace it with a `std::mt19937`, I am not an expert so I don't know how long you can use it before losing randomness. To renew the randomness of your generator, you can use a `std::random_device` and use it to `seed()` from time to time the generator. On some implementation (you'll have to check) the `random_device` uses even special instructions of the CPU to generate "hard" random numbers as seeds. Alas, you cannot simply reseed every time because such hardware generation is quite slow.
30,515,377
I am writing a c++ code for a Monte Carlo simulation. As such, I need to generate many numbers uniformly distributed between [0,1). I included the following code taken from [here](http://www.cplusplus.com/reference/random/uniform_real_distribution/) to generate my numbers: ``` // uniform_real_distribution #include <iostream> #include <random> std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0,1.0); int main() { double number = distribution(generator); //rnd number uniformly distributed between [0,1) return 0; } ``` So every time I need a new number, I just call `distribution(generator)`. I run my Monte Carlo simulation to get many sample results. The results should be normally distributed around the real mean (that is unknown). When I run a chi-square goodness-of-fit test to check if they are normally distributed, my sample results do not pass the test sometimes. The key word here is "sometimes", so this made me think that I called `distribution(generator)` too many times and in the end I lost randomness of the generated numbers. I am talking about 10^11 numbers generated in each simulation. Could it be possible? What if I reset the distribution with `distribution.reset()` before I call it? Would that solve my problem? Thanks for any suggestion you may have.
2015/05/28
[ "https://Stackoverflow.com/questions/30515377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950486/" ]
If a random number generator doesn't fail a test sometimes, then the test is too weak. For example, if a test has a 99% degree of confidence, a perfect random number generator should be expected to fail it about 1% of the time. For example, consider a perfectly fair coin. If you flip it 1,000 times, you will get on average 500 heads. If you want to use this as a test for randomness, you compute the range of values that a fair coin will fall within some percentage of the time. Then you make sure your random number generator doesn't fail the test more often than expected. Your testing methodology -- expecting a random number generator to pass every test every time -- only works if your tests are *very* weak. That would allow poor random number generators to pass too often and is not a good testing methodology. True story: A random number generator that I implemented was rigorously tested by [an independent testing lab](http://www.tstglobal.com/services/igaming/). They subjected it to 100 tests, each using millions of samples and testing for various properties. Each test had a 99% degree of confidence. The RNG failed 3 tests, which was within the expected range, and so passed the testing portion of the certification. That an RNG passes these extremely rigorous tests the vast majority of the time demonstrates that it's a very, very good RNG, perhaps perfect. It's hard to write a broken RNG that passes any of these tests ever. You need to compute the probability that a perfect RNG will fail your test and then see if your RNG shows a failure rate close to that expected.
Note that the strongness of your random sequence depends on the generator, not on the distribution. About the `default_random_engine` [the reference](http://www.cplusplus.com/reference/random/default_random_engine/) says "*a generator that provides at least acceptable engine behavior for relatively casual, inexpert, and/or lightweight use*"... probably not what you want. As suggested, you can replace it with a `std::mt19937`, I am not an expert so I don't know how long you can use it before losing randomness. To renew the randomness of your generator, you can use a `std::random_device` and use it to `seed()` from time to time the generator. On some implementation (you'll have to check) the `random_device` uses even special instructions of the CPU to generate "hard" random numbers as seeds. Alas, you cannot simply reseed every time because such hardware generation is quite slow.
17,928,097
I am trying to add a link inside a label in a ListView item template but I can't make it work. I have this label: ``` <asp:Label runat="server" ID="SummaryLabel" Text='<%# Eval("Summary").ToString().Substring(0,Math.Min(200,Eval("Summary").ToString().Length)) + "... " + "More"%>'/> ``` and I want the word More at the end to be a link to the details page of the item. Tried putting "More" inside an anchor tag and hyperlink but I get badly formed tags. I'd appreciate any help to solving this or suggestions on alternative approaches.
2013/07/29
[ "https://Stackoverflow.com/questions/17928097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665351/" ]
You can do what you want as follows: ``` <asp:Label runat="server" ID="SummaryLabel" Text='<%# Eval("Summary").ToString().Substring(0,Math.Min(200,Eval("Summary").ToString().Length)) + "... " + @"<a href=""Oherpage.aspx"">More</a>"%>'/> ``` Note how the `<a>` is constructed in there... `OtherPage.aspx` would be your link to whatever other page you need to send the user to.
Ok, revising, have you done this? ``` <asp:Label ...><Asp:HyperLink ...>More...</HyperLink> </Label> ```
51,277,457
I have a dictionary as follows ``` my_dict = { "key_1": "value_1", "key_2": { "key_1": True, "key_2": 1200 } "key_3": True, } ``` and in my class ``` @dataclass class TestClass: my_dict: typing.Dict[{str, str}, {str, typing.Dict[{str, bool}, {str, int}]}] ``` The above declaration is incorrect. If I want to add typing for my\_dict what it should be and how to write the structure since I am having different types as values?
2018/07/11
[ "https://Stackoverflow.com/questions/51277457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004875/" ]
You want to use a [`Union`](https://docs.python.org/3/library/typing.html#typing.Union) as the value for the dictionary: ``` from typing import Dict, Union @dataclass class TestClass: my_dict: Dict[str, Union[str, bool, int]] ``` The union informs the typechecker that values in the dictionary must be either `str`s, `bool`s, or `int`s. When getting values, you'll want to use `isinstance` to determine what to do with a value: ``` if isinstance(self.my_dict['a'], str): return self.my_dict['a'].encode('utf-8') else isinstance(self.my_dict['a'], bool): return not self.my_dict['a'] else: return self.my_dict['a'] / 10 ``` If you know that a key will contain a specific type, you can avoid the typechecker's complaints by using `cast`: ``` from typing import cast value = cast(bool, self.my_dict['some_bool']) ```
I'll take a stab it it. So, the type of the values looks to be pretty distinct and easy to determine at runtime. The code that accesses the dictionary data and performs some action on it dependent on its type can use *instanceof()* in an if/elif/else block. ``` def some_method(self, key): val = self.my_dict[key] if isinstance(val, str): # fixed from instanceof to isinstance... print val elif isinstance(val, dict): print "it was a dictionary" else: print "Guess it must have been an int or bool." ``` or you could test for type like so: if type(val) is str: dosomething()
91,669
I have a single select drop down and need to enable the user to clear his selection too. Is it elegant to do this: [![enter image description here](https://i.stack.imgur.com/UgB2z.png)](https://i.stack.imgur.com/UgB2z.png) Or, on selection of an option should the drop down be hidden, showing the selected items text along with the `X` mark beside it clicking on which the drop down would be shown again?
2016/03/21
[ "https://ux.stackexchange.com/questions/91669", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/80261/" ]
The phrase 'Please select a thing' implies that the user has not selected anything from the dropdown yet. To clear a selection, you can have two alternatives: 1. Add a 'Clear selection' choice in the dropdown. 2. Allow the user to switch back to 'Please select a thing' which will imply that the selection previously made has been undone. The [x] next to your dropdown confuses me. It seems like it would remove the entire dropdown, instead of just clearing the selection. My suggestion would be to use the dropdown itself for clearing options, staying within recognised UI patterns.
Your proposal looks fine to me as it is. I would say that you should not mess about with the interface. Do not have it morphing unless it is absolutely warranted... because that makes for a confusing user experience. Also in this particular case: no, do not force the user to click the [x] in order to make a new selection. It will be particularly annoying in case of mis-clicks.
91,669
I have a single select drop down and need to enable the user to clear his selection too. Is it elegant to do this: [![enter image description here](https://i.stack.imgur.com/UgB2z.png)](https://i.stack.imgur.com/UgB2z.png) Or, on selection of an option should the drop down be hidden, showing the selected items text along with the `X` mark beside it clicking on which the drop down would be shown again?
2016/03/21
[ "https://ux.stackexchange.com/questions/91669", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/80261/" ]
Your proposal looks fine to me as it is. I would say that you should not mess about with the interface. Do not have it morphing unless it is absolutely warranted... because that makes for a confusing user experience. Also in this particular case: no, do not force the user to click the [x] in order to make a new selection. It will be particularly annoying in case of mis-clicks.
One option would be to use the phrase 'Please select a thing' as a label above the field, and to include a 'blank' (as in empty) option in the dropdown or a "none". That way a user could select an option, and if they change their mind they can select the 'blank'/"none" option again. I would say one possible advantage of using a blank option, is that when the user scans over their entered information, it is easier for them to see that they have not entered a selection for this dropdown. It quickly and easily visible as an empty field, as there is no placeholder text in the field. This of course depends on implementation, and whether you want a label above the field. As for the 'X', I would lose it (certainly in my above suggestion), and if you really want it, change it to a small text link that says 'clear selection' or something similar.
91,669
I have a single select drop down and need to enable the user to clear his selection too. Is it elegant to do this: [![enter image description here](https://i.stack.imgur.com/UgB2z.png)](https://i.stack.imgur.com/UgB2z.png) Or, on selection of an option should the drop down be hidden, showing the selected items text along with the `X` mark beside it clicking on which the drop down would be shown again?
2016/03/21
[ "https://ux.stackexchange.com/questions/91669", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/80261/" ]
The phrase 'Please select a thing' implies that the user has not selected anything from the dropdown yet. To clear a selection, you can have two alternatives: 1. Add a 'Clear selection' choice in the dropdown. 2. Allow the user to switch back to 'Please select a thing' which will imply that the selection previously made has been undone. The [x] next to your dropdown confuses me. It seems like it would remove the entire dropdown, instead of just clearing the selection. My suggestion would be to use the dropdown itself for clearing options, staying within recognised UI patterns.
One option would be to use the phrase 'Please select a thing' as a label above the field, and to include a 'blank' (as in empty) option in the dropdown or a "none". That way a user could select an option, and if they change their mind they can select the 'blank'/"none" option again. I would say one possible advantage of using a blank option, is that when the user scans over their entered information, it is easier for them to see that they have not entered a selection for this dropdown. It quickly and easily visible as an empty field, as there is no placeholder text in the field. This of course depends on implementation, and whether you want a label above the field. As for the 'X', I would lose it (certainly in my above suggestion), and if you really want it, change it to a small text link that says 'clear selection' or something similar.
70,724,630
I've been trying the code below to get the spl-token account address for a specific token in a Solana wallet from the Solana wallet address, but I am having issues getting the result I am looking for. I run: ``` const web3 = require('@solana/web3.js'); (async () => { const solana = new web3.Connection("https://api.mainnet-beta.solana.com"); //the public solana address const accountPublicKey = new web3.PublicKey( "2B1Uy1UTnsaN1rBNJLrvk8rzTf5V187wkhouWJSApvGT" ); //mintAccount = the token mint address const mintAccount = new web3.PublicKey( "GLmaRDRmYd4u3YLfnj9eq1mrwxa1YfSweZYYZXZLTRdK" ); console.log( await solana.getTokenAccountsByOwner(accountPublicKey, { mint: mintAccount, }) ); })(); ``` I'm looking for the token account address in the return, 6kRT2kAVsBThd5cz6gaQtomaBwLxSp672RoRPGizikH4. I get: > > { context: { slot: 116402202 }, value: [ { account: [Object], > pubkey: [PublicKey] } ] } > > > I can drill down through this a bit using .value[0].pubkey or .value[0].account but ultimately can't get to the information i'm looking for, which is a return of 6kRT2kAVsBThd5cz6gaQtomaBwLxSp672RoRPGizikH4 Does anyone know what is going wrong? (Note I do not want to use the getOrCreateAssociatedAccountInfo() method, i'm trying to get the token account address without handling the wallets keypair)
2022/01/15
[ "https://Stackoverflow.com/questions/70724630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17929913/" ]
ISSUE SOLVED: I needed to grab the correct \_BN data and convert, solution below. ``` const web3 = require('@solana/web3.js'); (async () => { const solana = new web3.Connection("https://api.mainnet-beta.solana.com"); //the public solana address const accountPublicKey = new web3.PublicKey( "2B1Uy1UTnsaN1rBNJLrvk8rzTf5V187wkhouWJSApvGT" ); //mintAccount = the token mint address const mintAccount = new web3.PublicKey( "GLmaRDRmYd4u3YLfnj9eq1mrwxa1YfSweZYYZXZLTRdK" ); const account = await solana.getTokenAccountsByOwner(accountPublicKey, { mint: mintAccount}); console.log(account.value[0].pubkey.toString()); })(); ```
That will certainly work as a heavy-handed approach. As an alternative, you can try to just search for the associated token account owned by that wallet without creating it if it doesn't exist. You would essentially follow the logic at <https://github.com/solana-labs/solana-program-library/blob/0a61bc4ea30f818d4c86f4fe1863100ed261c64d/token/js/client/token.js#L539> except without the whole `catch` block.
36,131,129
I wasnt quite sure what to call this question but here is what i want to do: I am currently creating a series geneator for `chartjs` that will help me create my datasets. now the way i want to do it is by simply using `object keys` to extract data from each element in my array. Each element of an array could look something like this: [![enter image description here](https://i.stack.imgur.com/IXl3D.png)](https://i.stack.imgur.com/IXl3D.png) as you can see this object contains other objects inside of them. This creates a problem because say i want the name of the object `feedback_skill` i would have to do the following: ``` data.forEach(function (x) { x['feedback_skill']['name'] }); ``` Which cannot be hold into one variable. Now what i could do is pass the following array: `serieKey = ['feedback','name']` suggesting that the first element in the array is the first key and the next element is the variable i want to hit. However these datasets can have an unlimited number of layers so my question to you guys is: Is there a smart way of doing this?
2016/03/21
[ "https://Stackoverflow.com/questions/36131129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647457/" ]
I'm not aware of a native JavaScript way of doing this, but various JavaScript frameworks allow you to access deep-properties from objects like this. For example Dojo has [lang.getObject](https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#dojo-base-lang-getobject) and I can see that there is a [JQuery plugin](http://benalman.com/projects/jquery-getobject-plugin/) that does something similar, lodash [as well](https://lodash.com/docs#get). If you're not using these frameworks, then you could always create your own util function to perform something similar. These types of utility function allow you to pass the target as a "dot-notation" property, so you could call: ``` lang.getObject("feedback_skill.name", false, x) ``` Using Dojo for example, but they're all much of a muchness.
I don't see any problem with your approach, unlimited number of layers can be handled in the following manner : ``` data.forEach(function(x){ for(i in seriesKey) x = x[seriesKey[i]]; // x will contain whatever you wanted to retrieve when the loop ends doSomething(x); } ``` seriesKey can be an array like the one in your example, with as many elements as you need to traverse to the depth you want.
20,937
I recently started playing with reverse macro with my canon 50mm f1.8. A couple things I noticed immediately is: * Shallow depth of field * No control over aperture * difficult to shoot handheld I believe these are the common problems with this type of shooting Are there any techniques that I can use to improve/help with Reverse Macro shooting besides buying a Macro lens as they are kind of expensive. Here is what I've tried so far ![example](https://i.stack.imgur.com/bt4g3.jpg) ps. I have read [Are there macro focusing techniques for handheld shots?](https://photo.stackexchange.com/questions/18746/are-there-macro-focusing-techniques-for-handheld-shots) but focusing isn't really a problem.
2012/03/06
[ "https://photo.stackexchange.com/questions/20937", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/3782/" ]
I've faced similar problems and also was able to overcome a few of them. A few techniques that has proved to be efficient for me are: * Focus changes even if you move a millimeter. I tried so hard to keep my body as stiff as possible but that did NOT work. So, I just let it go. I start by looking at the blur image through the viewfinder, slowly move forward and start shooting as soon as the image looks clearer, keep shooting and moving all the way upto the point the image becomes blurry again. Do NOT move using your whole body/waist, instead try inhaling and exhaling slowly. * I always shoot in continuous mode which enables me to increase the chance of getting a better focused shot. * IS wont work, nor will aperture control. So, you'll need to set the aperture before detaching the lens. I usually use higher than normal ISO to be able to use a higher shutter speed, thus remove any chance of shake blur. * Not sure if you're using a reverse mount ring, if not, get one asap. It helps a lot and you can concentrate on things other than keeping your lens safe from falling. * DOF stacking is another technique you can apply. Its true I wasn't able to plan and execute DOF stacking yet, but if you take a lot of pictures of the same subject, chances are you'll find a couple or two which you can use to stack and gain greater DOF. * Use of external flash is also very helpful and let you use smaller aperture as well as higher shutter speed while keeping the ISO low. Generally you'd like to use a diffuser along with it. Use [this link](http://www.fredmiranda.com/forum/topic/621087) to get an idea about how to make your own DIY lighting setup for better macro shooting.
A tripod can be useful. Beside normal way you can focus moving your subject then :) I guess DOF can't be increased since you have no way of changing the aperture In my experience a dedicated macro lens gives better images (obvious), not much easier to focus without a tripod. Has an aperture that increases DOF. You can also try stacked lens, which result in rather small aperture and greater DOF. You need a long lens mounted on your camera and a short lens reverse mounted (or just placed) on the first one.
20,937
I recently started playing with reverse macro with my canon 50mm f1.8. A couple things I noticed immediately is: * Shallow depth of field * No control over aperture * difficult to shoot handheld I believe these are the common problems with this type of shooting Are there any techniques that I can use to improve/help with Reverse Macro shooting besides buying a Macro lens as they are kind of expensive. Here is what I've tried so far ![example](https://i.stack.imgur.com/bt4g3.jpg) ps. I have read [Are there macro focusing techniques for handheld shots?](https://photo.stackexchange.com/questions/18746/are-there-macro-focusing-techniques-for-handheld-shots) but focusing isn't really a problem.
2012/03/06
[ "https://photo.stackexchange.com/questions/20937", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/3782/" ]
I'd consider looking for a lens that has an aperture ring so you *can* (manually) control the aperture. Since you're mounting it reversed, it doesn't really matter what mount it uses -- just for example, an old manual-focus lens will be fine. At least in the US these are often available quite inexpensively ($10-15 is quite common, but probably half that with some looking). If you can't afford a tripod, for some macro work a bean bag (or sand bag) can work quite nicely. This trades off some versatility in favor of being small and inexpensive.
A tripod can be useful. Beside normal way you can focus moving your subject then :) I guess DOF can't be increased since you have no way of changing the aperture In my experience a dedicated macro lens gives better images (obvious), not much easier to focus without a tripod. Has an aperture that increases DOF. You can also try stacked lens, which result in rather small aperture and greater DOF. You need a long lens mounted on your camera and a short lens reverse mounted (or just placed) on the first one.
20,937
I recently started playing with reverse macro with my canon 50mm f1.8. A couple things I noticed immediately is: * Shallow depth of field * No control over aperture * difficult to shoot handheld I believe these are the common problems with this type of shooting Are there any techniques that I can use to improve/help with Reverse Macro shooting besides buying a Macro lens as they are kind of expensive. Here is what I've tried so far ![example](https://i.stack.imgur.com/bt4g3.jpg) ps. I have read [Are there macro focusing techniques for handheld shots?](https://photo.stackexchange.com/questions/18746/are-there-macro-focusing-techniques-for-handheld-shots) but focusing isn't really a problem.
2012/03/06
[ "https://photo.stackexchange.com/questions/20937", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/3782/" ]
I've faced similar problems and also was able to overcome a few of them. A few techniques that has proved to be efficient for me are: * Focus changes even if you move a millimeter. I tried so hard to keep my body as stiff as possible but that did NOT work. So, I just let it go. I start by looking at the blur image through the viewfinder, slowly move forward and start shooting as soon as the image looks clearer, keep shooting and moving all the way upto the point the image becomes blurry again. Do NOT move using your whole body/waist, instead try inhaling and exhaling slowly. * I always shoot in continuous mode which enables me to increase the chance of getting a better focused shot. * IS wont work, nor will aperture control. So, you'll need to set the aperture before detaching the lens. I usually use higher than normal ISO to be able to use a higher shutter speed, thus remove any chance of shake blur. * Not sure if you're using a reverse mount ring, if not, get one asap. It helps a lot and you can concentrate on things other than keeping your lens safe from falling. * DOF stacking is another technique you can apply. Its true I wasn't able to plan and execute DOF stacking yet, but if you take a lot of pictures of the same subject, chances are you'll find a couple or two which you can use to stack and gain greater DOF. * Use of external flash is also very helpful and let you use smaller aperture as well as higher shutter speed while keeping the ISO low. Generally you'd like to use a diffuser along with it. Use [this link](http://www.fredmiranda.com/forum/topic/621087) to get an idea about how to make your own DIY lighting setup for better macro shooting.
I'd consider looking for a lens that has an aperture ring so you *can* (manually) control the aperture. Since you're mounting it reversed, it doesn't really matter what mount it uses -- just for example, an old manual-focus lens will be fine. At least in the US these are often available quite inexpensively ($10-15 is quite common, but probably half that with some looking). If you can't afford a tripod, for some macro work a bean bag (or sand bag) can work quite nicely. This trades off some versatility in favor of being small and inexpensive.
67,771,195
I'm doing a polling method to my API every 5 seconds, to get real-time data. The code below works but after 1 hour of running, the page crash(Aww Snap, with the dinosaur image and error: out of memory). The data I'm collecting is quite large, and I'm expecting that javascript will offload the memory(garbage collection) every time the function is being called again. I can see in the Chrome Task Manager, the memory footprint is growing over time. Is there a way to clear the memory or offload the memory from growing over time? ``` data(){ return{ newdata:[], }; }, methods: { loadData:async function () { try { let response = await axios.get('/monitoring_data'); if (response.status != 200) { await new Promise(resolve => setTimeout(resolve, 1000)); await this.loadData(); }else { // Get the data this.newdata= response.data.Ppahvc; // Call loadData() again to get the next data await new Promise(resolve => setTimeout(resolve, 5000)); await this.loadData(); } } catch (e) { await this.loadData(); } }, }, mounted:function(){ this.loadData(); }, ```
2021/05/31
[ "https://Stackoverflow.com/questions/67771195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13687251/" ]
Use a `JOIN` in your query: ```sql SELECT * FROM movies_table m INNER JOIN directors_table d ON d.director_id = m.dir_id ``` And build the array structure in your loop: ```php while($r = mysqli_fetch_assoc($sth)) { $rows[] = [ 'id' => $r['id'], 'image' => $r['image'], /* other movie keys you need */ 'director' => [ 'id' => $r['director_id'], /* other director keys you need */ ] ]; } ```
Two solutions 1. Make a JOIN like @AymDev suggested in the first comment to your question. This might be the preferred solution if your tables are relatively small and you don't have any performance issues 2. Double query ``` // First retrieve all the directors and keep an array with their info. The Key of the array is the director ID $dataQuery = "SELECT * FROM directors_table"; $sth = mysqli_query($conn, $dataQuery); $directors = array(); while($r = mysqli_fetch_assoc($sth)) { $directors[$r['id']] = $r; } $dataQuery = "SELECT * FROM movies_table"; $sth = mysqli_query($conn, $dataQuery); $rows = array(); while($r = mysqli_fetch_assoc($sth)) { // Retrieve the director info from the previous array $r['director'] = $directors[$r['dir_id']]; $rows[] = $r; } $respObj->status = 'success'; $respObj->movies = $rows; $respJSON = json_encode($respObj); print $respJSON; ```
2,616,975
I am converting numbers between different bases without issues, but I'm struggling to understand the **why** the method I'm using works. If I convert $A5$ (base 16) to base 8, I would do the following: > > Turn $A5$ into binary (4 bits) > > > $A = 1010$ > > > $5 = 0101$ > > > $10100101$ (split into three bits) $= 010$ $100$ $101$ > > > $010$ = 2 > > > $100$ = 4 > > > $101$ = 5 > > > $A5$ (base 16) $= 245$ (base 8) > > > I know the answer is correct, but I don't understand why the binary is split into $X$ bits depending on the base, and how the value $X$ is chosen. If it's base 4, for example, how many bits should the binary be separated into when converting?
2018/01/23
[ "https://math.stackexchange.com/questions/2616975", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517621/" ]
This approach only works for bases that are powers of $2$. So, for base $2^k$ you convert to binary by concatenating strings of $k$ bits, one for each base-$2^k$ digit. In the other direction, you convert from base $2$ to base $2^k$ by dividing the binary digits in groups of $k$ (and possibly padding with leading $0$s to get a number of binary digits that is a multiple of $k$). The explanation is simple once you think that the number represented by a binary numeral $b\_{n-1}\cdots b\_1 b\_0$ is $$ \sum\_{0 \leq i <n} b\_i 2^i \enspace. $$ If, without loss of generality because of the padding, we assume that $n$ is a multiple of $k$, we can rewrite the summation as $$ \sum\_{0 \leq i < n/k} \Big( \sum\_{0 \leq j < k} b\_{ik+j} 2^j \Big) (2^k)^i \enspace. $$ Each summation in parentheses is a base-$2^k$ digit.
This approach only works when the base is a power of $2$. In that case you use $n$ bits when the base is $2^n$. In base $16=2^4$ you use four bits. There are $2^n$ binary strings of length $n$. In base $4=2^2$ you use $2$ bits.
2,616,975
I am converting numbers between different bases without issues, but I'm struggling to understand the **why** the method I'm using works. If I convert $A5$ (base 16) to base 8, I would do the following: > > Turn $A5$ into binary (4 bits) > > > $A = 1010$ > > > $5 = 0101$ > > > $10100101$ (split into three bits) $= 010$ $100$ $101$ > > > $010$ = 2 > > > $100$ = 4 > > > $101$ = 5 > > > $A5$ (base 16) $= 245$ (base 8) > > > I know the answer is correct, but I don't understand why the binary is split into $X$ bits depending on the base, and how the value $X$ is chosen. If it's base 4, for example, how many bits should the binary be separated into when converting?
2018/01/23
[ "https://math.stackexchange.com/questions/2616975", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517621/" ]
This approach only works for bases that are powers of $2$. So, for base $2^k$ you convert to binary by concatenating strings of $k$ bits, one for each base-$2^k$ digit. In the other direction, you convert from base $2$ to base $2^k$ by dividing the binary digits in groups of $k$ (and possibly padding with leading $0$s to get a number of binary digits that is a multiple of $k$). The explanation is simple once you think that the number represented by a binary numeral $b\_{n-1}\cdots b\_1 b\_0$ is $$ \sum\_{0 \leq i <n} b\_i 2^i \enspace. $$ If, without loss of generality because of the padding, we assume that $n$ is a multiple of $k$, we can rewrite the summation as $$ \sum\_{0 \leq i < n/k} \Big( \sum\_{0 \leq j < k} b\_{ik+j} 2^j \Big) (2^k)^i \enspace. $$ Each summation in parentheses is a base-$2^k$ digit.
This works because Base $b$ is equal base $a$ to a power. i.e. converting from base $a$ to base $a^k$. This will *not* work for any other type conversion. Here is why it works: In base $a$ an $n + 1 $ digit number $N = \sum\_{i=0}^n d\_i\*a^i$. Okay, let $n = q\*k + r$ where $0 \le r < k$. (This is just the division algorithm.) For simplicity sake lets define $d\_{t} = 0$ for $t > n$. So we can so $N = \sum\_{i=0}^{(q+1)\*k - 1} d\_i\*a^i$. (It's just that the $n+1 = q\*k + r + 1$ to $q\*k + (k-1)=(q+1)\*k -1$ digits are all $0$s.) So $N = \sum\_{i=0}^{qk+r} d\_i\*a^i = \sum\_{j=0}^{q} [d\_{k\*j}a^{k\*j} + d\_{k\*j + 1}a^{k\*j + 1} + ..... d\_{k\*j + (k-1)}\*a^{k\*j + (k-1)}]$ $= \sum\_{j=0}^{q} (a^k)^j\*[d\_{k\*j}a^{0} + d\_{k\*j + 1}a^{ 1} + ..... d\_{k\*j + (k-1)}\*a^{k-1}]$ Now $0 \le [d\_{k\*j}a^{0} + d\_{k\*j + 1}a^{ 1} + ..... d\_{k\*j + (k-1)}\*a^{k-1}]< a^k = b$. So let $c\_j = [d\_{k\*j}a^{0} + d\_{k\*j + 1}a^{ 1} + ..... d\_{k\*j + (k-1)}\*a^{k-1}]$ be a base $b$ digit. So $N = \sum\_{j=0}^{q} (a^k)^j\*[d\_{k\*j}a^{0} + d\_{k\*j + 1}a^{ 1} + ..... d\_{k\*j + (k-1)}\*a^{k-1}]$ $= \sum\_{j=0}^{q} b^j c\_j$. is a $q+1$ digit base $b$ number.
25,856,088
I am trying to update a variable using two different functions. I wrote a little C program to demonstrate: ``` #include <stdlib.h> #include <stdio.h> void updateHelper(int *x, int y) { *x = y; } void update(int x, int y) { updateHelper(&x, y); } int main(int argc, char *argv[]) { int num = 0; update(num, 1); printf("%d\n", num); return 0; } ``` Why is this printing a 0 and not a 1? I can't wrap my head around this. The function that is actually updating the value is indeed passed a reference of the variable(!?). Can someone explain why this happens? The arguments of update() can not be pointers. Are there any possible work-arounds for this?
2014/09/15
[ "https://Stackoverflow.com/questions/25856088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315551/" ]
You aren't updating the original variable. You're updating the *copy* of that variable that was passed to your `update` function. If you want to update the original variable, change `update` to take it's parameter as a pointer: ``` void update(int* x, int y) { updateHelper(x, y); } ``` and in main, pass the address: ``` update(&num, 1); ``` Edit: since you stated the arguments to update cannot be pointers, you will need to either have `update` return the new variable, or use a global variable, or ... In C, the only way to modify a reference to a variable in a function is by using pointers.
`x` in the call to `update` is just a local variable that happens to start with the same value as `num` in `main`. Therefore, even though *its* value is changed via the call to `updateHelper`, this has no effect on the value of `num`. That is, only the value of `num`, not it address, was passed to `update`, so nothing that happens subsequently during the call to `update` has any bearing on the value of `num`.
25,856,088
I am trying to update a variable using two different functions. I wrote a little C program to demonstrate: ``` #include <stdlib.h> #include <stdio.h> void updateHelper(int *x, int y) { *x = y; } void update(int x, int y) { updateHelper(&x, y); } int main(int argc, char *argv[]) { int num = 0; update(num, 1); printf("%d\n", num); return 0; } ``` Why is this printing a 0 and not a 1? I can't wrap my head around this. The function that is actually updating the value is indeed passed a reference of the variable(!?). Can someone explain why this happens? The arguments of update() can not be pointers. Are there any possible work-arounds for this?
2014/09/15
[ "https://Stackoverflow.com/questions/25856088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315551/" ]
You aren't updating the original variable. You're updating the *copy* of that variable that was passed to your `update` function. If you want to update the original variable, change `update` to take it's parameter as a pointer: ``` void update(int* x, int y) { updateHelper(x, y); } ``` and in main, pass the address: ``` update(&num, 1); ``` Edit: since you stated the arguments to update cannot be pointers, you will need to either have `update` return the new variable, or use a global variable, or ... In C, the only way to modify a reference to a variable in a function is by using pointers.
``` update(int x,..) ``` int x here is a argument by value. ie a copy (new address created) of num is created and the value is copied. try instead: ``` #include <stdlib.h> #include <stdio.h> void updateHelper(int *x, int y) { *x = y; } void update(int *x, int y) { updateHelper(x, y); } int main(int argc, char *argv[]) { int num = 0; update(&num, 1); printf("%d\n", num); return 0; } ```
25,856,088
I am trying to update a variable using two different functions. I wrote a little C program to demonstrate: ``` #include <stdlib.h> #include <stdio.h> void updateHelper(int *x, int y) { *x = y; } void update(int x, int y) { updateHelper(&x, y); } int main(int argc, char *argv[]) { int num = 0; update(num, 1); printf("%d\n", num); return 0; } ``` Why is this printing a 0 and not a 1? I can't wrap my head around this. The function that is actually updating the value is indeed passed a reference of the variable(!?). Can someone explain why this happens? The arguments of update() can not be pointers. Are there any possible work-arounds for this?
2014/09/15
[ "https://Stackoverflow.com/questions/25856088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315551/" ]
You aren't updating the original variable. You're updating the *copy* of that variable that was passed to your `update` function. If you want to update the original variable, change `update` to take it's parameter as a pointer: ``` void update(int* x, int y) { updateHelper(x, y); } ``` and in main, pass the address: ``` update(&num, 1); ``` Edit: since you stated the arguments to update cannot be pointers, you will need to either have `update` return the new variable, or use a global variable, or ... In C, the only way to modify a reference to a variable in a function is by using pointers.
Your initial call to the `update` function is a normal call-by-value, which means that `int num` gets copied, not referenced. Thus, when you later call `updateHelper` with a reference to the parameter `x`, all that gets modified is the copied value of num, local to the `update` function. So, your call stack ends up looking like this (read from bottom to top): ``` main() | num: 0 | update() < But `update's` x is a copy, does not point to anything | x: 1 . | \ updateHelper() | < Points to `update's` x | / | *x: 1 ^ ``` If your `update` function's interface can't take a pointer, then the only other options it has is to either return the modified value (which will also require a change to the interface), or to use a (possibly static) global variable.
73,445,292
Using a sql query, how can I return an array of json objects that looks like this: ``` { "result":[ { "RentBookRegistrationId":1, "date":"15-08-2022", "PersonName":"Peter", "Books":[ { "name":"Ulysses" }, { "name":"Hamlet } ], "Processes":[ { "no":1, "name":"Online booking" }, { "no":2, "name":"Reserved beforehand" }, { "no":4, "name":"Vending machined used" } ] } ] } ``` From a SQL Server database that looks like this: Table: **RentBookRegistration** ``` +----+------------+-----------------------------+ | id | date | person | +----+------------+-----------------------------+ | 1 | 15-08-2022 | {"no": 1, "name": "Peter"} | +----+-------- ---+-----------------------------+ | 2 | 16-08-2022 | {"no": 2, "name": "Anna"} | +----+------------+-----------------------------+ | 3 | 17-08-2022 | {"no": 1, "name": "Peter"} | +----+------------+-----------------------------+ | 4 | 17-08-2022 | {"no": 2, "name": "Mark"} | +----+------------+-----------------------------+ ``` Table: **BookData** ``` +----+------------------------+-----------------------------------------------------------+ | id | rentBookRegistrationId | book | +----+------------------------+-----------------------------------------------------------+ | 1 | 1 | {"name": "Ulysses", "author": "James Joyce", "year": 1918}| +----+------------------------+-----------------------------------------------------------+ | 2 | 1 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} | +----+------------------------+-----------------------------------------------------------+ | 3 | 2 | {"name": "Dune", "author": "Frank Herbert", "year": 1965} | +----+------------------------+-----------------------------------------------------------+ | 4 | 3 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} | +----+------------------------+-----------------------------------------------------------+ | 5 | 4 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} | +----+------------------------+-----------------------------------------------------------+ ``` Table: **ProcessData** ``` +----+------------------------+-----------------------------------------------------------+ | id | rentBookRegistrationId | processUsed | +----+------------------------+-----------------------------------------------------------+ | 1 | 1 | {"no": 1, "name": "Online booking"} | +----+------------------------+-----------------------------------------------------------+ | 2 | 1 | {"no": 2, "name": "Reserved beforehand"} | +----+------------------------+-----------------------------------------------------------+ | 3 | 1 | {"no": 4, "name": "Vending machined used"} | +----+------------------------+-----------------------------------------------------------+ | 3 | 2 | {"no": 1, "name": "Online booking"} | +----+------------------------+-----------------------------------------------------------+ | 4 | 2 | {"no": 4, "name": "Vending machined used"} | +----+------------------------+-----------------------------------------------------------+ | 5 | 3 | {"no": 2, "name": "Reserved beforehand"} | +----+------------------------+-----------------------------------------------------------+ ``` The table layout might seems a bit stupid, but they are simplified to make the question straightforward. This is how far I've come so far: ```sql select … from RentBookRegistration R where R.PersonName = 'Peter' ```
2022/08/22
[ "https://Stackoverflow.com/questions/73445292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14505900/" ]
You had done it pretty much right. All you needed was to use `setInterval` instead of `setTimeout`. Also, you need to store the interval in a variable and clear it on `mouseout` so that the text does not keep changing the color. ```js let interval; document.addEventListener('DOMContentLoaded', function listen() { var logo = document.querySelector('.logo-btn'); logo.addEventListener("mouseover", event => {interval = setInterval(()=>changeColor(event), 500)}); logo.addEventListener("mouseout", event => resetColor(event)); }) function changeColor(event) { var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"] var color = colors[Math.floor(Math.random() * colors.length)]; var logo = event.target; logo.style.color = color; } function resetColor(event) { var logo = event.target; logo.style.color = "black"; clearInterval(interval); } ``` ```css header { background-color: #fff; height: 80px; position: relative; } .header-logo { font-size: 50px; position: absolute; bottom: -15px; left: 40px; } .logo-btn { background-color: transparent; border: none; text-align: bottom; } ``` ```html <!DOCTYPE html> <html lang="en"> <head> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link href="styles.css" rel="stylesheet"> <title>My Webpage</title> </head> <body> <header> <div class="header-logo"> <a href="x"> <button class="logo-btn">Logo</button> </a> </div> </header> </body> </html> ```
It should be like this... ``` let colors = [1,2,3], element = document.querySelector('whatever-your-logo'), colorIndex = 0; function changeColor(){ //set color element.style.color = colors[colorIndex]; //change to next color colorIndex++; // if it's last color then back to first colorIndex if(colorIndex >= colors.length-1) colorIndex = 0; } //Interval let priod = 1000; //in ms let interval = setInterval(changeColor, priod); //done... ```
73,445,292
Using a sql query, how can I return an array of json objects that looks like this: ``` { "result":[ { "RentBookRegistrationId":1, "date":"15-08-2022", "PersonName":"Peter", "Books":[ { "name":"Ulysses" }, { "name":"Hamlet } ], "Processes":[ { "no":1, "name":"Online booking" }, { "no":2, "name":"Reserved beforehand" }, { "no":4, "name":"Vending machined used" } ] } ] } ``` From a SQL Server database that looks like this: Table: **RentBookRegistration** ``` +----+------------+-----------------------------+ | id | date | person | +----+------------+-----------------------------+ | 1 | 15-08-2022 | {"no": 1, "name": "Peter"} | +----+-------- ---+-----------------------------+ | 2 | 16-08-2022 | {"no": 2, "name": "Anna"} | +----+------------+-----------------------------+ | 3 | 17-08-2022 | {"no": 1, "name": "Peter"} | +----+------------+-----------------------------+ | 4 | 17-08-2022 | {"no": 2, "name": "Mark"} | +----+------------+-----------------------------+ ``` Table: **BookData** ``` +----+------------------------+-----------------------------------------------------------+ | id | rentBookRegistrationId | book | +----+------------------------+-----------------------------------------------------------+ | 1 | 1 | {"name": "Ulysses", "author": "James Joyce", "year": 1918}| +----+------------------------+-----------------------------------------------------------+ | 2 | 1 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} | +----+------------------------+-----------------------------------------------------------+ | 3 | 2 | {"name": "Dune", "author": "Frank Herbert", "year": 1965} | +----+------------------------+-----------------------------------------------------------+ | 4 | 3 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} | +----+------------------------+-----------------------------------------------------------+ | 5 | 4 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} | +----+------------------------+-----------------------------------------------------------+ ``` Table: **ProcessData** ``` +----+------------------------+-----------------------------------------------------------+ | id | rentBookRegistrationId | processUsed | +----+------------------------+-----------------------------------------------------------+ | 1 | 1 | {"no": 1, "name": "Online booking"} | +----+------------------------+-----------------------------------------------------------+ | 2 | 1 | {"no": 2, "name": "Reserved beforehand"} | +----+------------------------+-----------------------------------------------------------+ | 3 | 1 | {"no": 4, "name": "Vending machined used"} | +----+------------------------+-----------------------------------------------------------+ | 3 | 2 | {"no": 1, "name": "Online booking"} | +----+------------------------+-----------------------------------------------------------+ | 4 | 2 | {"no": 4, "name": "Vending machined used"} | +----+------------------------+-----------------------------------------------------------+ | 5 | 3 | {"no": 2, "name": "Reserved beforehand"} | +----+------------------------+-----------------------------------------------------------+ ``` The table layout might seems a bit stupid, but they are simplified to make the question straightforward. This is how far I've come so far: ```sql select … from RentBookRegistration R where R.PersonName = 'Peter' ```
2022/08/22
[ "https://Stackoverflow.com/questions/73445292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14505900/" ]
You had done it pretty much right. All you needed was to use `setInterval` instead of `setTimeout`. Also, you need to store the interval in a variable and clear it on `mouseout` so that the text does not keep changing the color. ```js let interval; document.addEventListener('DOMContentLoaded', function listen() { var logo = document.querySelector('.logo-btn'); logo.addEventListener("mouseover", event => {interval = setInterval(()=>changeColor(event), 500)}); logo.addEventListener("mouseout", event => resetColor(event)); }) function changeColor(event) { var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"] var color = colors[Math.floor(Math.random() * colors.length)]; var logo = event.target; logo.style.color = color; } function resetColor(event) { var logo = event.target; logo.style.color = "black"; clearInterval(interval); } ``` ```css header { background-color: #fff; height: 80px; position: relative; } .header-logo { font-size: 50px; position: absolute; bottom: -15px; left: 40px; } .logo-btn { background-color: transparent; border: none; text-align: bottom; } ``` ```html <!DOCTYPE html> <html lang="en"> <head> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link href="styles.css" rel="stylesheet"> <title>My Webpage</title> </head> <body> <header> <div class="header-logo"> <a href="x"> <button class="logo-btn">Logo</button> </a> </div> </header> </body> </html> ```
A recursive function can be a solution for your problem. You set mouseOver variable on 1 when mouse is over, and on 0 when mouse is out. You also call setColor on mouseover and check if mouse is over with mouseOver flag. Now you call setColor that set a new color every time it's called based on selected variable ``` var logo = document.querySelector('.logo-btn'); logo.addEventListener("mouseover", event => {setColor(event); mouseOver = 1}); logo.addEventListener("mouseout", event => resetColor(event)); var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"], selected = 0, mouseOver = 0 function setColor(e){ e.target.style.backgroundColor = colors[selected] if(mouseOver){ setTimeout(function(){ if(colors.length > selected + 1){ selected = 0 } else{ selected ++ } setColor(e) }, 500) } } function resetColor(event){ selected = 0 mouseOver = 0 e.target.style.backgroundColor = colors[selected] } ```
2,697
I have heard both interpretations, for me it would make more sense to be something from the mind as there is no creator God or its opposite in Buddhism, the image of a "temptator creature" like Satan sounds strange when we think about impermanence, on the other hand, some suttas that mention Mara may fit better with the concept of an external creature, I know this interpretation is questionable, so I'm making the question!
2014/08/15
[ "https://buddhism.stackexchange.com/questions/2697", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/533/" ]
Two snippets from suttas refering to Mara as an entity/position: MN 115: > > "But, venerable sir, in what way can a bhikkhu be called skilled in what is possible and what is impossible?" > > > "Here, Ananda, a bhikkhu undersands [...]: "It is possible that a man might occupy the position of Māra [...]" > > > MN 50: > > The venerable Maha Moggallana saw him [Māra] standing there and said: "I see you there too, Evil One. Do not think 'He does not see me.' You are standing against the door bar, Evil One. > > > "It happened once, Evil One, that I was a Māra named Dusi [...] > > > A sutta where a disciple directly asks what is Māra (SN 23.1): > > "Venerable sir, it is said, 'Māra, Māra.' In what way, venerable sir, might Māra be?" > > > "When there is form, Radha, there might be Māra, or the killer, or the one who is killed." > > > The above are from Nanamoli/Bodhi translations. Bhikkhu Bodhi also writes in a note of the Majjhima Nikaya: > > The name means "the Corrupter" or "the Corrupted One". In the Buddhist conception of the universe, the position of Mara, like that of Maha Brahma, is a fixed one that is assumed by different individuals in accordance with their kamma. > > >
There are multiple [Maras](http://en.wikipedia.org/wiki/Mara_(demon)) in Buddhism. One of them is a Deva. Other others being death, conditioned existence, and unskillful emotions.
2,697
I have heard both interpretations, for me it would make more sense to be something from the mind as there is no creator God or its opposite in Buddhism, the image of a "temptator creature" like Satan sounds strange when we think about impermanence, on the other hand, some suttas that mention Mara may fit better with the concept of an external creature, I know this interpretation is questionable, so I'm making the question!
2014/08/15
[ "https://buddhism.stackexchange.com/questions/2697", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/533/" ]
There are multiple [Maras](http://en.wikipedia.org/wiki/Mara_(demon)) in Buddhism. One of them is a Deva. Other others being death, conditioned existence, and unskillful emotions.
Using the Three Universal Characteristics of impermanence, suffering and non-self, you can see that "mara" is a creation of the mind, this is why "mara" is in or attached to everything!! It is only a cultivation of wisdom ( The Noble Eightfold Path) which can defeat mara, but also one needs mindfulness in each and every moment, as the experience changes from rebirth to rebirth via one of our six senses!! Metta.
2,697
I have heard both interpretations, for me it would make more sense to be something from the mind as there is no creator God or its opposite in Buddhism, the image of a "temptator creature" like Satan sounds strange when we think about impermanence, on the other hand, some suttas that mention Mara may fit better with the concept of an external creature, I know this interpretation is questionable, so I'm making the question!
2014/08/15
[ "https://buddhism.stackexchange.com/questions/2697", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/533/" ]
Two snippets from suttas refering to Mara as an entity/position: MN 115: > > "But, venerable sir, in what way can a bhikkhu be called skilled in what is possible and what is impossible?" > > > "Here, Ananda, a bhikkhu undersands [...]: "It is possible that a man might occupy the position of Māra [...]" > > > MN 50: > > The venerable Maha Moggallana saw him [Māra] standing there and said: "I see you there too, Evil One. Do not think 'He does not see me.' You are standing against the door bar, Evil One. > > > "It happened once, Evil One, that I was a Māra named Dusi [...] > > > A sutta where a disciple directly asks what is Māra (SN 23.1): > > "Venerable sir, it is said, 'Māra, Māra.' In what way, venerable sir, might Māra be?" > > > "When there is form, Radha, there might be Māra, or the killer, or the one who is killed." > > > The above are from Nanamoli/Bodhi translations. Bhikkhu Bodhi also writes in a note of the Majjhima Nikaya: > > The name means "the Corrupter" or "the Corrupted One". In the Buddhist conception of the universe, the position of Mara, like that of Maha Brahma, is a fixed one that is assumed by different individuals in accordance with their kamma. > > >
Using the Three Universal Characteristics of impermanence, suffering and non-self, you can see that "mara" is a creation of the mind, this is why "mara" is in or attached to everything!! It is only a cultivation of wisdom ( The Noble Eightfold Path) which can defeat mara, but also one needs mindfulness in each and every moment, as the experience changes from rebirth to rebirth via one of our six senses!! Metta.
57,201,932
Not using C that often, I came across a possibly simple problem. I have several functions, that need access to a global array-variable `g`. But the actual size of this variable has to be defined in an `init()`-function. The size depends on some other stuff, so `g` has to be declared somehow with a dynamic size. I read about `malloc` and other functions, but I am not sure how to use them properly. Example: ``` double g[dynamic]; // size is not known yet int n; void init() { // calculate "n" for array size n = ... // declare and initialze g with a size "n" } void dostuff() { for (int i = 0; i < n; i++) work(g[i]); } ``` How should I solve this?
2019/07/25
[ "https://Stackoverflow.com/questions/57201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7217855/" ]
You cannot use an **array**. You must use a **pointer**. ``` double *global_array; // size is not known yet size_t nglobal_array; // may be helpful to have the size void init(void) { // calculate "nglobal_array" for array size nglobal_array = 42; // declare and initialze global_array with a size "nglobal_array" global_array = malloc(nglobal_array * sizeof *global_array); if (global_array == NULL) { fprintf(stderr, "Error allocating resources.\nProgram aborted.\n"); exit(EXIT_FAILURE); } } void dostuff() { for (int i = 0; i < nglobal_array; i++) work(global_array[i]); } ``` Don't forget to `free(global_array)` when you no longer need it. Complete usage would then be something like this ``` #include <stdlib.h> // includes // declarations & definitions as above int main(void) { init(); dostuff(); free(global_array); } ```
What you want to achieve is not possible in C. A global array must have a fixed size at compile, or at least at link time. You can declare the array without a specified size: ``` extern double g[]; ``` But it must be defined somewhere with an actual size, computed from a constant expression at the definition place, and the size cannot be determined from the above declaration, so it must be passed some other way to the functions that will use the array: either implicitly, with a special value signifying the end of the array (like `'\0'` for `char` strings) or explicitly via a separate variable as you posted. Note however that `n` and `g` are very poor name choices for global variables as they are likely to clash with local variable names and convey no meaning to the reader. If the size is not known until run time, you should define a pointer instead of an array and also define a separate variable with the length of the array that will be allocated by the initialization function. ``` double *g; size_t g_length; ```
57,201,932
Not using C that often, I came across a possibly simple problem. I have several functions, that need access to a global array-variable `g`. But the actual size of this variable has to be defined in an `init()`-function. The size depends on some other stuff, so `g` has to be declared somehow with a dynamic size. I read about `malloc` and other functions, but I am not sure how to use them properly. Example: ``` double g[dynamic]; // size is not known yet int n; void init() { // calculate "n" for array size n = ... // declare and initialze g with a size "n" } void dostuff() { for (int i = 0; i < n; i++) work(g[i]); } ``` How should I solve this?
2019/07/25
[ "https://Stackoverflow.com/questions/57201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7217855/" ]
What you want to achieve is not possible in C. A global array must have a fixed size at compile, or at least at link time. You can declare the array without a specified size: ``` extern double g[]; ``` But it must be defined somewhere with an actual size, computed from a constant expression at the definition place, and the size cannot be determined from the above declaration, so it must be passed some other way to the functions that will use the array: either implicitly, with a special value signifying the end of the array (like `'\0'` for `char` strings) or explicitly via a separate variable as you posted. Note however that `n` and `g` are very poor name choices for global variables as they are likely to clash with local variable names and convey no meaning to the reader. If the size is not known until run time, you should define a pointer instead of an array and also define a separate variable with the length of the array that will be allocated by the initialization function. ``` double *g; size_t g_length; ```
No. C doesn't do that. Arrays declared in global scope have fixed space allocated for them in your binary(.EXE files on Windows and ELF executables on Linux). If you want an array of dynamic size, you need to dynamically allocate it. Example is here: ``` #include <stdlib.h> #define ARRAY_SIZE 100 typedef char T; //your type here T* array; void init() { array = malloc(sizeof(T) * ARRAY_SIZE); //array filled with garbage values //array = calloc(ARRAY_SIZE, sizeof(T)); //array filled with 0x00 } void finish() { free(array); // DO NOT ACCESS ARRAY AFTER THIS CALL! } int main() { init(); array[6] = 63; //access array as normal finish(); //array[41] = 23; //will most likely crash due to a segmentation fault, also called an access violation on Windoez } ```
57,201,932
Not using C that often, I came across a possibly simple problem. I have several functions, that need access to a global array-variable `g`. But the actual size of this variable has to be defined in an `init()`-function. The size depends on some other stuff, so `g` has to be declared somehow with a dynamic size. I read about `malloc` and other functions, but I am not sure how to use them properly. Example: ``` double g[dynamic]; // size is not known yet int n; void init() { // calculate "n" for array size n = ... // declare and initialze g with a size "n" } void dostuff() { for (int i = 0; i < n; i++) work(g[i]); } ``` How should I solve this?
2019/07/25
[ "https://Stackoverflow.com/questions/57201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7217855/" ]
You cannot use an **array**. You must use a **pointer**. ``` double *global_array; // size is not known yet size_t nglobal_array; // may be helpful to have the size void init(void) { // calculate "nglobal_array" for array size nglobal_array = 42; // declare and initialze global_array with a size "nglobal_array" global_array = malloc(nglobal_array * sizeof *global_array); if (global_array == NULL) { fprintf(stderr, "Error allocating resources.\nProgram aborted.\n"); exit(EXIT_FAILURE); } } void dostuff() { for (int i = 0; i < nglobal_array; i++) work(global_array[i]); } ``` Don't forget to `free(global_array)` when you no longer need it. Complete usage would then be something like this ``` #include <stdlib.h> // includes // declarations & definitions as above int main(void) { init(); dostuff(); free(global_array); } ```
No. C doesn't do that. Arrays declared in global scope have fixed space allocated for them in your binary(.EXE files on Windows and ELF executables on Linux). If you want an array of dynamic size, you need to dynamically allocate it. Example is here: ``` #include <stdlib.h> #define ARRAY_SIZE 100 typedef char T; //your type here T* array; void init() { array = malloc(sizeof(T) * ARRAY_SIZE); //array filled with garbage values //array = calloc(ARRAY_SIZE, sizeof(T)); //array filled with 0x00 } void finish() { free(array); // DO NOT ACCESS ARRAY AFTER THIS CALL! } int main() { init(); array[6] = 63; //access array as normal finish(); //array[41] = 23; //will most likely crash due to a segmentation fault, also called an access violation on Windoez } ```
132,892
In the 1987 *[Robocop](http://www.imdb.com/title/tt0093870/)* movie, Alex Murphy was shot by some gangsters. When OCP was making Robocop using Alex Murphy's body, **was Alex Murphy still alive, or did OCP use his *dead body* to make Robocop?**
2016/06/25
[ "https://scifi.stackexchange.com/questions/132892", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/64716/" ]
**Murphy was dead.** When the doctors are operating on him, the line is > > **Surgeon #1 -** *Ok, let's shock him to flatline, then quit.* > > > [They shock him] > > > **Surgeon #2** - *No pulse!* > > > **Surgeon #1** - *I'm calling it* [[medical slang for declaring the time of death](https://ell.stackexchange.com/questions/76601/call-it-what-does-this-term-mean-context-i-cant-im-calling-it-im-calli)]. > > > which tallies very nicely with what we see in the film's official novelisation > > A loud voice crashed through the fog. The dreams shattered. “I’ve got a straight line. Crash cart! 10 cc Adrenalin. Stand clear!” > > > He felt cold grease on his chest. A surge of electricity slammed into his muscles. There was the ferret-faced thug. > > > “Hit him again!” someone screamed. A sudden jolt conjured up the face of the Asian hit man. Another jolt. The farmboy. And another. The black man. And another. The high-foreheaded clown who blew his hand to shreds. His killers. He bade farewell to them all. Only blackness filled his life, now. A void. > > > **“That’s it. He’s gone,”** he heard someone say from another planet. > > > We see later see in the film that he was officially declared dead by the State. He had a funeral and his widow was provided with a pension. [![enter image description here](https://i.stack.imgur.com/r92r8.jpg)](https://i.stack.imgur.com/r92r8.jpg) and this from the film's [original script](http://www.awesomefilm.com/script/robocop-script.pdf) [![enter image description here](https://i.stack.imgur.com/l0zrZ.png)](https://i.stack.imgur.com/l0zrZ.png) --- If you take the later [TV series](https://en.wikipedia.org/wiki/RoboCop:_The_Series) as canon, we actually *see* his body in the DPD morgue [![enter image description here](https://i.stack.imgur.com/0l77m.jpg)](https://i.stack.imgur.com/0l77m.jpg)
I think that Murphy's body is gone. They used his face to honor him, says Robocop in the film *Robocop 2*. However, I think they used his face because they used his brain. It makes sense that if they used his brain in the creation of Robocop, they would use the face that used that brain, i.e. Murphy. So in my book, Murphy lives on in Robocop. The reason Robocop says (while gesturing his face), "They did this to honor him," is because he doesn't want to hurt his wife anymore, knowing that her husband is still alive, but never coming home because he works 24/7. Anyway, that's my take on it.
26,644,985
I am trying to achieve a strange query. I have a table like this: table People ``` ----------------------- | id | name | family | +----+------+--------+ | 1 | Bob | Smith | +----+------+--------+ | 2 | Joe | Smith | ---------------------- ``` I want to return an assoc array like this ``` id : 1 name : bob family : smith familySize : 2 ``` So something like this ``` "SELECT id, name, family, familySize FROM People" ``` How can I get the familySize in there? Keep in mind my query may have many families and I want them all to be returned. Thank you.
2014/10/30
[ "https://Stackoverflow.com/questions/26644985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3822370/" ]
The above 2 answers won't work with multiple families. You can do something like this: ``` SELECT id, name, family, familySize FROM People p1 JOIN (SELECT COUNT(*) as familySize, family FROM People GROUP BY family) p2 USING(family) ```
You can do it like this SELECT id, name, family, count(id) as familySize FROM People
26,644,985
I am trying to achieve a strange query. I have a table like this: table People ``` ----------------------- | id | name | family | +----+------+--------+ | 1 | Bob | Smith | +----+------+--------+ | 2 | Joe | Smith | ---------------------- ``` I want to return an assoc array like this ``` id : 1 name : bob family : smith familySize : 2 ``` So something like this ``` "SELECT id, name, family, familySize FROM People" ``` How can I get the familySize in there? Keep in mind my query may have many families and I want them all to be returned. Thank you.
2014/10/30
[ "https://Stackoverflow.com/questions/26644985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3822370/" ]
The above 2 answers won't work with multiple families. You can do something like this: ``` SELECT id, name, family, familySize FROM People p1 JOIN (SELECT COUNT(*) as familySize, family FROM People GROUP BY family) p2 USING(family) ```
``` "SELECT id, name, family, count(family) as familySize FROM People group by family" ```
26,644,985
I am trying to achieve a strange query. I have a table like this: table People ``` ----------------------- | id | name | family | +----+------+--------+ | 1 | Bob | Smith | +----+------+--------+ | 2 | Joe | Smith | ---------------------- ``` I want to return an assoc array like this ``` id : 1 name : bob family : smith familySize : 2 ``` So something like this ``` "SELECT id, name, family, familySize FROM People" ``` How can I get the familySize in there? Keep in mind my query may have many families and I want them all to be returned. Thank you.
2014/10/30
[ "https://Stackoverflow.com/questions/26644985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3822370/" ]
The above 2 answers won't work with multiple families. You can do something like this: ``` SELECT id, name, family, familySize FROM People p1 JOIN (SELECT COUNT(*) as familySize, family FROM People GROUP BY family) p2 USING(family) ```
I would like to mention here that what if two or three families have the same surname "Smith". It won't give you the desired results. What I suggest you is while inserting the data in the table assign a family head and all the family members have a field called family\_ID has primary key as value of family\_head. This will give you accurate results with 1000's of people. I have made a family portal has over 12k members now and it works fine for me. Hope it helps.
60,085,739
I am working on an internal program for work that is essentially built on PHP. My problem is that I have a a header, a side navigation, the main content (to the right of the nav) and a footer. [Rough Layout Picture](https://i.stack.imgur.com/whLdr.png) My issue is that I have two DIV's within a container, the nav is set to a percentage with a minimum width, and the content section is set to take the remaining space. In total both the nav and content should take about 91% of the screen real estate. [Whats Happening after shrinking the browser a bit](https://i.stack.imgur.com/qhwwU.png) My CSS looks like this for the fields I think are relevant: ``` .container{ width: 100%; float: inline-block; } .header{ float: left; text-align: left; background-color: lightblue; width: 100%; vertical-align: middle; display: block; border-radius: 15px; } .header h1{ font-weight: bold; font-size: 40px; text-indent: 50px; } .msg_alert{ background-color: green; color: white; width: 95%; padding: 5px; border-radius: 10px; } .err_msg_alert{ background-color: red; color: white; width: 95%; padding: 5px; border-radius: 10px; } .menu{ float: left; width: 13%; border: 3px solid grey; padding: 5px; background-color: lightgrey; border-radius: 15px; margin-top: 20px; margin-right: 20px; min-width: 200px; } .menu a{ float: left; color: black; text-align: left; padding: 14px; text-decoration: none; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); margin: 3px; background-color: lightblue; width: 40%; min-width: 150px; border-radius: 15px; } .menu a:hover{ background-color: grey; color: black; } .menu ul{ list-style-type: none; margin: 0; padding: 0; } .menu li{ padding: 8px; margin-bottom: 7px; } .content{ float: left; width: 78%; padding: 20px; margin-top: 20px; margin-left: 20px; /*border: 3px solid red;*/ } .footer{ display: inline-block; width: 100%; background-color: lightgrey; border-radius: 15px; font-size: 12px; text-align: center; margin-top: 5px; padding-bottom: 10px; } ``` I'm not sure what I've done wrong. Everything displays properly if the browser is in full screen but when I shrink it down to about 3/4's of the browser size the nav stays where it should be but the contents move below. I have setup a mobile version which works perfectly but the desktop mode is what I am having issues with. Thank you for the help in advance.
2020/02/05
[ "https://Stackoverflow.com/questions/60085739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12848465/" ]
REST was never designed for bulk transaction support, it's for representing the state of individual objects. That said, API design is very opinionated and you have to balance REST "pureness" with functionality. If I were designing this, I would go with option 1 and use delete at the "sessions" endpoint since you are removing all of the user sessions and not just a single or subset.
This answer may be opinion based, so take it as such. I would use **DELETE** if you are **removing** the resource (since you are going to be removing sessions). If you keep the sessions (but change some data in those resources eg sliding expiration) then I would consider using **PATCH** as you're **modifying** (resetting and not replacing) existing sessions.
60,085,739
I am working on an internal program for work that is essentially built on PHP. My problem is that I have a a header, a side navigation, the main content (to the right of the nav) and a footer. [Rough Layout Picture](https://i.stack.imgur.com/whLdr.png) My issue is that I have two DIV's within a container, the nav is set to a percentage with a minimum width, and the content section is set to take the remaining space. In total both the nav and content should take about 91% of the screen real estate. [Whats Happening after shrinking the browser a bit](https://i.stack.imgur.com/qhwwU.png) My CSS looks like this for the fields I think are relevant: ``` .container{ width: 100%; float: inline-block; } .header{ float: left; text-align: left; background-color: lightblue; width: 100%; vertical-align: middle; display: block; border-radius: 15px; } .header h1{ font-weight: bold; font-size: 40px; text-indent: 50px; } .msg_alert{ background-color: green; color: white; width: 95%; padding: 5px; border-radius: 10px; } .err_msg_alert{ background-color: red; color: white; width: 95%; padding: 5px; border-radius: 10px; } .menu{ float: left; width: 13%; border: 3px solid grey; padding: 5px; background-color: lightgrey; border-radius: 15px; margin-top: 20px; margin-right: 20px; min-width: 200px; } .menu a{ float: left; color: black; text-align: left; padding: 14px; text-decoration: none; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); margin: 3px; background-color: lightblue; width: 40%; min-width: 150px; border-radius: 15px; } .menu a:hover{ background-color: grey; color: black; } .menu ul{ list-style-type: none; margin: 0; padding: 0; } .menu li{ padding: 8px; margin-bottom: 7px; } .content{ float: left; width: 78%; padding: 20px; margin-top: 20px; margin-left: 20px; /*border: 3px solid red;*/ } .footer{ display: inline-block; width: 100%; background-color: lightgrey; border-radius: 15px; font-size: 12px; text-align: center; margin-top: 5px; padding-bottom: 10px; } ``` I'm not sure what I've done wrong. Everything displays properly if the browser is in full screen but when I shrink it down to about 3/4's of the browser size the nav stays where it should be but the contents move below. I have setup a mobile version which works perfectly but the desktop mode is what I am having issues with. Thank you for the help in advance.
2020/02/05
[ "https://Stackoverflow.com/questions/60085739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12848465/" ]
REST was never designed for bulk transaction support, it's for representing the state of individual objects. That said, API design is very opinionated and you have to balance REST "pureness" with functionality. If I were designing this, I would go with option 1 and use delete at the "sessions" endpoint since you are removing all of the user sessions and not just a single or subset.
I would go with `DELETE @ users/sessions` If you think about it, a reset is simply an admin dropping a session. The user gets their new session when/if they return. So a reset route does not make much sense as you are not reissuing sessions to all of your users in this action. My preference is `users/sessions` rather then `users/{*}/sessions`. The later route suggests that you are wanting to remove all sessions of the parent resource, in this case being a single user.
60,085,739
I am working on an internal program for work that is essentially built on PHP. My problem is that I have a a header, a side navigation, the main content (to the right of the nav) and a footer. [Rough Layout Picture](https://i.stack.imgur.com/whLdr.png) My issue is that I have two DIV's within a container, the nav is set to a percentage with a minimum width, and the content section is set to take the remaining space. In total both the nav and content should take about 91% of the screen real estate. [Whats Happening after shrinking the browser a bit](https://i.stack.imgur.com/qhwwU.png) My CSS looks like this for the fields I think are relevant: ``` .container{ width: 100%; float: inline-block; } .header{ float: left; text-align: left; background-color: lightblue; width: 100%; vertical-align: middle; display: block; border-radius: 15px; } .header h1{ font-weight: bold; font-size: 40px; text-indent: 50px; } .msg_alert{ background-color: green; color: white; width: 95%; padding: 5px; border-radius: 10px; } .err_msg_alert{ background-color: red; color: white; width: 95%; padding: 5px; border-radius: 10px; } .menu{ float: left; width: 13%; border: 3px solid grey; padding: 5px; background-color: lightgrey; border-radius: 15px; margin-top: 20px; margin-right: 20px; min-width: 200px; } .menu a{ float: left; color: black; text-align: left; padding: 14px; text-decoration: none; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); margin: 3px; background-color: lightblue; width: 40%; min-width: 150px; border-radius: 15px; } .menu a:hover{ background-color: grey; color: black; } .menu ul{ list-style-type: none; margin: 0; padding: 0; } .menu li{ padding: 8px; margin-bottom: 7px; } .content{ float: left; width: 78%; padding: 20px; margin-top: 20px; margin-left: 20px; /*border: 3px solid red;*/ } .footer{ display: inline-block; width: 100%; background-color: lightgrey; border-radius: 15px; font-size: 12px; text-align: center; margin-top: 5px; padding-bottom: 10px; } ``` I'm not sure what I've done wrong. Everything displays properly if the browser is in full screen but when I shrink it down to about 3/4's of the browser size the nav stays where it should be but the contents move below. I have setup a mobile version which works perfectly but the desktop mode is what I am having issues with. Thank you for the help in advance.
2020/02/05
[ "https://Stackoverflow.com/questions/60085739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12848465/" ]
REST was never designed for bulk transaction support, it's for representing the state of individual objects. That said, API design is very opinionated and you have to balance REST "pureness" with functionality. If I were designing this, I would go with option 1 and use delete at the "sessions" endpoint since you are removing all of the user sessions and not just a single or subset.
> > I want to expose another method for the admin to delete (reset) a user's all sessions. I am considering 2 options, I wonder which one is more Restful.... > > > You probably want to be using [POST](https://www.rfc-editor.org/rfc/rfc7231#section-4.3.3). > > POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- [Fielding, 2008](https://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post). > > > HTTP DELETE isn't often the right answer > > Relatively few resources allow the DELETE method -- its primary use is for remote authoring environments, where the user has some direction regarding its effect. -- [RFC 7231](https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5) > > > HTTP Methods belong to the "transfer documents over a network" domain, not to *your* domain. REST doesn't actually care about the spelling of the target-uri -- that's part of the point. General-purpose HTTP components don't assume that the uri has any specific semantics encoded into it. It is just a opaque identifier. That means that you can apply whatever URI design heuristics you like. It's a lot like choosing a name for a variable or a namespace in a general-purpose programming language; the compiler/interpreter don't usual care if the symbol "means" anything or not. We choose names that make things easier for the *human beings* that interact with the code. And so it is with URI as well. You'll probably want to use a spelling that is consistent with other identifiers in your API, so that it looks as though the api were designed by "one mind". A common approach starts from the notion that a resource is any information that can be named ([Fielding, 2000](https://www.ics.uci.edu/%7Efielding/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_1)). Therefore, it's our job to first (a) figure out the name of the resource that handles this request, then (b) figure out an identifier that "matches", that name. Resources are closely analogous to *documents*, so if you can think of the name of the document in which you would write this message, you are a good ways toward figuring out the name (ex: we write expiring sessions into the "security log", or into the "sessions log". Great, now figure out the corresponding URI.) If *I* ran the zoo: I imagine that ``` GET /users/{userKey}/sessions ``` would probably return a representation of the users cookie sessions. Because this representation would be something that changes when we delete all of the users sessions, I would want to post the delete request to this same target URI ``` POST /users/{userKey}/sessions ``` because doing it that way makes the [cache invalidation](https://www.rfc-editor.org/rfc/rfc7234#section-4.4) story a bit easier.
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
Your query is wrong it should be: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES(1, 1, "aaa"); ``` See here for more help: [Sql Insert Wiki](http://en.wikipedia.org/wiki/Insert_%28SQL%29) --- **Edit:** Your query and error: > > insert into t\_category\_values > (CategoryCode, CategoryValueCode, > CategoryValue) values(2, 1, 1); > > > no primary key > > > In insert while specifying to insert in few column instead of all in table you must have to include primary key. That means in your one of CategoryCode, CategoryValueCode, CategoryValue should be primary key or include fourth column that is primary key in table.
``` insert into `DBA`.`t_category_values` (`CategoryCode`, `CategoryValueCode`, `CategoryValue`) values(1, 1, "aaa"); ```
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
``` insert into `DBA`.`t_category_values` (`CategoryCode`, `CategoryValueCode`, `CategoryValue`) values(1, 1, "aaa"); ```
You are getting the error "No Primary Key" because you have not specified a valid unique primary key. Your table must be 4 columns. ``` INSERT INTO t_category_values (PRIMARY_KEY, CategoryCode, CategoryValueCode, CategoryValue) VALUES(pkey_value_here, 2, 1, 1); ``` The only time you dont need to specify the primary key column is when the primary key is an auto increment value. If it is an auto increment column the INSERT will automatically fill in that value for you and you dont need to worry about it.
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
Your query is wrong it should be: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES(1, 1, "aaa"); ``` See here for more help: [Sql Insert Wiki](http://en.wikipedia.org/wiki/Insert_%28SQL%29) --- **Edit:** Your query and error: > > insert into t\_category\_values > (CategoryCode, CategoryValueCode, > CategoryValue) values(2, 1, 1); > > > no primary key > > > In insert while specifying to insert in few column instead of all in table you must have to include primary key. That means in your one of CategoryCode, CategoryValueCode, CategoryValue should be primary key or include fourth column that is primary key in table.
You are getting the error "No Primary Key" because you have not specified a valid unique primary key. Your table must be 4 columns. ``` INSERT INTO t_category_values (PRIMARY_KEY, CategoryCode, CategoryValueCode, CategoryValue) VALUES(pkey_value_here, 2, 1, 1); ``` The only time you dont need to specify the primary key column is when the primary key is an auto increment value. If it is an auto increment column the INSERT will automatically fill in that value for you and you dont need to worry about it.
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
``` insert into `DBA`.`t_category_values` (`CategoryCode`, `CategoryValueCode`, `CategoryValue`) values(1, 1, "aaa"); ```
Insert query eg:- ``` Insert into `tableName`(field1, field2, field3) values ('value1', 'value2', 'value3'); ```
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
Try this (**edited** because you use Sybase SQL Anywhere): ``` INSERT INTO dba.t_category_values (CategoryCode, CategoryValueCode, CategoryValue) VALUES(1, 1, 'aaa'); ``` **EDITED:** from [Sybase web page](http://manuals.sybase.com/onlinebooks/group-pbarc/conn5/sqlug/@Generic__BookTextView/4620;pt=1435/%2a): Adding rows to a table Suppose that a new eastern sales department is created, with the same manager as the current Sales department. You can add this information to the database using the following INSERT statement: ``` INSERT INTO department ( dept_id, dept_name, dept_head_id ) VALUES ( 220, 'Eastern Sales', 902 ) ``` If you make a mistake and forget to specify one of the columns, SQL Anywhere reports an error. The NULL value is a special value used to indicate that something is either not known or not applicable. Some columns are allowed to contain the NULL value, and others are not.
You are getting the error "No Primary Key" because you have not specified a valid unique primary key. Your table must be 4 columns. ``` INSERT INTO t_category_values (PRIMARY_KEY, CategoryCode, CategoryValueCode, CategoryValue) VALUES(pkey_value_here, 2, 1, 1); ``` The only time you dont need to specify the primary key column is when the primary key is an auto increment value. If it is an auto increment column the INSERT will automatically fill in that value for you and you dont need to worry about it.
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
Your query is wrong it should be: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES(1, 1, "aaa"); ``` See here for more help: [Sql Insert Wiki](http://en.wikipedia.org/wiki/Insert_%28SQL%29) --- **Edit:** Your query and error: > > insert into t\_category\_values > (CategoryCode, CategoryValueCode, > CategoryValue) values(2, 1, 1); > > > no primary key > > > In insert while specifying to insert in few column instead of all in table you must have to include primary key. That means in your one of CategoryCode, CategoryValueCode, CategoryValue should be primary key or include fourth column that is primary key in table.
The INSERT goes like this: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES (1, 1, "aaa"); ``` 1. No "double quotes" around table names, backticks are allowed. `DBA` is the database, `t_category_values` is the table. 2. Name the columns you want to fill 3. Add 'values' followed by the values for those columns. If you want to insert data **from another table**, use a SELECT: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) SELECT (CategoryCode, CategoryValueCode, CategoryValue) FROM `DBA`.`old_category_values`; ```
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
The INSERT goes like this: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES (1, 1, "aaa"); ``` 1. No "double quotes" around table names, backticks are allowed. `DBA` is the database, `t_category_values` is the table. 2. Name the columns you want to fill 3. Add 'values' followed by the values for those columns. If you want to insert data **from another table**, use a SELECT: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) SELECT (CategoryCode, CategoryValueCode, CategoryValue) FROM `DBA`.`old_category_values`; ```
You are getting the error "No Primary Key" because you have not specified a valid unique primary key. Your table must be 4 columns. ``` INSERT INTO t_category_values (PRIMARY_KEY, CategoryCode, CategoryValueCode, CategoryValue) VALUES(pkey_value_here, 2, 1, 1); ``` The only time you dont need to specify the primary key column is when the primary key is an auto increment value. If it is an auto increment column the INSERT will automatically fill in that value for you and you dont need to worry about it.
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
Your query is wrong it should be: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES(1, 1, "aaa"); ``` See here for more help: [Sql Insert Wiki](http://en.wikipedia.org/wiki/Insert_%28SQL%29) --- **Edit:** Your query and error: > > insert into t\_category\_values > (CategoryCode, CategoryValueCode, > CategoryValue) values(2, 1, 1); > > > no primary key > > > In insert while specifying to insert in few column instead of all in table you must have to include primary key. That means in your one of CategoryCode, CategoryValueCode, CategoryValue should be primary key or include fourth column that is primary key in table.
Insert query eg:- ``` Insert into `tableName`(field1, field2, field3) values ('value1', 'value2', 'value3'); ```
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
The INSERT goes like this: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) VALUES (1, 1, "aaa"); ``` 1. No "double quotes" around table names, backticks are allowed. `DBA` is the database, `t_category_values` is the table. 2. Name the columns you want to fill 3. Add 'values' followed by the values for those columns. If you want to insert data **from another table**, use a SELECT: ``` INSERT INTO `DBA`.`t_category_values` (CategoryCode, CategoryValueCode, CategoryValue) SELECT (CategoryCode, CategoryValueCode, CategoryValue) FROM `DBA`.`old_category_values`; ```
Insert query eg:- ``` Insert into `tableName`(field1, field2, field3) values ('value1', 'value2', 'value3'); ```
5,673,223
I can't insert a value using this code: ``` insert into t_category_values (CategoryCode, CategoryValueCode, CategoryValue) values(2, 1, 1); ``` error msg ``` no primary key ```
2011/04/15
[ "https://Stackoverflow.com/questions/5673223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683150/" ]
Try this (**edited** because you use Sybase SQL Anywhere): ``` INSERT INTO dba.t_category_values (CategoryCode, CategoryValueCode, CategoryValue) VALUES(1, 1, 'aaa'); ``` **EDITED:** from [Sybase web page](http://manuals.sybase.com/onlinebooks/group-pbarc/conn5/sqlug/@Generic__BookTextView/4620;pt=1435/%2a): Adding rows to a table Suppose that a new eastern sales department is created, with the same manager as the current Sales department. You can add this information to the database using the following INSERT statement: ``` INSERT INTO department ( dept_id, dept_name, dept_head_id ) VALUES ( 220, 'Eastern Sales', 902 ) ``` If you make a mistake and forget to specify one of the columns, SQL Anywhere reports an error. The NULL value is a special value used to indicate that something is either not known or not applicable. Some columns are allowed to contain the NULL value, and others are not.
Insert query eg:- ``` Insert into `tableName`(field1, field2, field3) values ('value1', 'value2', 'value3'); ```
132,750
I want to create a table like [![enter image description here](https://i.stack.imgur.com/Xe1cb.png)](https://i.stack.imgur.com/Xe1cb.png) There are 2 cells in the 4th column which are merged vertically on the right side. While it is easy to merge them on the left side using `multirow`, I'm at a loss on how to merge on the right side Here is my source code (using [`IEEEtran.cls`](http://mirrors.ctan.org/macros/latex/contrib/IEEEtran/IEEEtran.cls)): ``` \documentclass[conference]{IEEEtran} % Add the compsoc option for Computer Society conferences. % *** GRAPHICS RELATED PACKAGES *** % \ifCLASSINFOpdf \usepackage[pdftex]{graphicx} % declare the path(s) where your graphic files are % \graphicspath{{../pdf/}{../jpeg/}} % and their extensions so you won't have to specify these with % every instance of \includegraphics \DeclareGraphicsExtensions{.pdf,.jpeg,.png,.eps} \else % or other class option (dvipsone, dvipdf, if not using dvips). graphicx % will default to the driver specified in the system graphics.cfg if no % driver is specified. \usepackage[dvips]{graphicx} % declare the path(s) where your graphic files are % \graphicspath{{../eps/}} % and their extensions so you won't have to specify these with % every instance of \includegraphics \DeclareGraphicsExtensions{.eps} \fi % correct bad hyphenation here \hyphenation{op-tical net-works semi-conduc-tor} \usepackage{lscape} \usepackage{multirow} %\usepackage{subfig} \usepackage{subfigure} %\usepackage{subcaption} \usepackage{tikz} \def\checkmark{\tikz\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;} \documentclass[conference]{IEEEtran} \ifCLASSINFOpdf \usepackage[pdftex]{graphicx} \DeclareGraphicsExtensions{.pdf,.jpeg,.png,.eps} \else \usepackage[dvips]{graphicx} \DeclareGraphicsExtensions{.eps} \fi % correct bad hyphenation here \hyphenation{op-tical net-works semi-conduc-tor} \usepackage{lscape} \usepackage{multirow} \usepackage{subfigure} \begin{document} \section{Introduction} \section{xxx} \begin{table}[h] \centering \begin{tabular}{ |p{0.6cm}|p{1cm}|p{0.6cm}|p{4cm}| } \hline {\fontsize{7}{60}\selectfont Source IP} & {\fontsize{7}{60}\selectfont Destination IP} & {\fontsize{7}{60}\selectfont CCN Name} & Example Application Scenarios \\ \hline $\times$ & xx & xx& Content requester wants to hide its location/IP \\ \hline dul & $\times$ & lus & \multirow{2}{*}{Content requester wants to hide its location/IP} \\ \cline{1-3} ddd & $\times$ & lus & \\ \hline $\times$ & Lucus & lus & Content requester wants to hide its location/IP \\ \hline $\times$ & Lucus & lus & Content requester wants to hide its location/IP \\ \hline \end{tabular} \caption{xxxx} \label{tab:header} \end{table} \begin{thebibliography}{1} \end{thebibliography} \end{document} ``` The result is the width of that two cells are not equal.
2013/09/11
[ "https://tex.stackexchange.com/questions/132750", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/36240/" ]
@egreg deserves the glory. Here is a MWE: ``` \begin{tabular}{l|l|l|l} a1 & a2 & a3 & a4\\ \hline b1 & b2 & b3 & \multirow{2}{*}{bc4}\\ \cline{1-3} c1 & c2 & c3 & \\ \hline d1 & d2 & d3 & d4 \end{tabular} ```
Try the following code: ``` \begin{table}[h] \centering \begin{tabular}{ |p{0.6cm}|p{1cm}|p{0.6cm}|p{4cm}| } \hline {\fontsize{7}{60}\selectfont Source IP} & {\fontsize{7}{60}\selectfont Destination IP} & {\fontsize{7}{60}\selectfont CCN Name} & Example Application Scenarios \\ \hline $\times$ & v & v & Content requester wants to hide its location/IP \\ \hline dul & $\times$ & lus & \multirow{2}{*}{\parbox[t]{4cm}{Content requester wants to hide its location/IP}} \\ \cline{1-3} ddd & $\times$ & lus & \\ \hline $\times$ & Lucus & lus & Content requester wants to hide its location/IP \\ \hline $\times$ & Lucus & lus & Content requester wants to hide its location/IP \\ \hline \end{tabular} \caption{xxx } \label{tab:header} \end{table} ```
41,236,858
I have created a ionic popup window, instead of the default two buttons at the bottom, I would like to add a button in the body of the popup window. Actually does it really possible to do so? If not, another other method / suggestion? I have tried to insert some html code in the template but it didn't work. I would like to add a button like the grey button as shown in the diagram. Thank you for your time for reading my question. [![enter image description here](https://i.stack.imgur.com/NMowe.png)](https://i.stack.imgur.com/NMowe.png)
2016/12/20
[ "https://Stackoverflow.com/questions/41236858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6878655/" ]
If you have tried everything that comes as an accepted ans according to your links for the ques, then why don't you try debugging your start activity, i mean on which you have put intent to start the respective activity. While debugging one of my application i found that android soft keyboard has that problem of not going down even after finishing the activity that calls it, it stays on screen for few seconds but this doesn't happen frequently. So i suggest you to debug your calling activity too just try putting "focusable=false" on the component from which you called the respective activity.
Simply what you need to do is to give ``` android:windowSoftInputMode="stateHidden" ``` in Manifest file of your Activity.
41,236,858
I have created a ionic popup window, instead of the default two buttons at the bottom, I would like to add a button in the body of the popup window. Actually does it really possible to do so? If not, another other method / suggestion? I have tried to insert some html code in the template but it didn't work. I would like to add a button like the grey button as shown in the diagram. Thank you for your time for reading my question. [![enter image description here](https://i.stack.imgur.com/NMowe.png)](https://i.stack.imgur.com/NMowe.png)
2016/12/20
[ "https://Stackoverflow.com/questions/41236858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6878655/" ]
If you have tried everything that comes as an accepted ans according to your links for the ques, then why don't you try debugging your start activity, i mean on which you have put intent to start the respective activity. While debugging one of my application i found that android soft keyboard has that problem of not going down even after finishing the activity that calls it, it stays on screen for few seconds but this doesn't happen frequently. So i suggest you to debug your calling activity too just try putting "focusable=false" on the component from which you called the respective activity.
Write below line inside your main xml tag ``` android:descendantFocusability="beforeDescendants" android:focusableInTouchMode="true" ``` just as below ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mainLayout" android:descendantFocusability="beforeDescendants" android:focusableInTouchMode="true" > ```
41,236,858
I have created a ionic popup window, instead of the default two buttons at the bottom, I would like to add a button in the body of the popup window. Actually does it really possible to do so? If not, another other method / suggestion? I have tried to insert some html code in the template but it didn't work. I would like to add a button like the grey button as shown in the diagram. Thank you for your time for reading my question. [![enter image description here](https://i.stack.imgur.com/NMowe.png)](https://i.stack.imgur.com/NMowe.png)
2016/12/20
[ "https://Stackoverflow.com/questions/41236858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6878655/" ]
If you have tried everything that comes as an accepted ans according to your links for the ques, then why don't you try debugging your start activity, i mean on which you have put intent to start the respective activity. While debugging one of my application i found that android soft keyboard has that problem of not going down even after finishing the activity that calls it, it stays on screen for few seconds but this doesn't happen frequently. So i suggest you to debug your calling activity too just try putting "focusable=false" on the component from which you called the respective activity.
Use these lines in `java` file: ``` InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); ```
64,626
I'm trying to follow some of the best practices of the "open science" movement. In my thesis, I've performed all of the analyses in R (a non-proprietary, open-source program for analyzing data), and my datasets are in the non-proprietary CSV format. I would like to be as transparent as possible, by sharing my datasets and R analysis/code files with my thesis committee, and ultimately with the public once my thesis is finalized and placed in a repository. How can I best do this? I was thinking about uploading my files to the Open Science Framework (<http://osf.io>) and citing them with a regular HTTPS link. Once my thesis is finalized, I would then "freeze" them on the OSF website (as I understand, this would prevent post-hoc changes), then get a DOI that points to the frozen files and cite that. Are there any better options?
2016/03/05
[ "https://academia.stackexchange.com/questions/64626", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/50325/" ]
First, best compliments for your intent on open and reproducible research! Your code and datasets ought to bring you better visibility for your research. GitHub is a good alternative to publish your code. If your datasets involve elements of machine learning you may donate it to the UCI Machine Learning Repository.
Check [figshare](https://figshare.com). I have no complaints, but I still under the free quota. Recently, I came across more 3 interesting data repository: * [The Dataverse project](http://dataverse.org/); * [mlData](http://mldata.org/); and * [OpenMl](http://www.openml.org/).
64,626
I'm trying to follow some of the best practices of the "open science" movement. In my thesis, I've performed all of the analyses in R (a non-proprietary, open-source program for analyzing data), and my datasets are in the non-proprietary CSV format. I would like to be as transparent as possible, by sharing my datasets and R analysis/code files with my thesis committee, and ultimately with the public once my thesis is finalized and placed in a repository. How can I best do this? I was thinking about uploading my files to the Open Science Framework (<http://osf.io>) and citing them with a regular HTTPS link. Once my thesis is finalized, I would then "freeze" them on the OSF website (as I understand, this would prevent post-hoc changes), then get a DOI that points to the frozen files and cite that. Are there any better options?
2016/03/05
[ "https://academia.stackexchange.com/questions/64626", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/50325/" ]
First, best compliments for your intent on open and reproducible research! Your code and datasets ought to bring you better visibility for your research. GitHub is a good alternative to publish your code. If your datasets involve elements of machine learning you may donate it to the UCI Machine Learning Repository.
I understand that this question is old but allow me to share my opinion. The OSF is one of the stable open data repository, just like Figshare, Zenodo, and many other similar free services. Many scientists have used it and I heard no complaints so far regarding its link or DOI stability over time. So it is very good for students or any scientist to post their dataset and code separately in this repository. I know that you can also do it the old way by embedding the code and data directly in the document (paper or thesis), but by making them available separately is highly advised to increase the visibility of your work. Other scientist can cite it just like they cite other scientific document, by adding the link and the DOI. You can always contact OSF team to seek for advise on how to maximise your OSF account or how to cite documents on OSF properly. Just do it again for your future research, considering you must be graduated by now. Best wishes.
64,626
I'm trying to follow some of the best practices of the "open science" movement. In my thesis, I've performed all of the analyses in R (a non-proprietary, open-source program for analyzing data), and my datasets are in the non-proprietary CSV format. I would like to be as transparent as possible, by sharing my datasets and R analysis/code files with my thesis committee, and ultimately with the public once my thesis is finalized and placed in a repository. How can I best do this? I was thinking about uploading my files to the Open Science Framework (<http://osf.io>) and citing them with a regular HTTPS link. Once my thesis is finalized, I would then "freeze" them on the OSF website (as I understand, this would prevent post-hoc changes), then get a DOI that points to the frozen files and cite that. Are there any better options?
2016/03/05
[ "https://academia.stackexchange.com/questions/64626", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/50325/" ]
Check [figshare](https://figshare.com). I have no complaints, but I still under the free quota. Recently, I came across more 3 interesting data repository: * [The Dataverse project](http://dataverse.org/); * [mlData](http://mldata.org/); and * [OpenMl](http://www.openml.org/).
I understand that this question is old but allow me to share my opinion. The OSF is one of the stable open data repository, just like Figshare, Zenodo, and many other similar free services. Many scientists have used it and I heard no complaints so far regarding its link or DOI stability over time. So it is very good for students or any scientist to post their dataset and code separately in this repository. I know that you can also do it the old way by embedding the code and data directly in the document (paper or thesis), but by making them available separately is highly advised to increase the visibility of your work. Other scientist can cite it just like they cite other scientific document, by adding the link and the DOI. You can always contact OSF team to seek for advise on how to maximise your OSF account or how to cite documents on OSF properly. Just do it again for your future research, considering you must be graduated by now. Best wishes.
171,023
According to the sequence of tenses in the following sentence, which should be used, 'is' or 'was'? > > She got a well-paid job as she is/was proficient in both English and Chinese. > > >
2018/07/02
[ "https://ell.stackexchange.com/questions/171023", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/76987/" ]
Depends on the context. If it is recent and the effects are still applied, I'd use *'is.'* > > She got the job as she's proficient in both English and Chinese > > > But, should it be a distant past, I'd use *was* (especially in storytelling). > > He got the job as a gym trainer as he *was* very strong and in shape > > >
Although it seems logical to apply the present tense, which can imply a continuous state of being, to her dual qualifications of speaking both English and Chinese, the correct choice in context is to use the past tense of *was*. The usage in the balance of the sentence is determined by the opening usage of what her qualifications *were* at the time, in the past, when she received the well-paid job.
38,700,449
I am trying to insert a large xml file with length 43000 into `clob`. [asktom](https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1202548400346932817) remcomanded using bind variables but its links was broken. so my question how to insert large xml file in a bind variable . this is my procedure ``` CREATE OR REPLACE PROCEDURE sp_insert_xml ( p_id IN INT, p_xml IN clob ) AS BEGIN declare x clob; y number(10); begin SELECT FILE into x from PROCESS_D where PROCESS_ID =1; select dbms_lob.getlength(x) into y from dual; DBMS_OUTPUT.PUT_LINE(y); end; --INSERT INTO TEST_ID VALUES (p_id, p_xml); END; ``` I want to split the length so I can insert them into a table
2016/08/01
[ "https://Stackoverflow.com/questions/38700449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291869/" ]
This ``` <img ng-src="https://someimageurl/{{ foo.replace('bar','') }} /> ``` is not an *angular replace method*, is just the *javascript replace method* being called inside angular interpolation. In angular2, you can do the same by doing: ``` <img [src]="'https://someimageurl/' + foo.replace('bar','')"/> ``` You can find more information about Template Syntax in [Angular 2 docs](https://angular.io/docs/ts/latest/guide/template-syntax.html).
Like this: ``` <img [src]="'https://someimageurl/' + foo.replace('bar','')" /> ```
4,322,649
> > Find the area under the graph of > $$ > f(t) = \frac{t}{(1+t^2)^a} > $$ > between $t=0$ and $t=x$ where $a>0$ and $a \neq 1$ is fixed, and evaluate the limit as $x \to \infty$. > > > Hello, for this question I tried using substitution but the different conditions like $t=0$ and $t=x$ confuse me. Especially what "$a$" is, since $a$ is positive and not equal $1$, I'm completely stuck there. Please explain how I would approach this question. I know substitution is neccesarly
2021/12/03
[ "https://math.stackexchange.com/questions/4322649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/971591/" ]
Hint: substitute $1 + t^2 = u$. If $t = 0$, what is $u$? If $t = x$, what is $u$? > > \begin{align} 1 + t^2 = u &\Rightarrow 2tdt = du\\ t = 0 &\Rightarrow u = 1+0^2 = 1\\ t = x &\Rightarrow u = 1+x^2 \end{align} > > > $a$ is a parameter, which you should consider as a fixed number.
You could use the reverse-chain rule: Let $u = 1 + t^2$, Then you have $du = 2t \times dt$ Hence, your integral becomes: $$\int{\frac{1}{u^a} \times t}{dt} \to \frac{1}{2}\int{\frac{1}{u^a} \times 2t}{dt} \to \frac{1}{2}\int{\frac{1}{u^a} du}$$ Since $a ≠ \{0, 1\}$ and $a > 0$ you can apply the index laws in integration. $$\frac{1}{2}\int{\frac{1}{u^a} du} = \frac{1}{2}\int{u^{-a} du} = \frac{1}{2} (\frac{1} {-a + 1} \times u^{-a + 1}) + C$$
4,322,649
> > Find the area under the graph of > $$ > f(t) = \frac{t}{(1+t^2)^a} > $$ > between $t=0$ and $t=x$ where $a>0$ and $a \neq 1$ is fixed, and evaluate the limit as $x \to \infty$. > > > Hello, for this question I tried using substitution but the different conditions like $t=0$ and $t=x$ confuse me. Especially what "$a$" is, since $a$ is positive and not equal $1$, I'm completely stuck there. Please explain how I would approach this question. I know substitution is neccesarly
2021/12/03
[ "https://math.stackexchange.com/questions/4322649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/971591/" ]
Hint: substitute $1 + t^2 = u$. If $t = 0$, what is $u$? If $t = x$, what is $u$? > > \begin{align} 1 + t^2 = u &\Rightarrow 2tdt = du\\ t = 0 &\Rightarrow u = 1+0^2 = 1\\ t = x &\Rightarrow u = 1+x^2 \end{align} > > > $a$ is a parameter, which you should consider as a fixed number.
You are correct that a substitution will work here. Namely, $u = 1+t^2$, which has differential $du = 2t \, dt$ and $u = 1 + 0^2 = 1$ and $u = 1 + x^2$. Can you make the substitution and complete the integral? (Treat $a$ and $x$ as if they are numbers.) Click to reveal: > > \begin{align} \int\_0^x \!\! \frac{t}{(1+t^2)^a} \, dt &= \frac12 \int\_1^{1+x^2} \!\! u^{-a} \, du \\ &= \biggl.\frac{1}{2(1-a)} \cdot \frac{1}{u^{a+1}} \biggr\rvert\_1^{1+x^2} \\ &= \frac{1}{2(1-a)} \biggl( \frac{1}{(1+x^2)^{a+1}} - 1 \biggr) \\ &= \frac{1}{2(a-1)} \biggl( 1 - \frac{1}{(1+x^2)^{a+1}} \biggr) \end{align} > > > This expression gives the value of the definite integral in terms of the quantities $a$ and $x$. Now, if you want to let $x$ increase without bound, you evaluate the the improper integral as a limit: > > \begin{align} \int\_0^\infty \!\! \frac{t}{(1+t^2)^a} \, dt &= \lim\_{x \to \infty} \int\_0^x \!\! \frac{t}{(1+t^2)^a} \, dt \\ &= \lim\_{x \to \infty} \frac{1}{2(a-1)} \biggl( 1 - \frac{1}{(1+x^2)^{a+1}} \biggr) \\ &= \frac{1}{2(a-1)}. \end{align} > > >
231,208
If $T:\Bbb R^n \to\Bbb R^m$ (where $n\neq m$) is a linear transformation, can $T$ be both one to one and onto? My first instinct was it can, but after thinking about it, it seems the set will either be dependent or there would be a row without a pivot. Is there a way to prove this for all examples?
2012/11/06
[ "https://math.stackexchange.com/questions/231208", "https://math.stackexchange.com", "https://math.stackexchange.com/users/48357/" ]
It's a ready consequence of [Kernel Extension Theorem (for vector spaces)](http://en.wikipedia.org/wiki/Dimension_theorem#Kernel_extension_theorem_for_vector_spaces) that such a transformation must either fail to be one-to-one or fail to be onto. (You may have heard "kernel" referred to as "null space" instead.) If $n<m$, then since the image (range) of the transformation has dimension at most $n$, it can't be the whole space $\Bbb R^m$, and so fails to be onto, even if it's one-to-one (that is, has a kernel of dimension $0$). If $n>m$, then since the image of the transformation has dimension at most $m$ (as a subspace of $\Bbb R^m$), it follows that the kernel of the transformation has positive dimension, and to the transformation fails to be one-to-one, even if it's onto (that is, has an image of dimension $m$). If you'd rather think of things in terms of the matrix corresponding to the transformation, see the [Rank-Nullity Theorem](http://en.wikipedia.org/wiki/Rank-nullity_theorem).
Suppose an operator $T$ on a finite dimensional space is one to one and onto. Then $v\_1,...,v\_k$ are linearly independent iff $T v\_1, ..., T v\_k$ are linearly independent. (Since $T$ is onto, it follows from this that $u\_1,...,u\_k$ are linearly independent iff $T^{-1} u\_1, ..., T^{-1} u\_k$ are linearly independent.) Hence a basis for the domain can be transformed into a basis for the range (of the same cardinality) and vice versa. It follows that the dimension of the range and domain are the same.
5,850,142
I know .NET and Mono are binary compatible but given a set of source code, will csc and mcs produce the exact same 100% identical binary CLI executable? Would one be able to tell whether an executable was compiled with csc or mcs?
2011/05/01
[ "https://Stackoverflow.com/questions/5850142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343845/" ]
A lot of things are not fully defined in the spec, or are implementation-specific extensions. Examples of not-fully-specified: * the synchronisation semantics of field-like events; this is ***explicitly*** open to implementations in the ecma spec; it is stricty defined in the MS spec, but uses a different version in c# 4.0 which ***does not yet*** appear in the formal spec, IIRC * `Expression` construction (from lambdas); is simply "defined elsewhere" (actually, it isn't) Examples of implementation extensions: * P/Invoke * COM interface handling (i.e. how you can call `new` on an interface) So no: it is not guarantees to have the same IL, either between csc or [g]mcs - but even between different versions of csc. Even more: depending on debug settings, optimizations being enabled or not, and some compilation constants being defined (such as DEBUG or TRACE), the same compiler will generate different code.
I'm sure they don't produce the same IL from the same sourcecode. Even different versions of the MS C# compiler don't. The optimizer will work differently and create slightly different code. I expect larger differences in the implementation of complex features such as iterators, local variable captured for lamdas,... Then there are arbitrary compiler generated names, for example for anonymous types. No reason why they should use the same naming scheme for them. I wouldn't be surprised if there was some assembly metadata containing the name and version of your compiler too.
331,365
I have a macOS 10.13 machine that is being used only for remote work, and has no need for printers. Printer Sharing is definitely turned off in System Preferences, and yet, `cupsd` is listening to a port: ``` # lsof -i :631 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME cupsd 427 root 5u IPv6 0xbb661a1308e1d70b 0t0 TCP localhost:ipp (LISTEN) cupsd 427 root 6u IPv4 0xbb661a130bee2d13 0t0 TCP localhost:ipp (LISTEN) ``` What is the appropriate way to turn off `cupsd`?
2018/07/17
[ "https://apple.stackexchange.com/questions/331365", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/6489/" ]
In the terminal... `sudo launchctl unload /System/Library/LaunchDaemons/org.cups.cupsd.plist` ...will unload cups. This stops the service. After that, `sudo launchctl remove /System/Library/LaunchDaemons/org.cups.cupsd.plist` ...will ensure that cups does not come back after a reboot. I don't know how OS X will react if you try to leave cups unloaded in the long term. Also, I am nearly certain that major (and likely some minor) OS updates will "correct the issue" and reload cups for you. So helpful. Last, you can check to see what services are currently running by using `sudo launchctl list`
The correct command, especially with macOS Catalina, to permanently disable cups is: `sudo launchctl unload -w /System/Library/LaunchDaemons/org.cups.cupsd.plist` (The currently accepted answer states `launchctl remove /System/Library/LaunchDaemons/org.cups.cupsd.plist` but in fact that doesn't do anything other than fail silently with an error return code)
17,407,435
There is a code which generate the file with one proc: ``` puts $fh "proc generate \{ fileName\} \{" puts $fh "[info body generateScriptBody]" puts $fh "\}" puts $fh "generate" close $fh proc generateScriptBody{} { source something1 source something2 ... } ``` In this case should I `source` inside proc or there are alternatives?
2013/07/01
[ "https://Stackoverflow.com/questions/17407435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892307/" ]
I don't understand what you are trying to do, but source within a proc is acceptable. If you are looking to write the whole proc into a file, take a look at `saveprocs` from the TclX package; it will help simplifying your code. ### Update Here is an example of using `saveprocs`: ``` package require Tclx # Generate a proc from body of one or more files set body [read_file something1] append body "\n" [read_file something2] proc generate {fileName} $body # Write to file saveprocs generate.tcl generate ``` In this case, I did away with all the `source` commands and read the contents directly into the proc's body.
I just encountered a problem with calling source inside a proc, maybe it's helpful for someone. I have two test files. This is `sourcetest1.tcl` which sources `sourcetest2.tcl` in three different ways: ``` puts "sourcetest1.tcl" proc mysource_wrong {script} { source $script } proc mysource_right {script} { uplevel "source sourcetest2.tcl" } #source sourcetest2.tcl #mysource_right sourcetest2.tcl mysource_wrong sourcetest2.tcl ``` This is `sourcetest2.tcl`: ``` puts "sourcetest2.tcl" set l {1 2 3} puts "outside: $l" proc doit {} { global l puts "doit: $l" } doit ``` Everything is fine with a direct `source` and with `mysource_right`, the output is in both cases: ```none sourcetest1.tcl sourcetest2.tcl outside: 1 2 3 doit: 1 2 3 ``` However, with `mysource_wrong`, we get the following output: ```none sourcetest1.tcl sourcetest2.tcl outside: 1 2 3 can't read "l": no such variable while executing "puts "doit: $l"" (procedure "doit" line 3) invoked from within "doit" (file "sourcetest2.tcl" line 12) invoked from within "source $script" (procedure "mysource_wrong" line 2) invoked from within "mysource_wrong sourcetest2.tcl" (file "sourcetest1.tcl" line 13) ``` My interpretation is that a `source` inside a `proc` puts the variable `l` into the scope of the `proc`, not into the global scope. This can be avoided by using `uplevel` like in `mysource_right`.
21,521,410
I have an js object like ``` { a: 1, b: 2, c: 3 } ``` I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below, ``` "{"a":"1", "b":"2", "c":"3"}" ``` But it is returning me like the below one if my js object has too many properties say more than 500, ``` "{"b":"2", "a":"1", "c":"3"}" ``` Is there any option to get my js object's json string as in sorted in asc.
2014/02/03
[ "https://Stackoverflow.com/questions/21521410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/744534/" ]
If the order is important for you, don't use `JSON.stringify` because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using `JSON.stringify` for our values, for instance if we have a string like `'abc\d"efg'`, we can simply get the proper result `JSON.stringify('abc\d"efg')`, because the whole idea of this function is to stringify in a right order: ``` function sort_stringify(obj){ var sortedKeys = Object.keys(obj).sort(); var arr = []; for(var i=0;i<sortedKeys.length;i++){ var key = sortedKeys[i]; var value = obj[key]; key = JSON.stringify(key); value = JSON.stringify(value); arr.push(key + ':' + value); } return "{" + arr.join(",\n\r") + "}"; } var jsonString = sort_stringify(yourObj); ``` If we wanted to do this not using `JSON.stringify` to parse the keys and values, the solution would be like: ``` function sort_stringify(obj){ var sortedKeys = Object.keys(obj).sort(); var arr = []; for(var i=0;i<sortedKeys.length;i++){ var key = sortedKeys[i]; var value = obj[key]; key = key.replace(/"/g, '\\"'); if(typeof value != "object") value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); arr.push('"' + key + '":"' + value + '"'); } return "{" + arr.join(",\n\r") + "}"; } ```
The JavaScript objects are unordered by definition (you may refer to ECMAScript Language Specification under section 8.6, [click here for details](http://www.ecma-international.org/publications/standards/Ecma-262.htm) ). The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time. If you still required sorting, convert the object into Array apply any sorting algorithm on it and then do JSON.stringify() on sorted array. Lets have an example below as: ``` var data = { one: { rank: 5 }, two: { rank: 2 }, three: { rank: 8 } }; var arr = []; ``` Push into array and apply sort on it as : ``` var mappedHash = Object.keys( data ).sort(function( a, b ) { return data[ a ].rank - data[ b ].rank; }).map(function( sortedKey ) { return data[ sortedKey ]; }); ``` And then apply JSON.stringy : ``` var expectedJSON = JSON.stringify(mappedHash); ``` The output will be: ``` "[{"rank":2},{"rank":5},{"rank":8}]" ```
74,435
What is the function of the two segnos in the following score? At the start of measure 7 there is a segno, and in measure 70 there is a second segno together with a Da Capo. In the following measure there is this indication (in Spanish): > > *Se toca otra vez la primera parte y luego la tercera* > > > Which translates as: > > "The first part is played again and then the third one" > > > [![Score of "Teresita - Valse"](https://i.stack.imgur.com/2cMTx.jpg)](https://i.stack.imgur.com/2cMTx.jpg) (see [here](https://drive.google.com/open?id=1EjN20nnXGzrgLUFGaxVaDpIBbuH1O34g) for larger image)
2018/09/06
[ "https://music.stackexchange.com/questions/74435", "https://music.stackexchange.com", "https://music.stackexchange.com/users/52590/" ]
This piece seems to have several mistakes in instructions and in notation. "The first part is played again and then the third one" doesn't seem to make sense. It's too vague. Also, the D.C. should be a D.S. al Fine. That makes more sense of the two segnos. There should logically be a Fine half way along the 5th line, the bar before the repeat. In this way, the format makes more logical sense - play the page from beginning to end, then do the repeat from half way through the 5th line, until the D.S. al Fine (beginning of second to bottom line), then from the sign (b.7) and finish half way through line 5. In notation, b.16 right hand should, I think, be the same as in b.32. Also, b.20 left hand should be the same as in b.19, and finally the 'B' in the left hand of the first bar in the final line should be a 'C'. That's my interpretation of what may have been meant in this little piece, anyway.
Jomiddnz is probably correct, but here's a possible alternative. Play thru to the end, then to the repeat to the end, then back to the repeat a third time, but this time hit the DS (written DC) and then finish off at the double bar in third desk. That might explain what the editor was thinking so far as "third time" goes.
47,528,077
I found the pattern used by the Google places IOS SDK to be clean and well designed. Basically they follow what is presented on the following apple presentation: [Advanced User interface with Collection view](https://developer.apple.com/videos/play/wwdc2014/232/) (It start slide 46). This is what is implemented in their GMSAutocompleteTableDataSource. It us up to the datasource to define the state of the tableview. We link the tableview. ``` var googlePlacesDataSource = GMSAutocompleteTableDataSource() tableView.dataSource = googlePlacesDataSource tableView.delegate = googlePlacesDataSource ``` Then every time something change the event is binded to the datasource: ``` googlePlacesDataSource.sourceTextHasChanged("Newsearch") ``` The data source perform the query set the table view as loading and then display the result. I would like to achieve this from my custom Source: ``` class JourneyTableViewDataSource:NSObject, UITableViewDataSource, UITableViewDelegate{ private var journeys:[JourneyHead]?{ didSet{ -> I want to trigger tableView.reloadData() when this list is populated... -> How do I do that? I do not have a reference to tableView? } } override init(){ super.init() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } ... } ``` Any idea?
2017/11/28
[ "https://Stackoverflow.com/questions/47528077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/876087/" ]
Change this: ``` A* a; ``` to this: ``` ::A* a; ``` since `C` inherits from `B`, and `B` from `A`, thus you need the scope resolution operator to do the trick. Instead of starting at the local scope which includes the class parents, `::A` starts looking at the global scope because of the `::`. From the [Standard](http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4567.pdf): > > **11.1.5 Acess Specifiers** > > > In a derived class, the lookup of a base class name will find the > injected-class-name instead of the name of the base class in the scope > in which it was declared. The injected-class-name might be less > accessible than the name of the base class in the scope in which it > was declared. > > >
ISO C++: 11.1 Access Specifiers > > 5 [Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. —end note] > > > And the example from the standard: ``` class A { }; class B : private A { }; class C : public B { A* p; // error: injected-class-name A is inaccessible ::A* q; // OK }; ``` --- [N3797 Working Draft, Standard for Programming Language C++](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)
70,333
I have a Sony VAIO VPCF22S1E. I just upgraded from 11.04 to 11.10 . While upgrading (on downloading packages step) I lost my internet connection and 2-3 minutes later it resumed. I continued to download packages. And finally, upgrading is completed. Now I'm using 11.10 . But when I log in to Ubuntu after 2 minutes the touchpad will be unresponsive. I can't use it or the integrated buttons. The **Disable touchpad while typing** option is turned off (suggested from [this answer](https://askubuntu.com/questions/66081/touchpad-gets-disabled-after-sometime-after-login/66142#66142)) but it did not solve the problem. How can I sure my packages downloaded and installed successfully? (As I said, I lost my connection while downloading packages) *PS: I can use USB mouse.* *PPS: I have tried `apt-get update` , `apt-get upgrade`*
2011/10/21
[ "https://askubuntu.com/questions/70333", "https://askubuntu.com", "https://askubuntu.com/users/17345/" ]
Here is a fix worked for first reboot but **now it's not working** : 1. Edit `/etc/default/grub` to include `GRUB_CMDLINE_LINUX=”i8042.nopnp”` 2. Run: `sudo update-grub` 3. Reboot.
Turn off disable touchpad while typing in mouse options and reboot.
70,333
I have a Sony VAIO VPCF22S1E. I just upgraded from 11.04 to 11.10 . While upgrading (on downloading packages step) I lost my internet connection and 2-3 minutes later it resumed. I continued to download packages. And finally, upgrading is completed. Now I'm using 11.10 . But when I log in to Ubuntu after 2 minutes the touchpad will be unresponsive. I can't use it or the integrated buttons. The **Disable touchpad while typing** option is turned off (suggested from [this answer](https://askubuntu.com/questions/66081/touchpad-gets-disabled-after-sometime-after-login/66142#66142)) but it did not solve the problem. How can I sure my packages downloaded and installed successfully? (As I said, I lost my connection while downloading packages) *PS: I can use USB mouse.* *PPS: I have tried `apt-get update` , `apt-get upgrade`*
2011/10/21
[ "https://askubuntu.com/questions/70333", "https://askubuntu.com", "https://askubuntu.com/users/17345/" ]
Here is a fix worked for first reboot but **now it's not working** : 1. Edit `/etc/default/grub` to include `GRUB_CMDLINE_LINUX=”i8042.nopnp”` 2. Run: `sudo update-grub` 3. Reboot.
I have the same problem, When i face this, i open up terminal and logs myself out and then logs back in, this seems to be working for me, but this is not a solution but it seems to be working any way, The disabling the touch pad wont work as it happened again after doing so,
70,333
I have a Sony VAIO VPCF22S1E. I just upgraded from 11.04 to 11.10 . While upgrading (on downloading packages step) I lost my internet connection and 2-3 minutes later it resumed. I continued to download packages. And finally, upgrading is completed. Now I'm using 11.10 . But when I log in to Ubuntu after 2 minutes the touchpad will be unresponsive. I can't use it or the integrated buttons. The **Disable touchpad while typing** option is turned off (suggested from [this answer](https://askubuntu.com/questions/66081/touchpad-gets-disabled-after-sometime-after-login/66142#66142)) but it did not solve the problem. How can I sure my packages downloaded and installed successfully? (As I said, I lost my connection while downloading packages) *PS: I can use USB mouse.* *PPS: I have tried `apt-get update` , `apt-get upgrade`*
2011/10/21
[ "https://askubuntu.com/questions/70333", "https://askubuntu.com", "https://askubuntu.com/users/17345/" ]
I have the same problem, When i face this, i open up terminal and logs myself out and then logs back in, this seems to be working for me, but this is not a solution but it seems to be working any way, The disabling the touch pad wont work as it happened again after doing so,
Turn off disable touchpad while typing in mouse options and reboot.
352,352
I would like some input on some refactoring I am to do on a mobile backend (API). I have been tossed a mobile API which I need to refactor and improve upon, especially in the area of performance. One (of the many) place where I can improve the performance while also improve the architecture is how the backend currently deals with push notifications. Let me briefly describe how it currently works, and then how I intent to restructure it. This is how it works now. The example is about the user submitting a comment to a feed post: 1. The user clicks send in the mobile app. The app shows a spinner and meanwhile sends a request to the backend. 2. The backend receives the request and starts handling it. It inserts a row in the comments table, does some other bookkeeping stuff, and then for the affected mobile devices it makes a request to either the Apple Push Notification server or the Google Firebase Service (or both if the receiver has both an Android and an iPhone). 3. On success the backend returns a 200 to the mobile app. 4. Upon receiving status code 200 from the backend, the mobile app removes the spinner and updates the UI with the submitted comment. It is simple but the issue with the above as I see it is a) Currently this sample endpoint has too many responsibilities. It deals with saving a comment, and also with sending out push notifications to devices. b) The performance is not the best since the mobile app waits for the backend to both save a comment (which is pretty fast) and send a notification which requires a HTTP request (which can be anything from fast to slow). So my idea is to remove all about notifications from the backend, and host that in a separate backend app (you might call it a microservice). So what I am thinking is to do it like this: 1. The user clicks "Send" in the mobile app. The app shows a spinner and meanwhile sends a request to the main API backend. 2. The mobile app also sends of another HTTP request, this time to a notification service which is separate from the main API backend. This is kind of a fire and forget request. So the app does not wait for this in anyway, and it can be send in the background (in iOS using e.g. GCD). 3. The main backend receives the request about the comment, and starts handling it. It inserts a row in the comments table, perhaps does some other bookkeeping stuff, and then it returns the response to the mobile app. 4. The notification service receives the request about the comment, and inserts a row in a notification table (this is for historical reasons, e.g. to make an Activity view or something like that), and then puts a message on some queue (or on Redis). A separate job takes whatever is on the queue/Redis and handles it (this is where we actually send a request to Apple Push Notification Server and Googles Firebase Service). By not having the HTTP notification service do the talking with these external services it will be easier to scale the HTTP resources. 5. Upon receiving the 200 from the main backend, the mobile app removes the spinner and updates the UI with the submitted comment. Again note that the mobile app does not wait on the second request it send off (it's not like it can do anything if that fails anyway). So this is way more complex. But the main API backend is now only concerned actually saving the comment. The mobile app also needs to send two requests instead of just one, but it doesn't need to wait for the second request. So overall it should giver better performance I think. With regards to the notification service it could be simpler by not using a queue/Redis but just have the notification service call up Apple and Google with the push notifications. But I am thinking that by separating that out into a simple HTTP service that only does some basic bookkeeping stuff and putting stuff on a queue/Redis it can be fast and simple, and the separate job would then do the actual work of calling up Apple and Google. Does it makes sense? Or have I over complicated things? All comments appreciated.
2017/07/07
[ "https://softwareengineering.stackexchange.com/questions/352352", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/219850/" ]
An API is high level enough to expect it to do multiple things with a single action. If I have an endpoint that does a "Buy Product" then I would expect it to handle all of the transaction handling, logging, and updating balances rather than breaking them up into services the client needs to contact individually. You have the right idea of making the push notification a fire and forget operation, but it can be done with a single endpoint on your API. If you use a work queue just make two separate jobs and execute both: wait for one and forget the other.
There are several things that could go wrong and mess with the requests. For example network issues, cpu overload, running out of memory, internet traffic, db server running out of space, inefficient SQL statements, inefficient db mappings, data tables too huge and poorly indexed, bottlenecks somewhere, running out of workers, etc... Develop a plan first. You have to identify the source and do act accordingly with the issue. KISS!!! Start by the simplest solution and test. Do implement load tests for a representative measurament of the performance. Get metrics. Later, these test will measure the quality of the solution too. Regarding the solution you suggest. Hell no! Why don't you try first with parallel executions? Execute the notifications on another thread. Don't wait for it to be finished. As you say, fire and forget. But still, you will need a way to prove that the solution has fixed the problem and its order of magnitude.
5,638,321
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),\*). But when I try to run `sh -c ls | wc` in my home directory via my program it failed and its exit status was 32512, also in stderr stream `"sh: ls | wc: command not found"` was printed. But the interesting thing is that the command `sh -c ls | wc` works correct if I run it in shell. What is the problem? Or more preferable how can I run shell specific commands via my program (i.ec which command with which parameters should I run)? The code part bellow is in child part after fork(). It executs the command. `tokenized_command` is `std::vector<std::string>` where in my case `"sh", "-c", "ls", "|", "wc"` are stored, also I have tried to store there `"sh", "-c", "\"ls | wc\""` but result is same. `command` is `char *` where full command line is stored. ``` boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]); const char **argv = bargv.get(); for(int i = 0; i < tokenized_command.size(); ++i) { argv[i] = tokenized_command[i].c_str(); printf("argv[%d]: %s\n", i, argv[i]); //trace } argv[tokenized_command.size()] = NULL; if(execvp(argv[0], (char * const *)argv) == -1) { fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno)); _exit(EXIT_FAILURE); } ``` P.S. I know that using `system(command)` instead `execvp` can solve my problem. But `system()` waits until command is finished, and this is not good enough for my program. And also I'm sure that in implementation of `system()` one of exec-family functions is used, so the problem can be solved via `exec` as well, but I don't know how.
2011/04/12
[ "https://Stackoverflow.com/questions/5638321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509233/" ]
`execvp` takes a path to an executable, and arguments with which to launch that executable. It doesn't take bourne shell commands. `ls | wc` is a bourne shell command (among others), and it can't be broken down into the path to an executable and some arguments due to the use of a pipe. This means it can't be executed using `execvp`. To execute a bourne shell command using `execvp`, one has to execute `sh` and pass `-c` and the command for arguments. So you want to execute `ls | wc` using `execvp`. ``` char *const argv[] = { "sh", "-c", "ls | wc", // Command to execute. NULL }; execvp(argv[0], argv) ``` You apparently tried ``` char *const argv[] = { "sh", "-c", "ls", // Command to execute. "|", // Stored in called sh's $0. "wc", // Stored in called sh's $1. NULL }; ``` That would be the same as bourne shell command `sh -c ls '|' wc`. And both are very different than shell command `sh -c ls | wc`. That would be ``` char *const argv[] = { "sh", "-c", "sh -c ls | wc", // Command to execute. NULL }; ``` You seem to think `|` and `wc` are passed to the `sh`, but that's not the case at all. `|` is a special character which results in a pipe, not an argument. --- As for the exit code, ``` Bits 15-8 = Exit code. Bit 7 = 1 if a core dump was produced. Bits 6-0 = Signal number that killed the process. ``` 32512 = 0x7F00 So it didn't die from a signal, a core dump wasn't produced, and it exited with code 127 (0x7F). What 127 means is unclear, which is why it should accompanied by an error message. You tried to execute program `ls | wc`, but there is no such program.
You should execute `sh -c 'ls | wc'`. Option `-c` expects a command in form of string. In shell of course it is working, because there is no difference between spawning `ls` and redirecting output to `wc` and launching `ls | wc` in separate shell.
27,097,703
> > Error: System.Net.Mail.SmtpException: Failure sending mail. ---> System.ArgumentException: The IAsyncResult object was not returned from the corresponding asynchronous method on this class. Parameter name: asyncResult at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result) --- End of inner exception stack trace --- > > > ``` private void DispatchMail(MailMessage message, MessageTrackerObject trackInfo) { SmtpClient mailClient = new SmtpClient(); mailClient.Host = ConfigurationManager.AppSettings[(Constants.FAXSETTINGS_SMTPSERVER)]; mailClient.Port = int.Parse(ConfigurationManager.AppSettings[(Constants.FAXSETTINGS_SMTPPORT)]); //mailClient.DeliveryMethod = SmtpDeliveryMethod.Network; NetworkCredential ntCredential = new NetworkCredential(); if (GetStaticSetting(Constants.APPCONFIG_KEY_MAILWINDOWSAUTH).ToLower() == "true") { //mailClient.UseDefaultCredentials = true; } else { ntCredential.UserName = GetStaticSetting(Constants.APPCONFIG_KEY_MAILUSERID); ntCredential.Password = GetStaticSetting(Constants.APPCONFIG_KEY_MAILPASSWORD); mailClient.Credentials = ntCredential; mailClient.UseDefaultCredentials = false; } mailClient.EnableSsl = GetStaticSetting(Constants.APPCONFIG_KEY_MAIL_SSL).ToLower() == "true"; mailClient.SendCompleted += new SendCompletedEventHandler(MailClient_SendCompleted); mailClient.SendAsync(message, trackInfo); //mailClient.Send(message); } private void MailClient_SendCompleted(object sender, AsyncCompletedEventArgs e) { string error = ""; MessageTrackerObject data = (MessageTrackerObject)e.UserState; string msg = string.Format("File: {0}", data.Info); try { foreach (string serial in data.Serials) { if (e.Cancelled) { error = e.Error != null ? String.Format(" #Error: {0}", e.Error.ToString()) : ""; string cancelled = string.Format("{0} Send canceled. {1}", msg, error); SetFaxStatus(serial, FaxStatus.Cancelled, cancelled); } else if (e.Error != null) { error = String.Format("{0} #Error: {1}", msg, e.Error.ToString()); SetFaxStatus(serial, FaxStatus.Error, error); } else { SetFaxStatus(serial, FaxStatus.Sent, string.Format("{0} Mail sent successfully.", msg)); } } //release resource data.Message.Dispose(); } catch (Exception ex) { } } ``` How can i avoid this error?
2014/11/24
[ "https://Stackoverflow.com/questions/27097703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3332414/" ]
Most probably the problem here is that the same instance of `MailMessage` is passed to `DispatchMail`. `MailMessage` is not thread-safe by design, and each `SmtpClient.SendAsync` is internally invoking `Message.BeginSend`. So, when several threads are attempting to send same `MailMessage`, there is a race condition when calling `Message.EndSend`. If `EndSend` is invoked by the same thread which called `BeginSend` - we are in luck. If not - exception from above is raised, > > The IAsyncResult object was not returned from the corresponding > asynchronous method on this class > > > Solution here is either to copy `MailMessage` for each call of `SendAsync`, or use `SendAsync` overload which accepts 5 parameters: ``` void SendAsync(string from, string recipients, string subject, string body, object token) ``` Edit: This exception is very easy to reproduce, to prove that MailMessage is not thread-safe. You may get several exceptions, `IAsyncResult` one from above, or `Item has already been added` when populating headers: ``` using System; using System.Net.Mail; using System.Threading.Tasks; class App { static void Main() { var mail = new MailMessage("[email protected]", "[email protected]", "Test Subj", "Test Body"); var client1 = new SmtpClient("localhost"); var client2 = new SmtpClient("localhost"); var task1 = client1.SendMailAsync(mail); var task2 = client2.SendMailAsync(mail); Task.WhenAll(task1, task2).Wait(); } } ```
Use the `ManualResetEvent` object. I'm guessing the SmtpClient is being disposed that's why it's losing the subscription to `MailClient_SendCompleted` ``` ManualResetEvent resetEvent; private void DispatchMail(MailMessage message, MessageTrackerObject trackInfo) { // other code here resetEvent = new ManualResetEvent(false); mailClient.EnableSsl = GetStaticSetting(Constants.APPCONFIG_KEY_MAIL_SSL).ToLower() == "true"; mailClient.SendCompleted += new SendCompletedEventHandler(MailClient_SendCompleted); mailClient.SendAsync(message, trackInfo); resetEvent.WaitOne(TimeSpan.FromSeconds(5)); // waits for 5 seconds //mailClient.Send(message); } private void MailClient_SendCompleted(object sender, AsyncCompletedEventArgs e) { resetEvent.Set(); // removes the wait after successfully sending string error = ""; MessageTrackerObject data = (MessageTrackerObject)e.UserState; // other code here } ```
60,248,125
I have this simple code: ``` $postCopy = $_POST['adminpanel']; array_walk($postCopy, function($v, $k) { return ''; }); ``` I did `var_dump` for `postCopy` before and after `array_walk` execution. In both `var_dump` executions, I get the same result: ``` array(2) { ["usefulinfo_countryfilescount"]=> string(1) "3" ["strageticoverviews_filesinpagecount"]=> string(1) "3" } ``` So it means that `array_walk` didn't execute correctly, because if it would- I'd get an array with `''` values...
2020/02/16
[ "https://Stackoverflow.com/questions/60248125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870867/" ]
You just forgot to pass argument by reference : ``` $postCopy = $_POST['adminpanel']; array_walk($postCopy, function(&$v, $k) { $v = ''; }); ```
From [the manual](https://www.php.net/manual/en/function.array-walk.php): > > **Note**: > > > If `callback` needs to be working with the actual values of the array, specify the first parameter of `callback` as a [reference](https://www.php.net/manual/en/language.references.php). Then, any changes made to those elements will be made in the original array itself. > > > So you need to change your call to: ```php array_walk($postCopy, function(&$v, $k) { $v = ""; }); ``` Note the `&` in the argument list. The return value of `callback` is not actually used. Also, consider using [`array_map`](https://www.php.net/manual/en/function.array-map.php), if you are modifying all elements of an array.
54,338,297
How can I run a task from the command line for long-running jobs like reports from Jenkins in Spring Boot? I'm looking for something similar to Ruby on Rails Rake tasks. Rake tasks execute the code from the command line in the same application context as the web server so that you can re-use code. * I found [Spring Batch](https://spring.io/projects/spring-batch#overview) but it sounded more like [Resque](https://github.com/resque/resque). * I found [command line runners](https://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner) but it said that they all run before the web server starts, so I can't *not* run it or only run one task. * I found [scheduled tasks](https://spring.io/guides/gs/scheduling-tasks/) which sounds *perfect*, but my app is load balanced with many instances so I would not want it running multiple times at once! I have a report where the query takes more than 30s to run, and generates a CSV file I would like to mail. I want it to run automatically each week with cron or Jenkins.
2019/01/24
[ "https://Stackoverflow.com/questions/54338297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148844/" ]
I hacked a solution. Suggestions welcome. ``` package com.example.tasks; @Component public class WeeklyReport implements CommandLineRunner { @Override public void run(String... args) throws Exception { Arrays.asList(args).stream().forEach(a -> System.out.println(a)); if (!(args.length > 0 && args[0].equals("-task report:weekly"))) return; System.out.println("weekly report"); System.exit(0); } ``` And running it from a 'cron' job with ``` $ mvn spring-boot:run -Drun.arguments="-task report:weekly" ``` <https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-command-line-runner> <https://www.baeldung.com/spring-boot-command-line-arguments> <https://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner>
I was facing a similar problem recently and I came up with these three possible solutions: 1. Designate a "housekeeper" role that can be assumed by at most one instance whose responsibility would be complete the scheduled job. But for this the housekeeper would have to send a heartbeat to the others (through the load balancer..) and if it stops then the remaining instances must elect a new one so it seems to be an interesting but way more complex approach that I might play with later. 2. Have a single-instance external service that would run scheduled tasks and will generate the weekly csv for you 3. Have a single-instance external service that only has the capacity to make scheduled api calls and that would call your original service through the load balancer. I prefer this solution as all the resources to complete the task are already present at the original service and it preserves the functionality. It is also flexible as the scheduler service can be replaced by more light weight cron job with a curl call or merged to another service in the future..etc.
10,271,293
So I've been doing things with LINQ lately and I've been looking online for a complete list of all integrated LINQ keywords and i couldn't find any. These are some of the ones i know: ``` from in let group by into orderby where select ``` Are there any others that I don't know about? Where can I go to find a complete list of all the things possible with integrated LINQ?
2012/04/22
[ "https://Stackoverflow.com/questions/10271293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184746/" ]
You need to distinguish in your mind between the [*standard LINQ query operators*](http://msdn.microsoft.com/en-us/library/bb397896.aspx) and the operators that are supported in C# by [*query expressions*](http://msdn.microsoft.com/en-us/library/bb397676.aspx). There are far more of the former than the latter - and VB supports some of them in the language directly. For quite a bit of detail about all the different operators, and which query expression parts bind to them, you may want to read my [Edulinq blog post series](http://codeblog.jonskeet.uk/category/edulinq/). It's a reimplementation of LINQ to Objects for educational purposes, looking at how each operator behaves etc. [Part 41](http://codeblog.jonskeet.uk/2011/01/28/reimplementing-linq-to-objects-part-41-how-query-expressions-work/) is explicitly about query expressions, including a cheat sheet at the bottom.
You can read the official MSDN documentation [here](http://goo.gl/n9flt). Another good reference can be found on [odetocode](http://goo.gl/01UX1). **Edit:** I just wanted to clarify that what you're looking for are the C# keywords for LINQ, not operators.
29,108,950
I'm trying to draw text to a canvas with a certain alpha level and clip the text and draw a background color with it's own alpha level: ``` ctx.globalCompositeOperation = '...'; ctx.fillStyle = 'rgba(' + fgcolor.r + ', ' + fgcolor.g + ', ' + fgcolor.b + ',' + (fgcolor.a / 255.0) + ')'; ctx.fillText(String.fromCharCode(chr), x,y); ctx.globalCompositeOperation = '...'; ctx.fillStyle = 'rgba(' + bgcolor.r + ', ' + bgcolor.g + ', ' + bgcolor.b + ',' + (bgcolor.a / 255.0) + ')'; ctx.fillRect(x, y, chr_width, chr_height); ``` I've tried playing with globalCompositeOperation and beginPath but I have been unable to achieve the desired result. I would also like to avoid drawImage and off screen canvases as speed is a major concern.
2015/03/17
[ "https://Stackoverflow.com/questions/29108950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/806771/" ]
This function will convert RGBA colors to RGB: ``` function RGBAtoRGB(r, g, b, a, backgroundR,backgroundG,backgroundB){ var r3 = Math.round(((1 - a) * backgroundR) + (a * r)) var g3 = Math.round(((1 - a) * backgroundG) + (a * g)) var b3 = Math.round(((1 - a) * backgroundB) + (a * b)) return "rgb("+r3+","+g3+","+b3+")"; } ``` 1. Convert the background RGBA to RGB and fill the background with RGB. 2. Convert the foreground RGBA to RGB and fill the foreground text with RGB.
This is exactly what I'm trying to do: ``` ctx.clearRect(x, y, chr_width, chr_height); ctx.save(); ctx.beginPath(); ctx.rect(x, y, chr_width, chr_height); ctx.clip(); if (fgcolor.a != 255) { ctx.fillStyle = 'rgba(' + fgcolor.r + ', ' + fgcolor.g + ', ' + fgcolor.b + ',' + (fgcolor.a / 255.0) + ')'; ctx.fillText(String.fromCharCode(chr), x,y); var imgData=ctx.getImageData(x,y,chr_width,chr_height); for (var idx = 0; idx < imgData.data.length; idx+=4) { if (! imgData.data[idx+3]) { imgData.data[idx] = bgcolor.r; imgData.data[idx+1] = bgcolor.g; imgData.data[idx+2] = bgcolor.b; imgData.data[idx+3] = bgcolor.a; } } ctx.putImageData(imgData,x,y); } else { ctx.fillStyle = 'rgba(' + bgcolor.r + ', ' + bgcolor.g + ', ' + bgcolor.b + ',' + (bgcolor.a / 255.0) + ')'; ctx.fillRect(x, y, chr_width, chr_height); ctx.fillStyle = 'rgba(' + fgcolor.r + ', ' + fgcolor.g + ', ' + fgcolor.b + ',' + (fgcolor.a / 255.0) + ')'; ctx.fillText(String.fromCharCode(chr), x,y); } ctx.globalAlpha = 1.0; ctx.globalCompositeOperation = 'source-over'; ctx.restore(); ``` Are there any speedier ways of accomplishing this avoiding accessing the data directly? Thanks.
7,506,475
I am new to creating installers. Before used the Microsoft visual studio deployment package. Now trying inno setup, pretty awesome. I saw that Visual studio one wrote some registries when installed. Do I have to create Registries for my package too? I have a visual c# application and need to create a installer for my company. Main intention is to create a installer that will easily update the old one, but this is a first version of software we are going to release to customers. Much appreciated. I saw tutorials of Registry in internet, but the point of creating is the one that I don't understand.
2011/09/21
[ "https://Stackoverflow.com/questions/7506475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821332/" ]
You don't HAVE to write any registry entries unless your app requires them. Inno automatically creates the usual entries to allow uninstall from the Add/Remove programs applet. Inno will also automatically handle [upgrades](http://www.vincenzo.net/isxkb/index.php?title=Upgrades) with no special effort. If you have previously distributed the app using an MSI package, then you will either need to allow side by side installs (different folders, etc) or uninstall the previous version first. The article above has a sample of how to get the uninstall path.
I'm not sure what you are asking exactly. If you mean how do I write to the Windows Registry, you create a `[Registry]` section in your inno-setup file and add what you need. Here is a [link to the documentation](http://www.jrsoftware.org/ishelp/topic_registrysection.htm).
20,788,467
I want to go to a specific section of my website when I click on the link in the menu bar for that section of the website, so you do not have to scroll through all the content, but to have links to the different sections. I've read that you can do this with jQuery and make an animation for it so that the page can smoothly go to that section of the website. Here's the **HTML** code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="java.js"></script> <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> <title>Test Website</title> <meta name="" content=""> <script type="text/javascript"> </script> </head> <body> <header> <div id="title"> <h1 class="headertext">My Test Website</h1> </div> <div id="menubar"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> </div> </header> <div class="hide"> </div> <div id="container"> <div id="leftmenu"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> <div id="triangle"></div> </div> <div id="content"> <h1>Contentpage</h1></br> Picture slideshow </br> </br> <div class="slider"> <img id="1" src="images/car1.jpg" border="0" alt="car1"/> <img id="2" src="images/car2.jpg" border="0" alt="car2"/> <img id="3" src="images/car3.jpg" border="0" alt="car3"/> <img id="4" src="images/car4.jpg" border="0" alt="car4"/> <img id="5" src="images/car5.jpg" border="0" alt="car5"/> </div><!--slider end--> <div class="shadow"></div> <div class="borderbottom"></div> </div><!--content div--> </div> </body> </html> ``` And here is the **CSS** code: ``` *{ margin: 0 auto 0 auto; text-align: left; color: #ffffff; } body{ margin: 0; text-align: left; font-size: 13px; font-family: arial, helvetica, sens-serif; color: #ffffff; width: 1200px; height: auto; background: #f4f4f4; } header { position: fixed; width: 100%; top: 0; background: rgba(0,0,0,.8); z-index: 10; } h1{ color: black; text-align: center; } .hide { position: fixed; width: 100%; top: 0; background: rgba(255,255,255,1); z-index:5; height: 123px; } .headertext{ margin-top: 15px; text-align: center; color: white; } #title{ font-size: 20px; margin: -10px 0 30px 0; width: 100%; height: 70px; border-top: 2px solid #000000; border-bottom: 2px solid #000000; } #menubar{ margin-top: 10px; float: left; clear: both; width: 100%; height: 20px; list-style: none; border-bottom: 2px solid #010000; } #menubar ul{ list-style: none; margin-top: -15px; text-align: center; } #menubar ul li{ list-style: none; display: inline; padding-right: 80px; } #menubar ul li a{ color: #ffffff; text-decoration: none; font-size: 15px; font-weight: bold; } #menubar ul li a:hover{ border-bottom: 2px solid #ffffff; } #container{ width: 1200px; height: 1400px; } #leftmenu{ position: fixed; margin-top: 123px; margin-left: 50px; padding-top: 20px; float: left; width: 160px; height: 350px; list-style: none; background: rgba(0,0,0,0.8); color: #ffffff; border-left: 2px solid #010000; border-right: 2px solid #010000; } #leftmenu ul li{ display: block; padding-bottom: 50px; } #leftmenu ul li a{ font-weight: bold; text-decoration: none; color: #ffffff; font-size: 15px; text-align: center; } #leftmenu ul li a:hover{ border-bottom: 2px solid #ffffff; transition: opacity .5s ease-in; opacity: 1; } #triangle{ margin-top: 12px; margin-left: -1px; width: 0px; height: 0; border-top: 80px solid rgba(0,0,0,0.8); border-left: 82px solid transparent; border-right: 82px solid transparent; } #content{ text-align: left; margin-left: 100px; width: 1000px; padding-top: 150px; padding-left: 160px; color: #000000; font-weight: bold; text-align: center; font-size: 15px; } .slider{ margin-top: 20px; width: 600px; height: 400px; overflow: hidden; margin: auto; border-radius: 10px; vertical-align: middle; } .shadow{ background-image:url(../images/shadow.png); background-repeat: no-repeat; background-position: top; width: 850px; height: 144px; vertical-align: middle; margin-top: -50px; } .slider img{ width: 600px; height: 400px; display: none; } .borderbottom{ border: 6px solid rgba(0,0,0,0.8); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; width: 1000px; position: fixed; margin-top: 20px; } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20788467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123507/" ]
If you have jQuery loaded you could try like this, no plugin required just jquery will do... HTML: ``` <div id="menubar"> <ul> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> ........all the menu items------- </ul> ``` JS: ``` $('#menubar ul li a').on('click',function(event){ var $anchor = $(this); $('html, body').animate({ scrollTop: $($anchor.attr('href')).offset().top + "px" }, 1500); event.preventDefault(); }); ``` This is the working [fiddle](http://jsfiddle.net/YJwTJ/3)
To scroll to a particular element on the page, the element must have an ID : ``` <a class="scroll" href="#myElement">Link</a> <div id="myElement"></div> ``` This anchor will make the document scroll to the top of the element #myElement. Then animate it with JS : ``` $('a.scroll').click(function(){ var href = $(this).attr('href'); var dest = $(href).offset().top; $('html, body').animate({ scrollTop: dest; }, 1000); return false; }); ```
20,788,467
I want to go to a specific section of my website when I click on the link in the menu bar for that section of the website, so you do not have to scroll through all the content, but to have links to the different sections. I've read that you can do this with jQuery and make an animation for it so that the page can smoothly go to that section of the website. Here's the **HTML** code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="java.js"></script> <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> <title>Test Website</title> <meta name="" content=""> <script type="text/javascript"> </script> </head> <body> <header> <div id="title"> <h1 class="headertext">My Test Website</h1> </div> <div id="menubar"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> </div> </header> <div class="hide"> </div> <div id="container"> <div id="leftmenu"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> <div id="triangle"></div> </div> <div id="content"> <h1>Contentpage</h1></br> Picture slideshow </br> </br> <div class="slider"> <img id="1" src="images/car1.jpg" border="0" alt="car1"/> <img id="2" src="images/car2.jpg" border="0" alt="car2"/> <img id="3" src="images/car3.jpg" border="0" alt="car3"/> <img id="4" src="images/car4.jpg" border="0" alt="car4"/> <img id="5" src="images/car5.jpg" border="0" alt="car5"/> </div><!--slider end--> <div class="shadow"></div> <div class="borderbottom"></div> </div><!--content div--> </div> </body> </html> ``` And here is the **CSS** code: ``` *{ margin: 0 auto 0 auto; text-align: left; color: #ffffff; } body{ margin: 0; text-align: left; font-size: 13px; font-family: arial, helvetica, sens-serif; color: #ffffff; width: 1200px; height: auto; background: #f4f4f4; } header { position: fixed; width: 100%; top: 0; background: rgba(0,0,0,.8); z-index: 10; } h1{ color: black; text-align: center; } .hide { position: fixed; width: 100%; top: 0; background: rgba(255,255,255,1); z-index:5; height: 123px; } .headertext{ margin-top: 15px; text-align: center; color: white; } #title{ font-size: 20px; margin: -10px 0 30px 0; width: 100%; height: 70px; border-top: 2px solid #000000; border-bottom: 2px solid #000000; } #menubar{ margin-top: 10px; float: left; clear: both; width: 100%; height: 20px; list-style: none; border-bottom: 2px solid #010000; } #menubar ul{ list-style: none; margin-top: -15px; text-align: center; } #menubar ul li{ list-style: none; display: inline; padding-right: 80px; } #menubar ul li a{ color: #ffffff; text-decoration: none; font-size: 15px; font-weight: bold; } #menubar ul li a:hover{ border-bottom: 2px solid #ffffff; } #container{ width: 1200px; height: 1400px; } #leftmenu{ position: fixed; margin-top: 123px; margin-left: 50px; padding-top: 20px; float: left; width: 160px; height: 350px; list-style: none; background: rgba(0,0,0,0.8); color: #ffffff; border-left: 2px solid #010000; border-right: 2px solid #010000; } #leftmenu ul li{ display: block; padding-bottom: 50px; } #leftmenu ul li a{ font-weight: bold; text-decoration: none; color: #ffffff; font-size: 15px; text-align: center; } #leftmenu ul li a:hover{ border-bottom: 2px solid #ffffff; transition: opacity .5s ease-in; opacity: 1; } #triangle{ margin-top: 12px; margin-left: -1px; width: 0px; height: 0; border-top: 80px solid rgba(0,0,0,0.8); border-left: 82px solid transparent; border-right: 82px solid transparent; } #content{ text-align: left; margin-left: 100px; width: 1000px; padding-top: 150px; padding-left: 160px; color: #000000; font-weight: bold; text-align: center; font-size: 15px; } .slider{ margin-top: 20px; width: 600px; height: 400px; overflow: hidden; margin: auto; border-radius: 10px; vertical-align: middle; } .shadow{ background-image:url(../images/shadow.png); background-repeat: no-repeat; background-position: top; width: 850px; height: 144px; vertical-align: middle; margin-top: -50px; } .slider img{ width: 600px; height: 400px; display: none; } .borderbottom{ border: 6px solid rgba(0,0,0,0.8); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; width: 1000px; position: fixed; margin-top: 20px; } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20788467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123507/" ]
To scroll to a particular element on the page, the element must have an ID : ``` <a class="scroll" href="#myElement">Link</a> <div id="myElement"></div> ``` This anchor will make the document scroll to the top of the element #myElement. Then animate it with JS : ``` $('a.scroll').click(function(){ var href = $(this).attr('href'); var dest = $(href).offset().top; $('html, body').animate({ scrollTop: dest; }, 1000); return false; }); ```
check out the scrolTo in jquery take a look at this : <http://demos.flesler.com/jquery/scrollTo/>
20,788,467
I want to go to a specific section of my website when I click on the link in the menu bar for that section of the website, so you do not have to scroll through all the content, but to have links to the different sections. I've read that you can do this with jQuery and make an animation for it so that the page can smoothly go to that section of the website. Here's the **HTML** code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="java.js"></script> <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> <title>Test Website</title> <meta name="" content=""> <script type="text/javascript"> </script> </head> <body> <header> <div id="title"> <h1 class="headertext">My Test Website</h1> </div> <div id="menubar"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> </div> </header> <div class="hide"> </div> <div id="container"> <div id="leftmenu"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> <div id="triangle"></div> </div> <div id="content"> <h1>Contentpage</h1></br> Picture slideshow </br> </br> <div class="slider"> <img id="1" src="images/car1.jpg" border="0" alt="car1"/> <img id="2" src="images/car2.jpg" border="0" alt="car2"/> <img id="3" src="images/car3.jpg" border="0" alt="car3"/> <img id="4" src="images/car4.jpg" border="0" alt="car4"/> <img id="5" src="images/car5.jpg" border="0" alt="car5"/> </div><!--slider end--> <div class="shadow"></div> <div class="borderbottom"></div> </div><!--content div--> </div> </body> </html> ``` And here is the **CSS** code: ``` *{ margin: 0 auto 0 auto; text-align: left; color: #ffffff; } body{ margin: 0; text-align: left; font-size: 13px; font-family: arial, helvetica, sens-serif; color: #ffffff; width: 1200px; height: auto; background: #f4f4f4; } header { position: fixed; width: 100%; top: 0; background: rgba(0,0,0,.8); z-index: 10; } h1{ color: black; text-align: center; } .hide { position: fixed; width: 100%; top: 0; background: rgba(255,255,255,1); z-index:5; height: 123px; } .headertext{ margin-top: 15px; text-align: center; color: white; } #title{ font-size: 20px; margin: -10px 0 30px 0; width: 100%; height: 70px; border-top: 2px solid #000000; border-bottom: 2px solid #000000; } #menubar{ margin-top: 10px; float: left; clear: both; width: 100%; height: 20px; list-style: none; border-bottom: 2px solid #010000; } #menubar ul{ list-style: none; margin-top: -15px; text-align: center; } #menubar ul li{ list-style: none; display: inline; padding-right: 80px; } #menubar ul li a{ color: #ffffff; text-decoration: none; font-size: 15px; font-weight: bold; } #menubar ul li a:hover{ border-bottom: 2px solid #ffffff; } #container{ width: 1200px; height: 1400px; } #leftmenu{ position: fixed; margin-top: 123px; margin-left: 50px; padding-top: 20px; float: left; width: 160px; height: 350px; list-style: none; background: rgba(0,0,0,0.8); color: #ffffff; border-left: 2px solid #010000; border-right: 2px solid #010000; } #leftmenu ul li{ display: block; padding-bottom: 50px; } #leftmenu ul li a{ font-weight: bold; text-decoration: none; color: #ffffff; font-size: 15px; text-align: center; } #leftmenu ul li a:hover{ border-bottom: 2px solid #ffffff; transition: opacity .5s ease-in; opacity: 1; } #triangle{ margin-top: 12px; margin-left: -1px; width: 0px; height: 0; border-top: 80px solid rgba(0,0,0,0.8); border-left: 82px solid transparent; border-right: 82px solid transparent; } #content{ text-align: left; margin-left: 100px; width: 1000px; padding-top: 150px; padding-left: 160px; color: #000000; font-weight: bold; text-align: center; font-size: 15px; } .slider{ margin-top: 20px; width: 600px; height: 400px; overflow: hidden; margin: auto; border-radius: 10px; vertical-align: middle; } .shadow{ background-image:url(../images/shadow.png); background-repeat: no-repeat; background-position: top; width: 850px; height: 144px; vertical-align: middle; margin-top: -50px; } .slider img{ width: 600px; height: 400px; display: none; } .borderbottom{ border: 6px solid rgba(0,0,0,0.8); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; width: 1000px; position: fixed; margin-top: 20px; } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20788467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123507/" ]
If you have jQuery loaded you could try like this, no plugin required just jquery will do... HTML: ``` <div id="menubar"> <ul> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> ........all the menu items------- </ul> ``` JS: ``` $('#menubar ul li a').on('click',function(event){ var $anchor = $(this); $('html, body').animate({ scrollTop: $($anchor.attr('href')).offset().top + "px" }, 1500); event.preventDefault(); }); ``` This is the working [fiddle](http://jsfiddle.net/YJwTJ/3)
check out the scrolTo in jquery take a look at this : <http://demos.flesler.com/jquery/scrollTo/>
20,788,467
I want to go to a specific section of my website when I click on the link in the menu bar for that section of the website, so you do not have to scroll through all the content, but to have links to the different sections. I've read that you can do this with jQuery and make an animation for it so that the page can smoothly go to that section of the website. Here's the **HTML** code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="java.js"></script> <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> <title>Test Website</title> <meta name="" content=""> <script type="text/javascript"> </script> </head> <body> <header> <div id="title"> <h1 class="headertext">My Test Website</h1> </div> <div id="menubar"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> </div> </header> <div class="hide"> </div> <div id="container"> <div id="leftmenu"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> <div id="triangle"></div> </div> <div id="content"> <h1>Contentpage</h1></br> Picture slideshow </br> </br> <div class="slider"> <img id="1" src="images/car1.jpg" border="0" alt="car1"/> <img id="2" src="images/car2.jpg" border="0" alt="car2"/> <img id="3" src="images/car3.jpg" border="0" alt="car3"/> <img id="4" src="images/car4.jpg" border="0" alt="car4"/> <img id="5" src="images/car5.jpg" border="0" alt="car5"/> </div><!--slider end--> <div class="shadow"></div> <div class="borderbottom"></div> </div><!--content div--> </div> </body> </html> ``` And here is the **CSS** code: ``` *{ margin: 0 auto 0 auto; text-align: left; color: #ffffff; } body{ margin: 0; text-align: left; font-size: 13px; font-family: arial, helvetica, sens-serif; color: #ffffff; width: 1200px; height: auto; background: #f4f4f4; } header { position: fixed; width: 100%; top: 0; background: rgba(0,0,0,.8); z-index: 10; } h1{ color: black; text-align: center; } .hide { position: fixed; width: 100%; top: 0; background: rgba(255,255,255,1); z-index:5; height: 123px; } .headertext{ margin-top: 15px; text-align: center; color: white; } #title{ font-size: 20px; margin: -10px 0 30px 0; width: 100%; height: 70px; border-top: 2px solid #000000; border-bottom: 2px solid #000000; } #menubar{ margin-top: 10px; float: left; clear: both; width: 100%; height: 20px; list-style: none; border-bottom: 2px solid #010000; } #menubar ul{ list-style: none; margin-top: -15px; text-align: center; } #menubar ul li{ list-style: none; display: inline; padding-right: 80px; } #menubar ul li a{ color: #ffffff; text-decoration: none; font-size: 15px; font-weight: bold; } #menubar ul li a:hover{ border-bottom: 2px solid #ffffff; } #container{ width: 1200px; height: 1400px; } #leftmenu{ position: fixed; margin-top: 123px; margin-left: 50px; padding-top: 20px; float: left; width: 160px; height: 350px; list-style: none; background: rgba(0,0,0,0.8); color: #ffffff; border-left: 2px solid #010000; border-right: 2px solid #010000; } #leftmenu ul li{ display: block; padding-bottom: 50px; } #leftmenu ul li a{ font-weight: bold; text-decoration: none; color: #ffffff; font-size: 15px; text-align: center; } #leftmenu ul li a:hover{ border-bottom: 2px solid #ffffff; transition: opacity .5s ease-in; opacity: 1; } #triangle{ margin-top: 12px; margin-left: -1px; width: 0px; height: 0; border-top: 80px solid rgba(0,0,0,0.8); border-left: 82px solid transparent; border-right: 82px solid transparent; } #content{ text-align: left; margin-left: 100px; width: 1000px; padding-top: 150px; padding-left: 160px; color: #000000; font-weight: bold; text-align: center; font-size: 15px; } .slider{ margin-top: 20px; width: 600px; height: 400px; overflow: hidden; margin: auto; border-radius: 10px; vertical-align: middle; } .shadow{ background-image:url(../images/shadow.png); background-repeat: no-repeat; background-position: top; width: 850px; height: 144px; vertical-align: middle; margin-top: -50px; } .slider img{ width: 600px; height: 400px; display: none; } .borderbottom{ border: 6px solid rgba(0,0,0,0.8); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; width: 1000px; position: fixed; margin-top: 20px; } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20788467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123507/" ]
If you have jQuery loaded you could try like this, no plugin required just jquery will do... HTML: ``` <div id="menubar"> <ul> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> ........all the menu items------- </ul> ``` JS: ``` $('#menubar ul li a').on('click',function(event){ var $anchor = $(this); $('html, body').animate({ scrollTop: $($anchor.attr('href')).offset().top + "px" }, 1500); event.preventDefault(); }); ``` This is the working [fiddle](http://jsfiddle.net/YJwTJ/3)
The standard way is to use named anchors: ``` <a href="index.html#section">section</a> ``` This link will navigate to `index.html` and the browser will scroll to the element with ID or NAME `section` if it exists, f.ex: ``` <section id="section"></section> ``` It also works for the `name` attribute, but it’s rarely used these days: ``` <section name="section"></section> ``` If you want jQuery to animate this behaviour, it’s a good idea to start with the standard implementation above, then add some enhanced functionality, f.ex: ``` $('#menubar').on('click', 'a', function(e) { e.preventDefault(); // prevents default scrolling var y = $(this.hash).offset().top; // grabs the #id element offset location $('html,body').animate({scrollTop: y}); // animate the scroll }); ```
20,788,467
I want to go to a specific section of my website when I click on the link in the menu bar for that section of the website, so you do not have to scroll through all the content, but to have links to the different sections. I've read that you can do this with jQuery and make an animation for it so that the page can smoothly go to that section of the website. Here's the **HTML** code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="java.js"></script> <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> <title>Test Website</title> <meta name="" content=""> <script type="text/javascript"> </script> </head> <body> <header> <div id="title"> <h1 class="headertext">My Test Website</h1> </div> <div id="menubar"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> </div> </header> <div class="hide"> </div> <div id="container"> <div id="leftmenu"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> <div id="triangle"></div> </div> <div id="content"> <h1>Contentpage</h1></br> Picture slideshow </br> </br> <div class="slider"> <img id="1" src="images/car1.jpg" border="0" alt="car1"/> <img id="2" src="images/car2.jpg" border="0" alt="car2"/> <img id="3" src="images/car3.jpg" border="0" alt="car3"/> <img id="4" src="images/car4.jpg" border="0" alt="car4"/> <img id="5" src="images/car5.jpg" border="0" alt="car5"/> </div><!--slider end--> <div class="shadow"></div> <div class="borderbottom"></div> </div><!--content div--> </div> </body> </html> ``` And here is the **CSS** code: ``` *{ margin: 0 auto 0 auto; text-align: left; color: #ffffff; } body{ margin: 0; text-align: left; font-size: 13px; font-family: arial, helvetica, sens-serif; color: #ffffff; width: 1200px; height: auto; background: #f4f4f4; } header { position: fixed; width: 100%; top: 0; background: rgba(0,0,0,.8); z-index: 10; } h1{ color: black; text-align: center; } .hide { position: fixed; width: 100%; top: 0; background: rgba(255,255,255,1); z-index:5; height: 123px; } .headertext{ margin-top: 15px; text-align: center; color: white; } #title{ font-size: 20px; margin: -10px 0 30px 0; width: 100%; height: 70px; border-top: 2px solid #000000; border-bottom: 2px solid #000000; } #menubar{ margin-top: 10px; float: left; clear: both; width: 100%; height: 20px; list-style: none; border-bottom: 2px solid #010000; } #menubar ul{ list-style: none; margin-top: -15px; text-align: center; } #menubar ul li{ list-style: none; display: inline; padding-right: 80px; } #menubar ul li a{ color: #ffffff; text-decoration: none; font-size: 15px; font-weight: bold; } #menubar ul li a:hover{ border-bottom: 2px solid #ffffff; } #container{ width: 1200px; height: 1400px; } #leftmenu{ position: fixed; margin-top: 123px; margin-left: 50px; padding-top: 20px; float: left; width: 160px; height: 350px; list-style: none; background: rgba(0,0,0,0.8); color: #ffffff; border-left: 2px solid #010000; border-right: 2px solid #010000; } #leftmenu ul li{ display: block; padding-bottom: 50px; } #leftmenu ul li a{ font-weight: bold; text-decoration: none; color: #ffffff; font-size: 15px; text-align: center; } #leftmenu ul li a:hover{ border-bottom: 2px solid #ffffff; transition: opacity .5s ease-in; opacity: 1; } #triangle{ margin-top: 12px; margin-left: -1px; width: 0px; height: 0; border-top: 80px solid rgba(0,0,0,0.8); border-left: 82px solid transparent; border-right: 82px solid transparent; } #content{ text-align: left; margin-left: 100px; width: 1000px; padding-top: 150px; padding-left: 160px; color: #000000; font-weight: bold; text-align: center; font-size: 15px; } .slider{ margin-top: 20px; width: 600px; height: 400px; overflow: hidden; margin: auto; border-radius: 10px; vertical-align: middle; } .shadow{ background-image:url(../images/shadow.png); background-repeat: no-repeat; background-position: top; width: 850px; height: 144px; vertical-align: middle; margin-top: -50px; } .slider img{ width: 600px; height: 400px; display: none; } .borderbottom{ border: 6px solid rgba(0,0,0,0.8); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; width: 1000px; position: fixed; margin-top: 20px; } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20788467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123507/" ]
The standard way is to use named anchors: ``` <a href="index.html#section">section</a> ``` This link will navigate to `index.html` and the browser will scroll to the element with ID or NAME `section` if it exists, f.ex: ``` <section id="section"></section> ``` It also works for the `name` attribute, but it’s rarely used these days: ``` <section name="section"></section> ``` If you want jQuery to animate this behaviour, it’s a good idea to start with the standard implementation above, then add some enhanced functionality, f.ex: ``` $('#menubar').on('click', 'a', function(e) { e.preventDefault(); // prevents default scrolling var y = $(this.hash).offset().top; // grabs the #id element offset location $('html,body').animate({scrollTop: y}); // animate the scroll }); ```
check out the scrolTo in jquery take a look at this : <http://demos.flesler.com/jquery/scrollTo/>
58,610,203
I try to limit access to a REST API using a JWT token using the `validate-jwt` policy. Never did that before. Here's my inbound policy (taken from the point **Simple token validation** [here](https://learn.microsoft.com/en-us/azure/api-management/api-management-access-restriction-policies?redirectedfrom=MSDN#ValidateJWT)): ``` <validate-jwt header-name="Authorization" require-scheme="Bearer"> <issuer-signing-keys> <key>{{jwt-signing-key}}</key> </issuer-signing-keys> <audiences> <audience>CustomerNameNotDns</audience> </audiences> <issuers> <issuer>MyCompanyNameNotDns</issuer> </issuers> </validate-jwt> ``` Using [this generator](http://jwtbuilder.jamiekurtz.com/) I created a claim (I'm not sure whether I understood issuer and audience correctly): ``` { "iss": "MyCompanyNameNotDns", "iat": 1572360380, "exp": 2361278784, "aud": "CustomerNameNotDns", "sub": "Auth" } ``` In the section **Signed JSON Web Token** I picked **Generate 64-bit key** from the combo box. The key that was generated I put in the place of **{{jwt-signing-key}}**. Now, I'm trying to call the API using Postman. I add an "Authorization" header, and as the value I put "Bearer {{ JWT created by the [linked generator](http://jwtbuilder.jamiekurtz.com/) }}". I get 401, JWT not present. What am I doing wrong?
2019/10/29
[ "https://Stackoverflow.com/questions/58610203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693915/" ]
According to my research, If you use HS256 signing algorithms, the key must be provided inline within the policy in the base64 encoded form. In other words, we must encode the key as base64 string. For more details, please refer to the [document](https://learn.microsoft.com/en-us/azure/api-management/api-management-access-restriction-policies#ValidateJWT) [![enter image description here](https://i.stack.imgur.com/ySPGw.png)](https://i.stack.imgur.com/ySPGw.png) My test steps are as below 1. Create Jwt token [![enter image description here](https://i.stack.imgur.com/6W6Vr.png)](https://i.stack.imgur.com/6W6Vr.png) [![enter image description here](https://i.stack.imgur.com/i1etp.png)](https://i.stack.imgur.com/i1etp.png) 2. Test a. If I directly provide the key in the policy, I get the 401 error [![enter image description here](https://i.stack.imgur.com/xebIY.png)](https://i.stack.imgur.com/xebIY.png) [![enter image description here](https://i.stack.imgur.com/6adLp.png)](https://i.stack.imgur.com/6adLp.png) b. If I encode the key as base64 string in the policy, I can call the api [![enter image description here](https://i.stack.imgur.com/3o9AB.png)](https://i.stack.imgur.com/3o9AB.png) [![enter image description here](https://i.stack.imgur.com/h5fcM.png)](https://i.stack.imgur.com/h5fcM.png)
[Jim Xu's answer](https://stackoverflow.com/a/58620325/1693915) to encode the key as base64 string in the policy allowed me to get this far :-) I set the **Ocp-Apim-Trace** parameter to true in order to debug it more closely. I followed the link provided in the response under **ocp-apim-trace-location**, and in the "on error" section I found the following message: ``` JWT Validation Failed: IDX10225: Lifetime validation failed. The token is missing an Expiration Time. Tokentype: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'.. ``` Which is funny, because I have set the Expiration Time... to 2099. I changed it to a month from now and it worked just fine.
70,102,930
I must to convert the 4 column to upper case with only one sed command. ``` user,gender,age,native_lang,other_lang 0,M,19,finnish,english swedish german 1,M,30,urdu,english 2,F,26,finnish,english swedish german 3,M,20,finnish,english french swedish 4,F,20,finnish,english swedish ``` This it's my best movement but change all columns. ``` sed -e 's/\(.*\)/\U\1/' ``` I really want understand the command, but I really lose myself why use" \ " or how to read it.
2021/11/24
[ "https://Stackoverflow.com/questions/70102930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16356062/" ]
You can use ```sh sed 's/^\(\([^,]*,\)\{3\}\)\([^,]*\)/\1\U\3/' # POSIX BRE sed -E 's/^(([^,]*,){3})([^,]*)/\1\U\3/' # POSIX ERE ``` See [an online demo](https://ideone.com/dGppHs): ```sh s='user,gender,age,native_lang,other_lang 0,M,19,finnish,english swedish german 1,M,30,urdu,english 2,F,26,finnish,english swedish german 3,M,20,finnish,english french swedish 4,F,20,finnish,english swedish ' sed 's/^\(\([^,]*,\)\{3\}\)\([^,]*\)/\1\U\3/' <<< "$s" ``` Output: ``` user,gender,age,NATIVE_LANG,other_lang 0,M,19,FINNISH,english swedish german 1,M,30,URDU,english 2,F,26,FINNISH,english swedish german 3,M,20,FINNISH,english french swedish 4,F,20,FINNISH,english swedish ``` *Details*: * `^` - start of string * `(([^,]*,){3})` - Group 1: three repetitions of any zero or more chars other than a comma and then a comma * `([^,]*)` - Group 3: zero or more chars other than a comma.
This might work for you (GNU sed): ``` sed 's/[^,]*/\U&/4' file ``` Uppercase the fourth set of non-commas. --- If not the headers, use: ``` sed '1!s/[^,]*/\U&/4' file ```
25,709,429
In my Qt app I'm trying to pass a large integer value from my C++ code to QML. In my C++ I have a Q\_PROPERTY(int ...), but apparently int sometimes isn't enough for my app and I get an overflow. Can I use long types or unsigned types in QML? How about dynamically sized int types? From the QML documentation all I could find was int with a range of "around -2000000000 to around 2000000000". Any help is appreciated! =)
2014/09/07
[ "https://Stackoverflow.com/questions/25709429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246924/" ]
I find your question interesting because it looks trivial initially, and though raises many points in the way to get an answer. I assume that you want to pass a 64 bit integer from C++ to QML. I explain later why. QML basic type for a 64 bit integer =================================== There is no 64 bit integral [QML basic type](http://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html), therefore you cannot expect your C++ value to be converted and stored in such a non-existing QML type property. As stated in the documentation, Qt modules can extend the list of available types. We can even think of a future where we could add our own types, but not nowadays : > > Currently only QML modules which are provided by Qt may provide their > own basic types, however this may change in future releases of Qt QML. > > > One may think that having their application compiled in a 64 bit platform should do the job, but it won't change a thing. There is [a lot of answers](https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be) about this question. To make it obvious, here is a comparison of the results using a 32 bit and a 64 bit compiler on the same computer : On my computer (64 bit processor : Core i7) with a 64 bit system (Windows 7 64 bit) using a 32 bit compiler (mingw53), I've got ``` 4 = sizeof(int) = sizeof(long) = sizeof(int*) = sizeof(size_t) ``` I've put `size_t` to make it clear it cannot be used to denote a file size, it's not [its purpose](http://en.cppreference.com/w/cpp/types/size_t). With a 64 bit compiler (msvc2017, x64), on the same system : ``` 4 = sizeof(int) = sizeof(long) 8 = sizeof(int*) = sizeof(size_t) ``` Using a 64 bit compiler did not change `sizeof(int)`, so thinking of an `int` to be the same size of an `int*` is obviously wrong. In your case, it appears that you want to store a file size and that 32 bits weren't enough to represent the size of a file. So if we cannot rely on an `int` to do it, what type should be used ? File size type size =================== For now, I assumed that a 64 bit integer should be enough and the right way to store a file size. But is it true ? According to cplusplus.com, the type for this is [std::streampos](http://www.cplusplus.com/doc/tutorial/files/). If you look for details on cppreference.com you find that `std::streampos` is a specialization of `std::fpos` and a description of its *typical* implementation : > > Specializations of the class template `std::fpos` identify absolute > positions in a stream or in a file. Each object of type `fpos` holds the > byte position in the stream (typically as a private member of type > `std::streamoff`) and the current shift state, a value of type `State` > (typically `std::mbstate_t`). > > > And the actual type of a [std::streamoff](http://en.cppreference.com/w/cpp/io/streamoff) is *probably* a 64 bit signed integer : > > The type `std::streamoff` is a signed integral type of sufficient size > to represent the maximum possible file size supported by the operating > system. Typically, this is a `typedef` to `long long`. > > > In addition, in the same page, you can read that : > > a value of type `std::fpos` is implicitly convertible to `std::streamoff` (the conversion result is the offset from the beginning > of the file). > > > a value of type `std::fpos` is constructible from a value of type `std::streamoff` > > > Let's look at what we have, again depending on the 32 or 64 bit target platform. Using a 32 bit compiler I've got ``` 8 = sizeof(long long) = sizeof(std::streamoff) 16 = sizeof(std::streampos) ``` It shows that, obviously, more information than is currently necessary to know a file size is stored in a `std::streampos`. With a 64 bit compiler, on the same system : ``` 8 = sizeof(long long) = sizeof(std::streamoff) 24 = sizeof(std::streampos) ``` Value of `sizeof(std::streamoff)` did not change. It may have. In both cases, it had to be large enough in order to store a file size. You may want to use `std::streamoff` to store the file size on the C++ side. You cannot rely on it being 64 bit. Let's assume that one wants to take the risk of making the assumption that it is 64 bit, as shown in these examples : still remains the problem of passing it to the QML as a basic type and, maybe, to the Javascript engine. Nevertheless using a near-64 bit in QML ======================================= If you just need to display the size as a number in bytes, you'll need a text representation in the UI. You can stick with this idea, use a string, and forget about passing an integral value. If you need to do arithmetic on the QML side, using Javascript, you'll probably hit the [53 bit barrier](http://www.ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) of the Javascript `Number` unless you do not use the core language to do the arithmetic. Here, if you make the assumption that a file size cannot be greater than 2^53, then using a `double` could work. You have to know how `double` type is handled on your target platforms as stated in [this answer](https://stackoverflow.com/a/1848761/4706859), and if you're lucky enough, it will have the same ability to store with no loss a 53 bit integral value. You can manipulate it directly in Javascript after, and this is guaranteed to work, at least in ECMA 262 version 8. So is it OK, now ? Can we use doubles for any file size lower than 2^53 ? Well… Qt does not necessarily implement the latest specification of ECMAScript and uses [several implementations](http://doc.qt.io/qt-5/topics-scripting.html). In Webviews, it does use a [rather common implementation](https://doc.qt.io/qt-5/qtwebengine-3rdparty-v8-javascript-engine.html). In QML, it uses its own, undocumented, built-in Javascript engine, based on ECMA 262 version 5. This version of ECMA does not explicitely mention a value for which all smaller integral values are guaranteed to be stored in a `Number`. That does not mean it won't work. Even if it had been mentionned, the implementation is only *based on* the specification and does not claim for compliance. You may find yourself in the unlucky position to have it working for a long time, and then discover that it does not anymore, in a newer release of Qt. It looks like a lot of assumptions have to be made. All of them may be and may remain true during the whole life of the software based on it. So it is a matter of dealing with a risk. Is there a way to lower that risk for one that would want to? Not risking a bit of correctness for a few bits =============================================== I see two main paths : * not bothering with all this stuff at all. Using a double for instance, and doing whatever you want as long as it seems to work. If it's not working for cases that do not happen, why trying to handle them ? When it does not work, you'll deal with it. * trying to be rigorous, and to do it the more robust way. As far as I understand, a solution of this kind could be to keep all the file size arithmetics on the C++ side and passing only safe values to the QML side. For instance boolean values for testing and strings for displaying the value of the sizes (total size, remaining size, …). You do not need to worry about how many bits there is in anything. An hint : the [bittorent protocol](http://www.bittorrent.org/beps/bep_0003.html) uses strings to encode sizes. The problem not limited to QML properties ========================================= The same problem may arise if you use Javascript to manipulate integral values with a `Number` instance, and use it as argument to an `int` parameter of a QML signal. For instance, declaring a signal like this : ``` signal sizeChanged(var newSize) // Number class (maybe 53 bit) integral value possible ``` may handle cases that the following certainly cannot : ``` signal sizeChanged(int newSize) // 32 bit int limitation ``` An example of failure is to pass `(new Date()).getTime()`. It is the same limitation that is not restricted to C++ property interactions with QML.
unsigned int and signed int are [directly](http://qt-project.org/doc/qt-5/qtqml-cppintegration-data.html) convertable to int in QML. If you are on a 32bit system, the unsigned int would get you from 0 to 4,294,967,295. This however, conflicts with the documentation, which like you state, mentions a reduced range of around -2 billion to around +2 billion [here](http://qt-project.org/doc/qt-5/qml-int.html). There is no further information about support for long, or for any other type of larger integer values. You could consider this question for the [Qt Mailing list](http://lists.qt-project.org/mailman/listinfo/interest) or [Qt forums](http://qt-project.org/forums/viewforum/10/). In the meantime, you may want to ask yourself, why you are passing such large integers around and if your application/design necessitates such a requirement.
12,964,240
So I've recently setup a LEMP server and have managed to work may way through some of the configurations. I'm now to the point where I can begin writing php scripts and building basic pages. Looking at the [php5-fpm wiki](http://php-fpm.org/wiki/Main_Page) there aren't any pages discussing any changes I should expect as far as php scripts and such are concerned, only installation/configuration settings. Is everything beyond the installation/configurations steps business as usual? From the point of view of a php developer what changes should I expect/make? How can best take advantage of the fpm version (in the php code, not module/system configurations)? I'm focused on comparing well-written php in both cases.
2012/10/18
[ "https://Stackoverflow.com/questions/12964240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558546/" ]
When I made the switch myself, I got to know a few perks about this kind of setup, such as APC file upload progress does not work out of the box (and you're better off using something else, such as nginx-progress-upload and/or JS File API); Some header names might have changed (prepending HTTP\_); and a new and very useful function called `fastcgi_finish_request`. For more information, though, look around the [PHP-FPM Manual](http://php.net/manual/en/install.fpm.php).
Only major gotcha I can think of is that some functions in the `pcntl` extensions, such as `pcntl_fork`, are not supported when running under FPM. (However, they're not supported under `mod_php` either, so this shouldn't come as too much of a surprise.)
57,827,842
I have around 10k `.bytes` files in my directory and I want to use count vectorizer to get n\_gram counts (i.e fit on train and transform on test set). In those 10k files I have 8k files as train and 2k as test. ``` files = ['bfiles/GhHS0zL9cgNXFK6j1dIJ.bytes', 'bfiles/8qCPkhNr1KJaGtZ35pBc.bytes', 'bfiles/bLGq2tnA8CuxsF4Py9RO.bytes', 'bfiles/C0uidNjwV8lrPgzt1JSG.bytes', 'bfiles/IHiArX1xcBZgv69o4s0a.bytes', ............................... ...............................] print(open(files[0]).read()) 'A4 AC 4A 00 AC 4F 00 00 51 EC 48 00 57 7F 45 00 2D 4B 42 45 E9 77 51 4D 89 1D 19 40 30 01 89 45 E7 D9 F6 47 E7 59 75 49 1F ....' ``` I can't do something like below and pass everything to `CountVectorizer`. ``` file_content = [] for file in file: file_content.append(open(file).read()) ``` I can't append each file text to a big nested lists of files and then use `CountVectorizer` because the all combined text file size exceeds 150gb. I don't have resources to do that because `CountVectorizer` use huge amount of memory. I need a more efficient way of solving this, Is there some other way I can achieve what I want without loading everything into memory at once. Any help is much appreciated. All I could achieve was read one file and then use `CountVectorizer` but I don't know how to achieve what I'm looking for. ``` cv = CountVectorizer(ngram_range=(1, 4)) temp = cv.fit_transform([open(files[0]).read()]) temp <1x451500 sparse matrix of type '<class 'numpy.int64'>' with 335961 stored elements in Compressed Sparse Row format> ```
2019/09/06
[ "https://Stackoverflow.com/questions/57827842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11816060/" ]
You can build a solution using the following flow: 1) Loop through you files and create a set of all tokens in your files. In the example below this is done using Counter, but you can use python sets to achieve the same result. The bonus here is that Counter will also give you the total number of occurrences of each term. 2) Fit CountVectorizer with the set/list of tokens. You can instantiate CountVectorizer with ngram\_range=(1, 4). Below this is avoided in order to limit the number of features in df\_new\_data. 3) Transform new data as usual. The example below works on small data. I hope you can adapt the code to suit your needs. ``` import glob import pandas as pd import numpy as np from collections import Counter from sklearn.feature_extraction.text import CountVectorizer # Create a list of file names pattern = 'C:\\Bytes\\*.csv' csv_files = glob.glob(pattern) # Instantiate Counter and loop through the files chunk by chunk # to create a dictionary of all tokens and their number of occurrence counter = Counter() c_size = 1000 for file in csv_files: for chunk in pd.read_csv(file, chunksize=c_size, index_col=0, header=None): counter.update(chunk[1]) # Fit the CountVectorizer to the counter keys vectorizer = CountVectorizer(lowercase=False) vectorizer.fit(list(counter.keys())) # Loop through your files chunk by chunk and accummulate the counts counts = np.zeros((1, len(vectorizer.get_feature_names()))) for file in csv_files: for chunk in pd.read_csv(file, chunksize=c_size, index_col=0, header=None): new_counts = vectorizer.transform(chunk[1]) counts += new_counts.A.sum(axis=0) # Generate a data frame with the total counts df_new_data = pd.DataFrame(counts, columns=vectorizer.get_feature_names()) df_new_data Out[266]: 00 01 0A 0B 10 11 1A 1B A0 A1 \ 0 258.0 228.0 286.0 251.0 235.0 273.0 259.0 249.0 232.0 233.0 AA AB B0 B1 BA BB 0 248.0 227.0 251.0 254.0 255.0 261.0 ``` Code for the generation of the data: ``` import numpy as np import pandas as pd def gen_data(n): numbers = list('01') letters = list('AB') numlet = numbers + letters x = np.random.choice(numlet, size=n) y = np.random.choice(numlet, size=n) df = pd.DataFrame({'X': x, 'Y': y}) return df.sum(axis=1) n = 2000 df_1 = gen_data(n) df_2 = gen_data(n) df_1.to_csv('C:\\Bytes\\df_1.csv') df_2.to_csv('C:\\Bytes\\df_2.csv') df_1.head() Out[218]: 0 10 1 01 2 A1 3 AB 4 1A dtype: object ```
The sklearn documentation states that `.fit_transform` could take an iterable which yields either str, unicode or file objects. So you can create a generator which yield your files one by one and passes it to the fit method. You can create a generator by passing the path to your files as shown below: ``` def gen(path): A = os.listdir(path) for i in A: yield (i) ``` Now you can create your generator and pass it on to CountVectorizer as follows: ``` q = gen("/path/to/your/file/") from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(ngram_range=(1, 4)) cv.fit_transform(q) ```
57,827,842
I have around 10k `.bytes` files in my directory and I want to use count vectorizer to get n\_gram counts (i.e fit on train and transform on test set). In those 10k files I have 8k files as train and 2k as test. ``` files = ['bfiles/GhHS0zL9cgNXFK6j1dIJ.bytes', 'bfiles/8qCPkhNr1KJaGtZ35pBc.bytes', 'bfiles/bLGq2tnA8CuxsF4Py9RO.bytes', 'bfiles/C0uidNjwV8lrPgzt1JSG.bytes', 'bfiles/IHiArX1xcBZgv69o4s0a.bytes', ............................... ...............................] print(open(files[0]).read()) 'A4 AC 4A 00 AC 4F 00 00 51 EC 48 00 57 7F 45 00 2D 4B 42 45 E9 77 51 4D 89 1D 19 40 30 01 89 45 E7 D9 F6 47 E7 59 75 49 1F ....' ``` I can't do something like below and pass everything to `CountVectorizer`. ``` file_content = [] for file in file: file_content.append(open(file).read()) ``` I can't append each file text to a big nested lists of files and then use `CountVectorizer` because the all combined text file size exceeds 150gb. I don't have resources to do that because `CountVectorizer` use huge amount of memory. I need a more efficient way of solving this, Is there some other way I can achieve what I want without loading everything into memory at once. Any help is much appreciated. All I could achieve was read one file and then use `CountVectorizer` but I don't know how to achieve what I'm looking for. ``` cv = CountVectorizer(ngram_range=(1, 4)) temp = cv.fit_transform([open(files[0]).read()]) temp <1x451500 sparse matrix of type '<class 'numpy.int64'>' with 335961 stored elements in Compressed Sparse Row format> ```
2019/09/06
[ "https://Stackoverflow.com/questions/57827842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11816060/" ]
You can build a solution using the following flow: 1) Loop through you files and create a set of all tokens in your files. In the example below this is done using Counter, but you can use python sets to achieve the same result. The bonus here is that Counter will also give you the total number of occurrences of each term. 2) Fit CountVectorizer with the set/list of tokens. You can instantiate CountVectorizer with ngram\_range=(1, 4). Below this is avoided in order to limit the number of features in df\_new\_data. 3) Transform new data as usual. The example below works on small data. I hope you can adapt the code to suit your needs. ``` import glob import pandas as pd import numpy as np from collections import Counter from sklearn.feature_extraction.text import CountVectorizer # Create a list of file names pattern = 'C:\\Bytes\\*.csv' csv_files = glob.glob(pattern) # Instantiate Counter and loop through the files chunk by chunk # to create a dictionary of all tokens and their number of occurrence counter = Counter() c_size = 1000 for file in csv_files: for chunk in pd.read_csv(file, chunksize=c_size, index_col=0, header=None): counter.update(chunk[1]) # Fit the CountVectorizer to the counter keys vectorizer = CountVectorizer(lowercase=False) vectorizer.fit(list(counter.keys())) # Loop through your files chunk by chunk and accummulate the counts counts = np.zeros((1, len(vectorizer.get_feature_names()))) for file in csv_files: for chunk in pd.read_csv(file, chunksize=c_size, index_col=0, header=None): new_counts = vectorizer.transform(chunk[1]) counts += new_counts.A.sum(axis=0) # Generate a data frame with the total counts df_new_data = pd.DataFrame(counts, columns=vectorizer.get_feature_names()) df_new_data Out[266]: 00 01 0A 0B 10 11 1A 1B A0 A1 \ 0 258.0 228.0 286.0 251.0 235.0 273.0 259.0 249.0 232.0 233.0 AA AB B0 B1 BA BB 0 248.0 227.0 251.0 254.0 255.0 261.0 ``` Code for the generation of the data: ``` import numpy as np import pandas as pd def gen_data(n): numbers = list('01') letters = list('AB') numlet = numbers + letters x = np.random.choice(numlet, size=n) y = np.random.choice(numlet, size=n) df = pd.DataFrame({'X': x, 'Y': y}) return df.sum(axis=1) n = 2000 df_1 = gen_data(n) df_2 = gen_data(n) df_1.to_csv('C:\\Bytes\\df_1.csv') df_2.to_csv('C:\\Bytes\\df_2.csv') df_1.head() Out[218]: 0 10 1 01 2 A1 3 AB 4 1A dtype: object ```
By using a generator instead of list, your code won't store the value of your files into your memory. Instead, it will yield a value and let forget it, then yields the next, and so on. Here, I'll use your code and do a simple tweak to change list into a generator. You could just use `()` instead of `[]`. ``` cv = CountVectorizer(ngram_range=(1, 4)) temp = cv.fit_transform((open(file).read() for file in files)) ```
1,462,272
$x^2-(2+i)x+(-1+7i)=0$ I tried to solve it and I got stuck here: $x=(2+i)±\sqrt{\frac{7-24i}{2}}$
2015/10/03
[ "https://math.stackexchange.com/questions/1462272", "https://math.stackexchange.com", "https://math.stackexchange.com/users/276466/" ]
Firstly, you correctly found the discriminant: $$D = B^2 - 4AC = [-(2+i)]^2-4(-1+7i) = 7 - 24i.$$ Then: $$x\_{1,2} = \frac{-B\pm \sqrt{D}}{2A}=\frac{2+i\pm\sqrt{7-24i}}{2}.\tag{1}$$ But: $$\sqrt{7-24i}=\pm(4-3i).$$ Why? Let $\sqrt{7-24i} = z\implies z^2 = 7-24i$. If we let $z = a+bi \implies a^2-b^2 +2ab i = 7-24i $. Thus: $$\left\{ \begin{array}{l} a^2 - b^2 = 7\\ ab = -12 \end{array} \right. $$ Solving the above system in Reals, we get 2 pairs of solutions: $(a,b) = (4,-3)$ and $(a,b) = (-4,3)$. Both $z\_1 = 4-3i$ and $z\_2 = -4+3i$ satisfy the equation $z^2 = 7-24i$. No matter the choice we make for $\sqrt{27-4i}$ (either $4-3i$ or $-4+3i$), the solutions given by the quadratic formula will be the same, due to the "$\pm$ sign" in the numerator. Apply this to $(1)$ and you will get the result.
HINT ---- Write $7 - 24\iota $ in the $r e^{\iota \theta}$ form, where $r = \sqrt{7^2 + 24^2}$ and $ \tan{\theta} = -\frac{24}{7} $. Note, $\theta$ will be in 4th quadrant.