Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
20,901,966
I have got a map with markers as below. I want to show the div "popup" close to the particular img I clicked on (cursor position). The markers are loaded by an ajax call. JQuery (JS): ``` $( "img").on('click', function(event) { var div = $("#popup"); div.css( { display:"absolute", top:event.pageY, left: event.pageX}); return false; }); ``` HTML: ``` <img class="leaflet-tile leaflet-tile-loaded" style="width: 256px; height: 256px; left: 483px; top: -188px;" src="http://a.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/10/540/357.png"></img> <img class="leaflet-tile leaflet-tile-loaded" style="width: 256px; height: 256px; left: 739px; top: -188px;" src="http://b.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/10/541/357.png"></img> <img class="leaflet-tile leaflet-tile-loaded" style="width: 256px; height: 256px; left: 227px; top: 68px;" src="http://a.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/10/539/358.png"> </img> <div id="popup">showme</div> ```
2014/01/03
[ "https://Stackoverflow.com/questions/20901966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69834/" ]
Apparently you just used the CSS property "display" instead of "position" in your JS. Here's a working fiddle: <http://jsfiddle.net/T32ZV/> And here's the working code: ``` $( "img").on('click', function(event) { var div = $("#popup"); div.css({ position:"absolute", top:event.pageY, left: event.pageX }); return false; }); ```
hide the $('#popup') first and your css property was wrong, `position` instead of `display` ``` <div id="popup" style="display:none">showme</div> $("img").on('click', function(event) { var div = $("#popup"); div.css( { position:"absolute", top:event.pageY, left: event.pageX }).show(); return false; }); ```
48,257,736
I am using Vim80 on Windows 10. Using Netrw command , by default it will open up my `%HOME%` path. I want to open specific disk drive on my computer like `F:` using netrw. I have searched through similar questions on Stack Overflow and found answers like using `:Ex F:` or `:cd F:\` but it does not change the default directory. What is the netrw vim command that will enable me to change the drive I am working on?
2018/01/15
[ "https://Stackoverflow.com/questions/48257736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9116264/" ]
i was able to fix the issue , it was due to missing no\_proxy which when i added for my ipaddress it started working.
You need to declare the registry as an [insecure registry](https://docs.docker.com/registry/insecure/) by editing the deamon.json file. By default, when connecting to a registry on localhost there is no need to have TLS certificates configured. However, when you try to connect to remote registry and it is insecure, you need to add an insecure registry line for the remote registry.
376,536
The title basically is the question. Well, I know why Apple added chip to their cables and changed the connector for good measure. That's of course not a corporate greed but a loving care about their customers... and making sure it would cost them a fortune to leave. But nowhere in the USB specification it requires anything but the wire. Of course high speed introduces strict limits to electrical characteristics etc. But still... it is JUST A WIRE! Billions of cables in the world work just fine without anything else. However when it comes to magnetic cables, which are basically regular cables with connector attached to wires by some pins and magnets, they all have chips inside. The end result is that it is practically impossible to find cable which works with all USB devices in home. Each cable comes with a list of incompatible devices almost as long as compatible. Fast charging that used to be enabled by simple pull-up in micro connector now requires "improved smart chip" and does not work with half of the mobile phones. The question is - why? Is there any reason I don't see? Unlike Apple products these cables are dirt-cheap, and if there is no increased cost then there should not be a reason for manufacturers to make all this mess out of perfectly simple and extremely useful idea. Update: Regarding suggestions to tear down some cable - yes, tearing down and analyzing them with DSO may provide an answer to compatibility problems. But the whole point of posting a question here was the hope that there could be an electrical engineer who *knows* an answer. Also, according to (very limited) marketing info, some manufacturers include identification chip into **plug** portion, designed to trick Apple devices into thinking they connected to authentic cable and avoid annoying pop-ups. Legal issues aside, this has nothing to do with the question, since those cables still have more chips in the connector portion. Funny thing though, is that most devices on "incompatible" lists are Android micro-B / type-C devices. Anyway, here are the theories presented so far: 1. By @pjc50: To simulate the **order of connection** required by USB spec and guaranteed mechanically in regular cables. This is top contender at the moment, because it is applicable to all 3 types of cables on the market (non-reversible, electronically reversible and mechanically reversible). 2. By @Ali\_Chen: To provide additional **ESD protection** highly important here due to exposed pins. This is another strong argument for having chips in the cable, also applicable to all types of cables. 3. By @dim: To avoid **dangling pins** in dual-row models, which might affect high-speed transmission. Not sure if this is critical for USB 2.0 speeds though. 4. By @dim: To **reverse outputs** in single-row models. Yes, this certainly is the case. Note that many cables reverse power only, leaving you without data. Also note, that simple reversing *should not* result in selective compatibility issues. 5. By @tom: To **control the LED**. Now, this is certainly a reason to have some circuitry inside. But if the price is loss of primary function with half of the devices then this is dubious reason, to say the least. Update 2: Is seems there is no one here with insider knowledge of what is really going on in those connectors. So, I am willing to accept @pjc50 and @agent-l suggestions that those chips facilitate an **order of connection** required by USB specification, as something that is *supposed* to be inside from engineering point of view. At the same time, considering how cheap those cables are, I'd like to point out @ali-chen suggestion that they are simple TVS as something that is *actually* there. As a side note, very interesting idea came out of @ali-chen comments - that there are *more reasons to have chips inside plugs* than inside cables. I know that iPhone plugs have chips in them to simulate genuine Apple cable. But since those plugs expose USB interface pins to all the ESD around, having TVS in all plugs regardless of connector type strikes me as another *must have*. Also for electrically-reversible cables the simplest solution to swap power lines would be to put diode bridge in the plug, instead of trying to somehow guess the insertion direction and manage power in the connector. So, until someone tears down actual cable and tells us the truth I propose to consider this question answered.
2018/05/26
[ "https://electronics.stackexchange.com/questions/376536", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/187920/" ]
It is usually very difficult to short out a regular USB cable. Both male and female connectors have covers and recessed pins. This is not the case for magnetic connectors so they will require a microcontroller, or at least an IC, to determine whether a connection has been made and therefore whether it is safe to deliver power and data. They also appear to have fewer pins than a regular connector, so I assume some data conversion is required at either end.
Disclaimer: This answer is mostly a guess The device you link to in the comments has a built in LED in the connector, which illuminates when the device is attached and charging. As such it will require some form of circuitry to detect device presence and illuminate the LED. Having said that, the only picture you provide a link to is a cartoon graphic showing the mystical ICs. Who knows what if anything is actually in the cable, and what if anything it does. Without a proper tear down and photos of the guts of a real cable, it's impossible to answer.
376,536
The title basically is the question. Well, I know why Apple added chip to their cables and changed the connector for good measure. That's of course not a corporate greed but a loving care about their customers... and making sure it would cost them a fortune to leave. But nowhere in the USB specification it requires anything but the wire. Of course high speed introduces strict limits to electrical characteristics etc. But still... it is JUST A WIRE! Billions of cables in the world work just fine without anything else. However when it comes to magnetic cables, which are basically regular cables with connector attached to wires by some pins and magnets, they all have chips inside. The end result is that it is practically impossible to find cable which works with all USB devices in home. Each cable comes with a list of incompatible devices almost as long as compatible. Fast charging that used to be enabled by simple pull-up in micro connector now requires "improved smart chip" and does not work with half of the mobile phones. The question is - why? Is there any reason I don't see? Unlike Apple products these cables are dirt-cheap, and if there is no increased cost then there should not be a reason for manufacturers to make all this mess out of perfectly simple and extremely useful idea. Update: Regarding suggestions to tear down some cable - yes, tearing down and analyzing them with DSO may provide an answer to compatibility problems. But the whole point of posting a question here was the hope that there could be an electrical engineer who *knows* an answer. Also, according to (very limited) marketing info, some manufacturers include identification chip into **plug** portion, designed to trick Apple devices into thinking they connected to authentic cable and avoid annoying pop-ups. Legal issues aside, this has nothing to do with the question, since those cables still have more chips in the connector portion. Funny thing though, is that most devices on "incompatible" lists are Android micro-B / type-C devices. Anyway, here are the theories presented so far: 1. By @pjc50: To simulate the **order of connection** required by USB spec and guaranteed mechanically in regular cables. This is top contender at the moment, because it is applicable to all 3 types of cables on the market (non-reversible, electronically reversible and mechanically reversible). 2. By @Ali\_Chen: To provide additional **ESD protection** highly important here due to exposed pins. This is another strong argument for having chips in the cable, also applicable to all types of cables. 3. By @dim: To avoid **dangling pins** in dual-row models, which might affect high-speed transmission. Not sure if this is critical for USB 2.0 speeds though. 4. By @dim: To **reverse outputs** in single-row models. Yes, this certainly is the case. Note that many cables reverse power only, leaving you without data. Also note, that simple reversing *should not* result in selective compatibility issues. 5. By @tom: To **control the LED**. Now, this is certainly a reason to have some circuitry inside. But if the price is loss of primary function with half of the devices then this is dubious reason, to say the least. Update 2: Is seems there is no one here with insider knowledge of what is really going on in those connectors. So, I am willing to accept @pjc50 and @agent-l suggestions that those chips facilitate an **order of connection** required by USB specification, as something that is *supposed* to be inside from engineering point of view. At the same time, considering how cheap those cables are, I'd like to point out @ali-chen suggestion that they are simple TVS as something that is *actually* there. As a side note, very interesting idea came out of @ali-chen comments - that there are *more reasons to have chips inside plugs* than inside cables. I know that iPhone plugs have chips in them to simulate genuine Apple cable. But since those plugs expose USB interface pins to all the ESD around, having TVS in all plugs regardless of connector type strikes me as another *must have*. Also for electrically-reversible cables the simplest solution to swap power lines would be to put diode bridge in the plug, instead of trying to somehow guess the insertion direction and manage power in the connector. So, until someone tears down actual cable and tells us the truth I propose to consider this question answered.
2018/05/26
[ "https://electronics.stackexchange.com/questions/376536", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/187920/" ]
These are some mock-up "improvements" to charging USB cables. They have a Type-C plug, and then a magnetically-coupled power cable. Other "cables" have a Micro-B plug interchangeable with Type-C plug. > > But nowhere in the USB specification it requires anything but the > wire. > > > This is incorrect, for Type-C connector the USB Specifications **do require** a chip to be embedded into the Type-C connector, on CC lines. It is called "electronic marker". This chip is required to inform the power recipient that the cable can carry higher current, 3 A or 5 A, so the device can engage the "fast charging" internal circuitry without risk of smoking out inappropriately thin cables. Without this IC the consuming device won't charge at maximum rate. There seems to be an unlimited creativity for aftermarket "charging" cables, with magnetic locks (pioneered by Apple I guess), with lighted shrouds, etc., so the compatibility likely depends on who makes the fancy cable. EDIT: If the cable is the "legacy assembly Type-A to Type-C", it would be illegal to advertise the cable as having more than 500 mA capability. So ICs pictured in the the provided link ["magnetic USB"](https://www.aliexpress.com/item/WSKEN-lite-2-magnetic-cable-micro-USB-cable-USB-type-c-cable-fast-charging-for-samsung/32849551871.html) are less likely to be the "electronic markers". Since the magnetic joint exposes signal pins without typical protection by shield/shroud, these ICs are likely just additional ESD suppressors.
Disclaimer: This answer is mostly a guess The device you link to in the comments has a built in LED in the connector, which illuminates when the device is attached and charging. As such it will require some form of circuitry to detect device presence and illuminate the LED. Having said that, the only picture you provide a link to is a cartoon graphic showing the mystical ICs. Who knows what if anything is actually in the cable, and what if anything it does. Without a proper tear down and photos of the guts of a real cable, it's impossible to answer.
376,536
The title basically is the question. Well, I know why Apple added chip to their cables and changed the connector for good measure. That's of course not a corporate greed but a loving care about their customers... and making sure it would cost them a fortune to leave. But nowhere in the USB specification it requires anything but the wire. Of course high speed introduces strict limits to electrical characteristics etc. But still... it is JUST A WIRE! Billions of cables in the world work just fine without anything else. However when it comes to magnetic cables, which are basically regular cables with connector attached to wires by some pins and magnets, they all have chips inside. The end result is that it is practically impossible to find cable which works with all USB devices in home. Each cable comes with a list of incompatible devices almost as long as compatible. Fast charging that used to be enabled by simple pull-up in micro connector now requires "improved smart chip" and does not work with half of the mobile phones. The question is - why? Is there any reason I don't see? Unlike Apple products these cables are dirt-cheap, and if there is no increased cost then there should not be a reason for manufacturers to make all this mess out of perfectly simple and extremely useful idea. Update: Regarding suggestions to tear down some cable - yes, tearing down and analyzing them with DSO may provide an answer to compatibility problems. But the whole point of posting a question here was the hope that there could be an electrical engineer who *knows* an answer. Also, according to (very limited) marketing info, some manufacturers include identification chip into **plug** portion, designed to trick Apple devices into thinking they connected to authentic cable and avoid annoying pop-ups. Legal issues aside, this has nothing to do with the question, since those cables still have more chips in the connector portion. Funny thing though, is that most devices on "incompatible" lists are Android micro-B / type-C devices. Anyway, here are the theories presented so far: 1. By @pjc50: To simulate the **order of connection** required by USB spec and guaranteed mechanically in regular cables. This is top contender at the moment, because it is applicable to all 3 types of cables on the market (non-reversible, electronically reversible and mechanically reversible). 2. By @Ali\_Chen: To provide additional **ESD protection** highly important here due to exposed pins. This is another strong argument for having chips in the cable, also applicable to all types of cables. 3. By @dim: To avoid **dangling pins** in dual-row models, which might affect high-speed transmission. Not sure if this is critical for USB 2.0 speeds though. 4. By @dim: To **reverse outputs** in single-row models. Yes, this certainly is the case. Note that many cables reverse power only, leaving you without data. Also note, that simple reversing *should not* result in selective compatibility issues. 5. By @tom: To **control the LED**. Now, this is certainly a reason to have some circuitry inside. But if the price is loss of primary function with half of the devices then this is dubious reason, to say the least. Update 2: Is seems there is no one here with insider knowledge of what is really going on in those connectors. So, I am willing to accept @pjc50 and @agent-l suggestions that those chips facilitate an **order of connection** required by USB specification, as something that is *supposed* to be inside from engineering point of view. At the same time, considering how cheap those cables are, I'd like to point out @ali-chen suggestion that they are simple TVS as something that is *actually* there. As a side note, very interesting idea came out of @ali-chen comments - that there are *more reasons to have chips inside plugs* than inside cables. I know that iPhone plugs have chips in them to simulate genuine Apple cable. But since those plugs expose USB interface pins to all the ESD around, having TVS in all plugs regardless of connector type strikes me as another *must have*. Also for electrically-reversible cables the simplest solution to swap power lines would be to put diode bridge in the plug, instead of trying to somehow guess the insertion direction and manage power in the connector. So, until someone tears down actual cable and tells us the truth I propose to consider this question answered.
2018/05/26
[ "https://electronics.stackexchange.com/questions/376536", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/187920/" ]
*Disclaimer: I am answering about USB-A and -B connectors, C are bit much more complicated.* USB standard does not include magnetic connectors. Therefore, those can't be formally called "USB cables". How should you think about such "cable" is that it's USB-A-to proprietary and then proprietary-to-USB-B device. The "device" part is crucial here, because the magnetic connector imposes own problems, like current limitation, reliability of connection, exposed pins and wrong order of making contact. There is a crucial part of USB spec that makes simple magnetic connector impossible. USB defines plugging as a process. The ground and voltage pins are supposed to make the contact first, only then the data pins can made contact. So the device can power up and begin negotiation as soon as data gets connected. That's why data pins in USB plugs are shorter, so as you put the plug in, they make contact last. If I were making a magnetic connector (which, makes all contacts simultaneous), I'd insert **a chip that would delay connecting of data pins** to replicate the required behaviour. I believe that the compatibility tables are **mostly** "made-up". They don't guarantee that the cable will be incompatible with other devices, they merely guarantee that the cable will be compatible with listed devices. This is most likely because the magnetic connectors are bulkier than regular connectors. Compatibility table is merely a manufacturer securing themselves against you returning the cable because "it doesn't work with my device". On the other hand, there are also devices that use the voltage negotiation over old USB plugs. Eg my Samsung S7 asks the voltage to be bumped to +9V and the bundled charger delivers. It could fry a Charger Doctor, if I'd try to use one. So, it's reasonable that manufacturers don't want you to use a cable that's limited to 5V (by the chip) on S7. Either the cable chip can be smart enough to detect such negotiation and disrupt it or it'll fry. Thankfully, USB-C has it covered. > > Fast charging that used to be enabled by simple pull-up in micro connector now requires "improved smart chip" and does not work with half of the mobile phones. > > > I don't know anything about that, can you point me to the spec regarding micro plugs? AFAIK there is no spec for resistors in connectors (if we exclude OTG and USB-C). Resistors are in the charger and the device determines max current by those resistance + voltage drop. Having extra connector on the way (which is weak and with small contact surface) surely adds some voltage drop, so the most primitive implementations (high currents @5V) would certainly be very limited. Bottom line: I believe that limits on fast charging are mostly due to physics of magnetic connector itself. The order-ensuring chip has to sense a device being connected, so it most likely monitors current, and that most likely add a bit of resistance on +5V too, further limiting current-carrying capacity. Some regular cables and USB gadgets also prevent fast charging, so magnetic cables are no exceptional in this regard at all. I wouldn't put the blame on the chip, but rather on stretching USB to it's limits.
Disclaimer: This answer is mostly a guess The device you link to in the comments has a built in LED in the connector, which illuminates when the device is attached and charging. As such it will require some form of circuitry to detect device presence and illuminate the LED. Having said that, the only picture you provide a link to is a cartoon graphic showing the mystical ICs. Who knows what if anything is actually in the cable, and what if anything it does. Without a proper tear down and photos of the guts of a real cable, it's impossible to answer.
43,953,617
I want to use stored procedures in C# to get data from a SQL Server table. I want to print the city with the id that I'll pass as a parameter, but I don't know the correct syntax of using parameters like that for a stored procedure in C#. This is the C# code that I'm using: ``` string connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand command = new SqlCommand("SP_GetCityByID where id = 2", conn); command.CommandType = CommandType.StoredProcedure; SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int); param.Direction = ParameterDirection.Input; command.ExecuteNonQuery(); Console.WriteLine(param.Value); } ```
2017/05/13
[ "https://Stackoverflow.com/questions/43953617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7871297/" ]
``` SqlCommand command = new SqlCommand("SP_GetCityByID ", conn); ``` You don't put a `where` condition when you call a stored procedure. `where` condition needs to be inside the body of stored procedure which should compare the `id` column of your city table with `@ID` parameter you are passing to stored procedure. Secondly, `ExecuteNonQuery` function which you have written at the end will not serve your purpose. Use `ExecuteScalar` function instead as given below: ``` String cityName= command.ExecuteScalar(); ``` I am assuming your stored procedure accepts parameter `@ID` and returns matching city name in the form of table.
provide parameter as below: ``` string connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand command = new SqlCommand("SP_GetCityByID", conn); command.CommandType = CommandType.StoredProcedure; SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int).Value = 2; //param.Direction = ParameterDirection.Input; command.ExecuteNonQuery(); Console.WriteLine(param.Value); } ```
13,647,658
Let's say I have next construction ``` <table id="mainTable"> <tr> <td> <div class="parentDiv"> <input class="childInput"/> <table> <tbody> <tr> <td> <span>I am here!</span> <td> </tr> </tbody> </table> </div> </td> </tr> </table> ``` How can I get `input` element from `span`? Using jQuery or standart methods. `mainTable` has many rows so I can't use `id` on input. I can do it with: ``` $($(spanElement).parents(".parentDiv")[0]).children(".childInput")[0] ``` Do you know an easier way?
2012/11/30
[ "https://Stackoverflow.com/questions/13647658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143825/" ]
For really simple data storage needs you can just use the [java File Writer library](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html) for writing simple primitive data types to a file, then when you need to retrieve the data just use the [File Reader Library](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html). This is about as simple as you can get with storing data with java. If that is to simple, then I would suggest look at serializing your data objects and writing them to a file instead. Here's a [link](http://www.ibm.com/developerworks/java/library/j-5things1/index.html), discusses the merits of object Serialization.
If you want save your objects, java serialisation is simpel to use. You get fast (by means of programming effort) and correct results. For configuration input files i recommend java Property files. For huge data, and cross plattfrom transfer java serialisation is less useable.
13,647,658
Let's say I have next construction ``` <table id="mainTable"> <tr> <td> <div class="parentDiv"> <input class="childInput"/> <table> <tbody> <tr> <td> <span>I am here!</span> <td> </tr> </tbody> </table> </div> </td> </tr> </table> ``` How can I get `input` element from `span`? Using jQuery or standart methods. `mainTable` has many rows so I can't use `id` on input. I can do it with: ``` $($(spanElement).parents(".parentDiv")[0]).children(".childInput")[0] ``` Do you know an easier way?
2012/11/30
[ "https://Stackoverflow.com/questions/13647658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143825/" ]
If your traffic grows to larger amounts, consider using a database instead of a flat file. For small amounts you can use a flat file. Accipheran makes a good point to make sure you don't give your users access to things you want secure or hidden. You don't have to use YAML, you can specify your own protocols depending on how much customization you need. But there are already libraries for YAML handling. File IO: <http://www.vogella.com/articles/JavaIO/article.html>
If you want save your objects, java serialisation is simpel to use. You get fast (by means of programming effort) and correct results. For configuration input files i recommend java Property files. For huge data, and cross plattfrom transfer java serialisation is less useable.
61,944,530
We are using the marvelous `exams` package to produce items to be imported to Moodle. Although we noticed that using LaTeX code (i.e. {}) creates conflict with the Moodle code when importing questions. As so, we would like to know alternatives to use all LaTeX functionalities within Moodle. E.g. the $H\_0: \mu\_{males}=\mu\_{females}$ won't be imported due to the "{}"
2020/05/21
[ "https://Stackoverflow.com/questions/61944530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7773713/" ]
I just had the same error. I think the docs for [editing app/build.gradle](https://flutter.dev/docs/deployment/android#configure-signing-in-gradle) are a bit confusing. Here is how I solved it. Note the duplicate buildTypes block. ``` signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } ``` Here is my full app/build.gradle (remember to change the applicationId). ``` def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.google.gms.google-services' apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { compileSdkVersion 28 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { applicationId "!!!YOUR APP ID HERE!!!" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } ```
The answer is Android Studio. I did it. VS Code seems to launch a framework like Flutter. Maybe that problem is a kind of test. A patience test.
61,944,530
We are using the marvelous `exams` package to produce items to be imported to Moodle. Although we noticed that using LaTeX code (i.e. {}) creates conflict with the Moodle code when importing questions. As so, we would like to know alternatives to use all LaTeX functionalities within Moodle. E.g. the $H\_0: \mu\_{males}=\mu\_{females}$ won't be imported due to the "{}"
2020/05/21
[ "https://Stackoverflow.com/questions/61944530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7773713/" ]
I just had the same error. I think the docs for [editing app/build.gradle](https://flutter.dev/docs/deployment/android#configure-signing-in-gradle) are a bit confusing. Here is how I solved it. Note the duplicate buildTypes block. ``` signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } ``` Here is my full app/build.gradle (remember to change the applicationId). ``` def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.google.gms.google-services' apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { compileSdkVersion 28 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { applicationId "!!!YOUR APP ID HERE!!!" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } ```
FYI Duplicate buildTypes block is not true approach. In this way, you override buildTypes. Although your error seems to be fixed, you are not actually signing the APK.
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
`'tes\\ting'` is correct, but you are viewing the `repr` output for the string, which will always show escape characters. ``` >>> print 'tes\\ting' tes\ting ```
b is fine in the second example, you see two slashes because you're printing the representation of b, so slashes are escaped in it too. ``` >>> b 'tes\\ting' >>> print b tes\ting >>> ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
If you want double slashes because the shell will escape \ again, use a raw string: ``` b = a[:3] + r'\\' + a[3:] ```
b is fine in the second example, you see two slashes because you're printing the representation of b, so slashes are escaped in it too. ``` >>> b 'tes\\ting' >>> print b tes\ting >>> ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
If you want double slashes because the shell will escape \ again, use a raw string: ``` b = a[:3] + r'\\' + a[3:] ```
Python's quoting the backslash again when it shows you the representation of the string (in such a way that you could paste it in and get the string with an escaped backslash). If you print the string, you'll see there's only one in the actual string. ``` >>> print "hello\\world" hello\world ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
You are being misled by Python's output. Try: ``` >>> a = "test\\ing" >>> print(a) test\ing >>> print(repr(a)) 'test\\ing' >>> a 'test\\ing' ```
b is fine in the second example, you see two slashes because you're printing the representation of b, so slashes are escaped in it too. ``` >>> b 'tes\\ting' >>> print b tes\ting >>> ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
The second example is correct. There are two slashes because you are printing the *Python representation* of the string. If you want to see the actual string, call `print a`.
Python's quoting the backslash again when it shows you the representation of the string (in such a way that you could paste it in and get the string with an escaped backslash). If you print the string, you'll see there's only one in the actual string. ``` >>> print "hello\\world" hello\world ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
You are being misled by Python's output. Try: ``` >>> a = "test\\ing" >>> print(a) test\ing >>> print(repr(a)) 'test\\ing' >>> a 'test\\ing' ```
The second example is correct. There are two slashes because you are printing the *Python representation* of the string. If you want to see the actual string, call `print a`.
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
`'tes\\ting'` is correct, but you are viewing the `repr` output for the string, which will always show escape characters. ``` >>> print 'tes\\ting' tes\ting ```
Python's quoting the backslash again when it shows you the representation of the string (in such a way that you could paste it in and get the string with an escaped backslash). If you print the string, you'll see there's only one in the actual string. ``` >>> print "hello\\world" hello\world ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
The second example is correct. There are two slashes because you are printing the *Python representation* of the string. If you want to see the actual string, call `print a`.
b is fine in the second example, you see two slashes because you're printing the representation of b, so slashes are escaped in it too. ``` >>> b 'tes\\ting' >>> print b tes\ting >>> ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
You are being misled by Python's output. Try: ``` >>> a = "test\\ing" >>> print(a) test\ing >>> print(repr(a)) 'test\\ing' >>> a 'test\\ing' ```
Python's quoting the backslash again when it shows you the representation of the string (in such a way that you could paste it in and get the string with an escaped backslash). If you print the string, you'll see there's only one in the actual string. ``` >>> print "hello\\world" hello\world ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
You are being misled by Python's output. Try: ``` >>> a = "test\\ing" >>> print(a) test\ing >>> print(repr(a)) 'test\\ing' >>> a 'test\\ing' ```
`'tes\\ting'` is correct, but you are viewing the `repr` output for the string, which will always show escape characters. ``` >>> print 'tes\\ting' tes\ting ```
46,903,286
I have an activity which contains 2 buttons - Login and Sign up. Both of these has an activity linked (Fragment based Tabbed activity) which contains the Login/Signup form. Now I'm unable to navigate to the particular tab when clicked on a button. ie, If signup button is clicked, it should open Signup fragment based tab and If login button is clicked, it should open login fragment based tab. How do I achieve this? Below are my codes for the respective actions. **Home Activity.java -** ``` public class HomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); findViewById(R.id.signup_btn).setOnClickListener(listener_signup_btn); findViewById(R.id.signin_btn).setOnClickListener(listener_signin_btn); } View.OnClickListener listener_signup_btn = new View.OnClickListener() { @Override public void onClick(View view) { //Intent intent = new Intent(HomeActivity.this, SignupActivity.class); //startActivity(intent); } }; View.OnClickListener listener_signin_btn = new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(HomeActivity.this, HomeTaberActivity.class); startActivity(intent); } }; } ``` **HomeTaberActivity.java -** ``` public class HomeTaberActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { private TabLayout hometabLayout; private ViewPager homeviewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hometaber); hometabLayout = (TabLayout) findViewById(R.id.hometabLayout); hometabLayout.addTab(hometabLayout.newTab().setText("Sign In")); hometabLayout.addTab(hometabLayout.newTab().setText("Sign Up")); hometabLayout.setTabGravity(TabLayout.GRAVITY_FILL); homeviewPager = (ViewPager) findViewById(R.id.homepager); HomePager adapter = new HomePager(getSupportFragmentManager(), hometabLayout.getTabCount()); adapter.Initialise(new LoginActivity(),new SignupActivity()); adapter.addstring("Sign In"); adapter.addstring("Sign Up"); homeviewPager.setAdapter(adapter); hometabLayout.setupWithViewPager(homeviewPager); } @Override public void onTabSelected(TabLayout.Tab tab) { homeviewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } } ```
2017/10/24
[ "https://Stackoverflow.com/questions/46903286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8769268/" ]
Well, maybe this is not the most elegant solution, but I hope it helps! ``` library(shiny) ui <- fluidPage( textInput("jobid", label = "Enter job ID", value = ""), uiOutput("button"), textOutput("downloadFail") ) server <- function(input, output, session) { output$button <- renderUI({ if (input$jobid == ""){ actionButton("do", "Download", icon = icon("download")) } else { downloadButton("downloadData", "Download") } }) available <- eventReactive(input$do, { input$jobid != "" }) output$downloadFail <- renderText({ if (!(available())) { "No job id to submit" } else { "" } }) output$downloadData <- downloadHandler( filename = function() { paste("data-", Sys.Date(), ".csv", sep="") }, content = function(file) { write.csv(data, file) }) } shinyApp(ui, server) ```
You could use `showNotification`, or to write to the UI look at `renderUI` and `outputUI` functions. ``` `output$download <- downloadHandler( filename = function(){ "filename.csv") }, content = function(file){ if(nrow(data() < 10000) { write.csv(data(), file) } else { showNotification("Data too big") } )` ```
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
Standard C++ does not support variable-length arrays.1 If you want this behaviour, I would suggest using a `std::vector` rather than a raw C-style array. --- 1. However, you can find them in C99, or in non-standard language extensions.
At the moment of compilation the value of variable n is unknown (it's just what've been in memory under the address it was given), so you can't make a variable of unknown size. and in second case, you know the size, as you've used cin (not sin).
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
Standard C++ does not support variable-length arrays.1 If you want this behaviour, I would suggest using a `std::vector` rather than a raw C-style array. --- 1. However, you can find them in C99, or in non-standard language extensions.
If you want to create an array of variable size you must do it on the heap using `new`. The only way that you can use it the way you have would be if you had declared your integer as a constant.
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
Standard C++ does not support variable-length arrays.1 If you want this behaviour, I would suggest using a `std::vector` rather than a raw C-style array. --- 1. However, you can find them in C99, or in non-standard language extensions.
(1) The first thing that happens when you create an instance of A is allocating the memory, at that point the member `n` does not exist so it is impossible to know how much memory `arr` needs. (2) Creates an array on the stack, this only moves the stackpointer a bit.
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
If you want to create an array of variable size you must do it on the heap using `new`. The only way that you can use it the way you have would be if you had declared your integer as a constant.
At the moment of compilation the value of variable n is unknown (it's just what've been in memory under the address it was given), so you can't make a variable of unknown size. and in second case, you know the size, as you've used cin (not sin).
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
(1) The first thing that happens when you create an instance of A is allocating the memory, at that point the member `n` does not exist so it is impossible to know how much memory `arr` needs. (2) Creates an array on the stack, this only moves the stackpointer a bit.
At the moment of compilation the value of variable n is unknown (it's just what've been in memory under the address it was given), so you can't make a variable of unknown size. and in second case, you know the size, as you've used cin (not sin).
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
(1) The first thing that happens when you create an instance of A is allocating the memory, at that point the member `n` does not exist so it is impossible to know how much memory `arr` needs. (2) Creates an array on the stack, this only moves the stackpointer a bit.
If you want to create an array of variable size you must do it on the heap using `new`. The only way that you can use it the way you have would be if you had declared your integer as a constant.
28,021,734
I could not understand how to update Q values for tic tac toe game. I read all about that but I could not imagine how to do this. I read that Q value is updated end of the game, but I haven't understand that if there is Q value for each action ?
2015/01/19
[ "https://Stackoverflow.com/questions/28021734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4462426/" ]
You have a `Q` value for each state-action pair. You update one `Q` value after every action you perform. More precisely, if applying action `a1` from state `s1` gets you into state `s2` and brings you some reward `r`, then you update `Q(s1, a1)` as follows: ``` Q(s1, a1) = Q(s1, a1) + learning_rate * (r + discount_factor * max Q(s2, _) - Q(s1, a1)) ``` In many games, such as tic-tac-toe you don't get rewards until the end of the game, that's why you have to run the algorithm through several episodes. That's how information about utility of final states is propagated to other states.
The problem with the standard Q Learning algorithm is that it just takes too long to propagate the values from the final to the first move because you only know the outcome of the game at the end of it. Therefore the Q Learning algorithm should be modified. The following paper gives some details on possible modifications: 1. a non negative reward is given after the game ends (except for draw), then the Q updates is not performed at every action step (which changes nothing), but only after the end of the game 2. the Q updates is performed by propagating its new value from the last move backward to the first move 3. another update formula is incorporated that also considers the opponent point of view because of the turn-taking nature of two-player game Abstract: > > This paper reports our experiment on applying Q Learning algorithm for > learning to play Tic-tac-toe. The original algorithm is modified by > updating the Q value only when the game terminates, propagating the > update process from the final move backward to the first move, and > incorporating a new update rule. We evaluate the agent performance > using full-board and partial-board representations. In this > evaluation, the agent plays the tic-tac-toe game against human > players. The evaluation results show that the performance of modified > Q Learning algorithm with partial-board representation is comparable > to that of human players. > > > [Learning to Play Tic-Tac-Toe (2009) by Dwi H. Widyantoro & Yus G. Vembrina](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?tp=&arnumber=5254776&url=http%3A%2F%2Fieeexplore.ieee.org%2Fiel5%2F5235860%2F5254768%2F05254776.pdf%3Farnumber%3D5254776) (Unfortunately it is behind a paywall. Either you have access to the IEEE archive or you can ask the authors to provide a copy on researchgate: <https://www.researchgate.net/publication/251899151_Learning_to_play_Tic-tac-toe>)
36,331,289
I have one MYSQL query with me I want to execute this query in laravel. ``` select d1.update_id from ( select update_id, count(update_id) as ct from updates_tags where tag_id in (67,33,86,55) group by update_id) as d1 where d1.ct=4 ``` Please guide me how do i Do it easily. I have one reference with me.... It is not working ``` $updateArray = DB::table('updates_tags') ->select('update_id', DB::raw('count(*) as update_id')) ->whereIn('tag_id',$jsontags) ->groupBy('update_id') ->having('update_id','=',count($jsontags)) ->lists('update_id'); ```
2016/03/31
[ "https://Stackoverflow.com/questions/36331289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6139469/" ]
change the `where('total','=',count($tags)) to having('total','=',count($tags))` ``` $update = DB::table('tags') ->select('t_id', 'u_id', DB::raw('count(*) as total')) ->whereIn('t_id',$tags) ->groupBy('u_id') ->having('total','=',count($tags)) ->lists('u_id'); ```
In classic PHP, we used to use `mysqli` connector. In CodeIgniter, we use ActiveRecords (fully lovely). In Laravel, there is also ActiveRecords for SQL queries. Checkout the official Laravel docs, query builder is your friend. <https://laravel.com/docs/4.2/queries>
36,331,289
I have one MYSQL query with me I want to execute this query in laravel. ``` select d1.update_id from ( select update_id, count(update_id) as ct from updates_tags where tag_id in (67,33,86,55) group by update_id) as d1 where d1.ct=4 ``` Please guide me how do i Do it easily. I have one reference with me.... It is not working ``` $updateArray = DB::table('updates_tags') ->select('update_id', DB::raw('count(*) as update_id')) ->whereIn('tag_id',$jsontags) ->groupBy('update_id') ->having('update_id','=',count($jsontags)) ->lists('update_id'); ```
2016/03/31
[ "https://Stackoverflow.com/questions/36331289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6139469/" ]
You can just do a RAW query. like this: ``` $sqlQuery = "SELECT d1.update_id FROM..."; $result = DB::select(DB::raw($sqlQuery)); ``` the $result will be an array
In classic PHP, we used to use `mysqli` connector. In CodeIgniter, we use ActiveRecords (fully lovely). In Laravel, there is also ActiveRecords for SQL queries. Checkout the official Laravel docs, query builder is your friend. <https://laravel.com/docs/4.2/queries>
1,132,336
> > Let $G$ be a finite group and define the power map $p\_m:G\to G$ for any $m\in\mathbb Z$ by $p\_m(x)=x^m$. > When is this map a group homomorphism? > > > **Elaborately**: Can we somehow describe or classify those groups $G$ and numbers $m$ for which $p\_m$ is a homomorphism? > For example, is the image $p\_m(G)$ necessarily an abelian subgroup like in all of my examples? > If a group admits a nontrivial $m$ (that is, $m\not\equiv0,1\pmod N$) for which $p\_m$ is a homomorphism, is the group necessarily a product of an abelian group and another group? > > > Observations ------------ 1. The $p\_m$ is clearly a homomorphism whenever $G$ is abelian. 2. Also, if $N$ is the least common multiple of orders of elements of $G$, then $p\_{m+N}=p\_m$ for all $m$ so the answer only depends on $m$ modulo $N$. (Note that $N$ divides $|G|$ but need not be equal to it.) Also, $p\_0$ and $p\_1$ are always homomorphisms and $p\_{-1}$ is so if and only if $G$ is abelian. Examples -------- 1. If $G=C\_4\times S\_3$ (where $C\_n$ denotes the cyclic group of order $n$), then $p\_6$ is a nontrivial homomorphism (neither constant nor identity). Its image is $C\_2\times0<C\_4\times S\_3$. 2. More generally, if $G\_1$ is any nonabelian group and $n$ coprime to $m=|G\_1|$, then $p\_m$ is a nontrivial homomorphism for $G=C\_n\times G\_1$.
2015/02/03
[ "https://math.stackexchange.com/questions/1132336", "https://math.stackexchange.com", "https://math.stackexchange.com/users/166535/" ]
You can't prove that it always produces primes, because that is not true. The way to prove that it *doesn't* always produce primes is to show a counterexample. The smallest counterexample is $$ q\_6 = 2\cdot 3\cdot 5\cdot7\cdot 11\cdot 13+1 = 30031 = 59\cdot 509 $$ It's hard to state categorically that this *can't* be proved other than exhibiting a counterexample. Conceivably we could find some property that the $q\_i$ sequence has (and prove that it has it without computing so much that we run into the counterexample itself) and then prove that no sequence with that property can consist entirely of primes. But even if that can be carried out, it would surely (in this case) be more complex than showing the counterexample.
How about "Every number has possible prime factors up to its square root. Thus every $q$ has possible prime factors between the largest prime used to create it and it's own square root."?
41,992,735
I have a very simple page.php that should display all URL parameters. (I am having this issue in a more complex page but stripped it down to only this test, and the issue persists) ``` <?php if (!isset($_SESSION)) { session_start(); } print_r($_GET); ?> ``` When I navigate directly to page.php?someProperty=testing , I sometimes get an empty array(), followed by working as expected on the second attempt, and every subsequent attempt. It seems to always fail the first time I make a request from the server after having been away for a while. I'm beginning to think it's something lower level. It's very difficult to debug because as soon as I observe it, it goes away. What could cause this? **Environment Info:** * PHP 5.3 * Apache 2 * Redhat Linux PS - I've read other similar posts, but in each case, someone had forgotten to initialize a session or something. I also made sure no whitespace or headers are set before the session is initialized Update - When the page fails to read the URL parameters, the browser also immediately drops the query string from the location bar as well, reducing it to domain.com/page.php Even if I manually type in the full address for page.php?test=test into the URL bar, it just immediately shortens, and the page outputs a blank array. Also, there is no rewriting of any kind enabled in Apache
2017/02/02
[ "https://Stackoverflow.com/questions/41992735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3554288/" ]
Try like this.For matching multiple words you have use `contains` again. ``` $("td:contains('hour'):contains('day')").css("color", "red"); ``` Example ```js $("p:contains('is'):contains('name')").css("background-color", "red"); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>My name is Donald.</p><!--it will matched contains both `is` and `name`--> <p>I live in Duckburg.</p><!--not matched --> <p>My best friend is Mickey.</p><!--not matched contains only `is`--> ```
You need to further refine the selector after finding the first match and be aware of the case-sensitive nature of your test (only lower-case matches will be found). ```js $("td:contains('hour'):contains('day')").css("color", "red"); ``` ```css table, td { border:1px solid black; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Hour</td> <td>Day</td> <td>hour</td> <td>day</td> <td>None</td> <td>hour and day</td> <td>Hour and Day</td> </tr> </table> ``` For a case-insensitive search: ```js var theCells = $("td"); // Loop through the cells and check lower-case text against lower-case value theCells.each(function(){ if(this.textContent.toLowerCase().indexOf("hour") > -1 && this.textContent.toLowerCase().indexOf("day") > -1){ this.style.color = "red"; } }); ``` ```css table, td { border:1px solid black; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Hour</td> <td>Day</td> <td>None</td> <td>hour and day</td> <td>Hour and Day</td> </tr> </table> ```
53,951,386
<https://imgur.com/bcKQIJr> <-- Calendar Image I have a calendar that requires a double click select dates. I'm working in Javascript, and the NodeJS Selenium-webdriver library has a pretty limited set of events, with no double click option... Do I need to incorporate another library for a double click feature or something? I've really hit a wall. I know this code doesn't work, I've tried a little bit of everything. I just need to double click on a list of elements like the one below. ``` `el = driver.findElement(By.xpath("//div[@class='container']//table[2]//tbody[1]//tr[1]//td[3]")); el.click() .then(_ => driver.sleep(250)) .then(_ => el.click()) ` ``` I can see the clicks happening, so I know I have the element right and the event is happening at the right place/time... but I can't trigger the "selected" dates with what I've got.
2018/12/27
[ "https://Stackoverflow.com/questions/53951386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10458621/" ]
In case of some case (specific to browsers) this might not work for calendars. You might need to use javascript executer for this purpose. Below is some code for your reference. ``` let ele = document.evaluate("//th[@title='Chrome']", document, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; var clickEvent = document.createEvent ('MouseEvents'); clickEvent.initEvent ('dblclick', true, true); ele.dispatchEvent (clickEvent); ``` This should simulate double click on the element. Store this script in a variable (e.g. scrpit) and send to browser for execution using js executor. below is some sample code assuming variable `script` has the js script ``` driver.executeScript(script).then(function(return_value) { console.log('returned ', return_value) }); ```
You should be able to use the `actions()` method as described in [this](https://stackoverflow.com/questions/46286755/selenium-web-driver-double-click-or-select-a-value-like-ctrla-in-a-nodejs) question's answer. ``` driver.actions().doubleClick(el).perform(); ```
37,587
Since I married Mjoll the Lioness recently she's set up shop in my home and it seems like the merchandise she sells varies greatly depending her current location/actual inventory. I traded her things like dragon scales/materials and checked her shop to find those materials listed there as well. If this is the case, I guess my real question is are the items that are listed in her store ***my*** items? and will they ever be sold or "disappear" somehow without my consent or knowledge? I really don't want to find out that valuable items/weapons/armor I spent a long time acquiring ended up being the "deal of the week." Are items in my spouse's shop mine and will they ever be sold against my will?
2011/11/21
[ "https://gaming.stackexchange.com/questions/37587", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/14934/" ]
If your spouse was a merchant before you married them, they will sell the same goods they would normally. If not, they will sell pawnbroker-type goods and (reportedly) loose items you leave in their inventory. They will not sell items you leave around the house. Their inventory "refreshes" like other shopkeeper inventories, so don't sell them something you are planning to buy back later.
From wiki: "You don't need to worry about losing items by placing them in your spouse's inventory because they sold them to someone. Like all merchants in the game, they will actually only sell things to you, and not other people."
52,717,879
I have a project with the following directory structure: ``` src/main/java src/main/resources src/test/java src/test/resources ``` I want to add a new folder, `integrationTest`: ``` src/integrationTest/java src/integrationTest/resources ``` Where I want to keep integration tests totally separate from unit tests. How should I go about adding this? In the build.gradle, I'm not sure how to specify a new task that'd pick this folder build it and run the tests separately.
2018/10/09
[ "https://Stackoverflow.com/questions/52717879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3719089/" ]
Gradle has a concept of `source sets` which is exactly what you need here. You have a detailed documentation about that in the *Java Plugin* documenation here : <https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_source_sets> You can define a new source set "integrationTest" in your `build.gradle` ``` sourceSets { integrationTest { java { compileClasspath += main.output + test.output runtimeClasspath += main.output + test.output srcDir file('src/integration-test/java') } resources.srcDir file('src/integration-test/resources') } } ``` This will automatically create new *configurations* `integrationTestCompile` and `integrationTestRuntime`, that you can use to define an new *Task* `integrationTests`: ``` task integrationTest(type: Test) { testClassesDirs = sourceSets.integrationTest.output.classesDirs classpath = sourceSets.integrationTest.runtimeClasspath } ``` For reference : a working full example can be found here : <https://www.petrikainulainen.net/programming/gradle/getting-started-with-gradle-integration-testing/>
Please add the newly created source folder also to source sets in **build.gradle** as below: ``` sourceSets { main { java { srcDirs = ['src'] } } test { java { srcDirs = ['test'] } } integrationTest { java { srcDirs = ['integrationTest'] } } } ``` Cheers !
134,978
i know hexadecimal charchter ( 0 1 2 3 4 5 6 7 8 9 A B C D E F) when i write code ``` string a= hex"011a" //it is ok ``` but when write this code ``` string a=hex"011aa" // get Error ``` why? and how can i take advantage of this in solidity
2022/09/04
[ "https://ethereum.stackexchange.com/questions/134978", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/107176/" ]
First, you need to add the characters in pairs, since a pair of hex digit is a byte. The line that is showing an error has an uneven set of characters: ```js string a=hex"011aa" // get Error ``` Better do this: ```js string a2 =hex"011a0a"; ``` Also, the reason is that you need to add bytes whose values are within the range (in decimal) of 0-127. Because those are the value printable UTF-8 characters that Solidity support. For example, look at this table: <https://www.asciitable.com/> You will see that it goes from 0 to 127 in decimal. In hexadecimal, the range goes from 0-7F. If you try this: ```js string a = hex"aa"; ``` It will not work, because the decimal value of the hex `aa` is 170, and we know that it should not be greater than 127. So we are limited to the range 0-7F in hex: ```js string min_max_accii_value = hex"00_7f"; ``` Do your own conversion here: <https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=aa> So, you can do something like this, and separate it with `_` to make it more readable: ```js string a3 = hex"00_0a_7f"; ``` Here the docs: <https://docs.soliditylang.org/en/v0.8.11/types.html#unicode-literals>
Although its really unclear what you're trying to do, when you do `string x = hex'something'`, the compiler will look for UTF-8 characters that corresponds to the hex number you entered, and is therefore is expecting an even number of characters (2 hex characters = 1 byte). As for your 2nd question, i don't really understand it, sorry, you can... Use that to output non printable characters, i guess? (which is what you're doing with the 1st string, 01 and 1a are both non printable characters in UTF-8) But yeah, why would you do that?
5,581,261
Today is my first day trying to use Oracle databases in Asp.NET so I have no idea of what I need to do. I have added this code ``` Dim oOracleConn As OracleConnection = New OracleConnection() oOracleConn.ConnectionString = "Data Source=xxxxx;User Id=yyy;Password=psw;" oOracleConn.Open() Response.write("Connected to Oracle.") oOracleConn.Close() oOracleConn.Dispose() End Sub ``` But it gives me the error > > Type 'OracleConnection' is not defined. > > > Now i've had a look on the internet and it says that it may be the reference to the DLL that is missing? I know I have got a DLL reference in my page and I don't think I even have the DLL anywhere on my server. Where do I get this DLL from? I've downloaded the ODBC .NET data provider but this didn't seem to help. I've tried to add a reference in Visual Studio but I can't find the Oracle client reference in the list. Any ideas? Thanks
2011/04/07
[ "https://Stackoverflow.com/questions/5581261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372364/" ]
The Oracle recommended method is to use the [Oracle Data Provider for .NET](http://www.oracle.com/technetwork/topics/dotnet/index-085163.html) You'll need an Oracle Client that is compatible with the version of the database you are using installed on your dev machine and the web sever machine. There are some quirks with how you have to specify the database connection string. Some kind internet soul has [documented](http://www.connectionstrings.com/oracle) the database connection strings for the oracle providers. The oracle client has a file, called TNSNAMES.ORA, which is typically located in the /NETWORK/ADMIN folder under the oracle home where the client was installed (the installation location varies by version and installation settings). This file contains a list of databases with the Port Number, Hostname, and Oracle SID which allows the oracle client to make a connection to a server. Once all of this is configured (or you decide to use the "TNS-less" connection string), you should be able to make database connections to oracle. The ODP.NET provider documentation also provides some sample code which is very helpful when getting started with it.
Per [this](http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracleconnection.aspx), this OracleConnection is an obsolete API, however the DLL being used is: ``` System.Data.OracleClient.dll ``` EDIT: This [article](http://www.c-sharpcorner.com/UploadFile/rajeshnk/OracleConnectivityInNet11302005055528AM/OracleConnectivityInNet.aspx) provides some data on different API's to connect to Oracle with .NET
5,581,261
Today is my first day trying to use Oracle databases in Asp.NET so I have no idea of what I need to do. I have added this code ``` Dim oOracleConn As OracleConnection = New OracleConnection() oOracleConn.ConnectionString = "Data Source=xxxxx;User Id=yyy;Password=psw;" oOracleConn.Open() Response.write("Connected to Oracle.") oOracleConn.Close() oOracleConn.Dispose() End Sub ``` But it gives me the error > > Type 'OracleConnection' is not defined. > > > Now i've had a look on the internet and it says that it may be the reference to the DLL that is missing? I know I have got a DLL reference in my page and I don't think I even have the DLL anywhere on my server. Where do I get this DLL from? I've downloaded the ODBC .NET data provider but this didn't seem to help. I've tried to add a reference in Visual Studio but I can't find the Oracle client reference in the list. Any ideas? Thanks
2011/04/07
[ "https://Stackoverflow.com/questions/5581261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372364/" ]
The Oracle recommended method is to use the [Oracle Data Provider for .NET](http://www.oracle.com/technetwork/topics/dotnet/index-085163.html) You'll need an Oracle Client that is compatible with the version of the database you are using installed on your dev machine and the web sever machine. There are some quirks with how you have to specify the database connection string. Some kind internet soul has [documented](http://www.connectionstrings.com/oracle) the database connection strings for the oracle providers. The oracle client has a file, called TNSNAMES.ORA, which is typically located in the /NETWORK/ADMIN folder under the oracle home where the client was installed (the installation location varies by version and installation settings). This file contains a list of databases with the Port Number, Hostname, and Oracle SID which allows the oracle client to make a connection to a server. Once all of this is configured (or you decide to use the "TNS-less" connection string), you should be able to make database connections to oracle. The ODP.NET provider documentation also provides some sample code which is very helpful when getting started with it.
The real problem is data type mapping,but not connection or provider .
17,135,857
I got a form called Form1 and a rich text box called richtextbox1, which is automatically generated, so it's private. I got another class that connects to a server, I want to output the status of connecting but I can only access the richtextbox1.Text in the Form1 class, I got 2 possible solutions for this, which would be better or is there a better one that I don't know of? 1. making the textbox public 2. instead of : ``` Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); ``` creating a form1 object first and using that to store the form that is running: ``` //somewhere global Form1 theform = new Form1(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(theform); ``` Then using the object somewhere in my connection class.
2013/06/16
[ "https://Stackoverflow.com/questions/17135857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373581/" ]
I'd create a public property in `Form1` that you can use. `Form1.cs` ``` public string TextBoxText { get { return myTextBox.Text; } set { myTextBox.Text = value; } } ``` You can then set the value from another class. `AnotherClass.cs` ``` myForm1.TextBoxText = "Current server status"; ``` How you get access to `myForm1` depends on how you're calling the other class. For example, you could pass the form into the other class's constructor. ``` private Form1 myForm1 = null; public AnotherClass(Form1 mainForm) { myForm1 = mainForm; myForm1.TextBoxText = "Current server status"; } ```
If you are creating the class that is communicating with the server in Form1, add an event to it and subscribe to it in Form1 when you create it.
42,765,259
**Background:** On a project I am working on, we've switched from using AngularJS (1.6.2) with JavaScript, to TypeScript 2.1.5. We have a decorator applied to the `$exceptionHandler` service that causes JavaScript exceptions to make a call to a common API that send the development team an e-mail; in this way, we can easily see what front-end errors our end-users are encountering in the wild. **Problem:** I recently converted this decorator from JavaScript, to TypeScript. When I try to run the application, I encounter a whitescreen of nothing. After much debugging I discovered that the issue is because AngularJS expects the `$provide.decorator` to pass a function along with a list of dependencies. However, an object is instead being observed, and thus forcing Angular to fail-safe. I diagnosed the problem by setting breakpoints inside of `angular.js` itself; it specifically will fail on line 4809 (inside of function `createInternalInjector(cache, factory)`) due to a thrown, unhandled JavaScript exception, but the part that's actually responsible for the failure is line 4854, inside of function `invoke(fn, self, locals, serviceName)`. The reason it fails, is because the dependencies passed come across as `['$delegate', '$injector',]`; the function is missing from this set. Lastly, one thing I considered doing was simply defining a JavaScript function in the class code. This does not work in my case for two reasons. First, in our `ts.config`, we have `noImplicitAny` set to true; functions are implicitly of the `any` type. Additionally, TypeScript itself appears not to recognize `function` as a keyword, and instead tries and fails to compile it as a symbol on class `ExceptionHandler`. **TypeScript Exception Handler:** ``` export class ExceptionHandler { public constructor( $provide: ng.auto.IProviderService ) { $provide.decorator('$exceptionHandler`, [ '$delegate', '$injector', this.dispatchErrorEmail ]); } public dispatchErrorEmail( $delegate: ng.IExceptionHandlerService, $injector: ng.auto.IInjectorService ): (exception: any, cause: any) => void { return (exception: any, cause: any) => { // First, execute the default implementation. $delegate(exception, cause); // Get our Web Data Service, an $http wrapper, injected... let webDataSvc: WebDataSvc = $injector.get<WebDataSvc>('webDataSvc'); // Tell the server to dispatch an email to the dev team. let args: Object = { 'exception': exception }; webDataSvc.get('/api/common/errorNotification', args); }; } } angular.module('app').config(['$provide', ExceptionHandler]); ``` **Original JS:** ``` (function () { 'use strict'; angular.module('app').config(['$provide', decorateExceptionHandler]); function decorateExceptionHandler($provide) { $provide.decorator('$exceptionHandler', ['$delegate', '$injector', dispatchErrorEmail]); } function dispatchErrorEmail($delegate, $injector) { return function (exception, cause) { // Execute default implementation. $delegate(exception, cause); var webDataSvc = $injector.get('webDataSvc'); var args = { 'exception': exception, }; webDataSvc.get('/api/common/ErrorNotification', args); }; } })(); ``` **Questions:** 1. In what way can I rewrite the TypeScript Exception Handler to be properly picked up by AngularJS? 2. If I can't, is this an AngularJS bug that needs to be escalated? I know for a fact I'm not the only person using AngularJS with TypeScript; being unable to decorate a service due to language choice seems like a pretty major problem.
2017/03/13
[ "https://Stackoverflow.com/questions/42765259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404206/" ]
Converting everything to classes isn't the purpose of TS, there's no use for classes here. JS code is supposed to be augmented with types and probably be enhanced with `$inject` annotation. ``` angular.module('app').config(decorateExceptionHandler); decorateExceptionHandler.$inject = ['$provide']; export function decorateExceptionHandler($provide: ng.auto.IProviderService) { $provide.decorator('$exceptionHandler', dispatchErrorEmail); } dispatchErrorEmail.$inject = ['$delegate', '$injector']; export function dispatchErrorEmail( $delegate: ng.IExceptionHandlerService, $injector: ng.auto.IInjectorService ): (exception: any, cause: any) => void { ... } ``` `config` expects a regular function, not a constructor. And the reason why the original TS code fails is that `ExceptionHandler` isn't called with `new`, thus `this` is not an object, and `this.dispatchErrorEmail` is not a function.
Here's another way to do it using [TypeScript namespaces](https://www.typescriptlang.org/docs/handbook/namespaces.html). It feels a little cleaner to me, keeping the exception extension functions isolated, and is a nice conceptually coming from something like C#. exception.module.ts ``` import * as angular from 'angular'; import { LoggerModule } from '../logging/logger.module'; import { ExceptionExtension } from './exception.handler'; export const ExceptionModule = angular.module('app.common.exception', [LoggerModule]) .config(ExceptionExtension.Configure) .name; ``` exception.handler.ts ``` import { ILoggerService } from '../logging/logger.service'; export namespace ExceptionExtension { export const ExtendExceptionHandler = ($delegate: ng.IExceptionHandlerService, logger: ILoggerService) => { return function (exception: Error, cause?: string): void { $delegate(exception, cause); logger.error(exception.message, "Uncaught Exception", cause ? cause : ""); } }; ExtendExceptionHandler.$inject = ['$delegate', 'ILoggerService']; export const Configure = ($provide: ng.auto.IProvideService) => { $provide.decorator('$exceptionHandler', ExtendExceptionHandler); }; Configure.$inject = ['$provide']; } ```
77,723
Jumping cursor while typing on my Asus EEE PC 1015PE. Keyboard shortcut--Function key plus F3 also not working, as well as a few other function keys not working. Would appreciate any help. Note: mouse/touchpad "Disable touchpad while typing" setting is enabled, but does not work.
2011/11/10
[ "https://askubuntu.com/questions/77723", "https://askubuntu.com", "https://askubuntu.com/users/33124/" ]
``` gksudo gedit /etc/modprobe.d/options.conf ``` Add this line to the file and save it: > > options psmouse proto=imps > > > Restart. Source: <https://bugs.launchpad.net/ubuntu/+source/xserver-xorg-input-synaptics/+bug/355326/comments/9>
Try disabling mouse/touchpad "Disable touchpad while typing" setting and maybe it will help with that couse anyway u say it doesnt work so maybe thats why it jumps couse doesnt work. Also try again enabling. and restart after each try. If doesnt help leave as disabled that option and install Touchfreeze from ubuntu soft manager. If on reboot it doesnt work automatically then put it to be starting on startup in System > Preferences > Sessions startup programms with adding new and writing command in there touchfreeze
77,723
Jumping cursor while typing on my Asus EEE PC 1015PE. Keyboard shortcut--Function key plus F3 also not working, as well as a few other function keys not working. Would appreciate any help. Note: mouse/touchpad "Disable touchpad while typing" setting is enabled, but does not work.
2011/11/10
[ "https://askubuntu.com/questions/77723", "https://askubuntu.com", "https://askubuntu.com/users/33124/" ]
``` gksudo gedit /etc/modprobe.d/options.conf ``` Add this line to the file and save it: > > options psmouse proto=imps > > > Restart. Source: <https://bugs.launchpad.net/ubuntu/+source/xserver-xorg-input-synaptics/+bug/355326/comments/9>
I had the same issue, solution was to install SYNAPTIKS from the Ubuntu 11.10 repo. Worked well, no-more issues.
77,723
Jumping cursor while typing on my Asus EEE PC 1015PE. Keyboard shortcut--Function key plus F3 also not working, as well as a few other function keys not working. Would appreciate any help. Note: mouse/touchpad "Disable touchpad while typing" setting is enabled, but does not work.
2011/11/10
[ "https://askubuntu.com/questions/77723", "https://askubuntu.com", "https://askubuntu.com/users/33124/" ]
``` gksudo gedit /etc/modprobe.d/options.conf ``` Add this line to the file and save it: > > options psmouse proto=imps > > > Restart. Source: <https://bugs.launchpad.net/ubuntu/+source/xserver-xorg-input-synaptics/+bug/355326/comments/9>
Try using the `FN` key and the `f` buttons, obviously not those marked for general use like brightness or sound. I just found that if I use the `fn` and `f5` buttons on my laptop it stops the touchpad. I had tried various other things to deactivate it, from unistalling to diabling to downloading software; then came across this post and yeahhhh it works like magic. :-)
67,113,324
I made a function that replaces multiple instances of a single character with multiple patterns depending on the character location. There were two ways I found to accomplish this: 1. This one looks horrible but it works: def xSubstitution(target\_string): ``` while target_string.casefold().find('x') != -1: x_finded = target_string.casefold().find('x') if (x_finded == 0 and target_string[1] == ' ') or (target_string[x_finded-1] == ' ' and ((target_string[-1] == 'x' or 'X') or target_string[x_finded+1] == ' ')): target_string = target_string.replace(target_string[x_finded], 'ecks', 1) elif (target_string[x_finded+1] != ' '): target_string = target_string.replace(target_string[x_finded], 'z', 1) else: target_string = target_string.replace(target_string[x_finded], 'cks', 1) return(target_string) ``` 2. This one technically works, but I just can't get the regex patterns right: import re def multipleRegexSubstitutions(sentence): ``` patterns = {(r'^[xX]\s'): 'ecks ', (r'[^\w]\s?[xX](?!\w)'): 'ecks', (r'[\w][xX]'): 'cks', (r'[\w][xX][\w]'): 'cks', (r'^[xX][\w]'): 'z',(r'\s[xX][\w]'): 'z'} regexes = [ re.compile(p) for p in patterns ] for regex in regexes: for match in re.finditer(regex, sentence): match_location = sentence.casefold().find('x', match.start(), match.end()) sentence = sentence.replace(sentence[match_location], patterns.get(regex.pattern), 1) return sentence ``` From what I figured it out, the only problem in the second function is the regex patterns. Could someone help me? EDIT: Sorry I forgot to tell that the regexes are looking for the different x characters in a string, and replace an X in the beggining of a word for a 'Z', in the middle or end of a word for 'cks' and if it is a lone 'x' char replace with 'ecks'
2021/04/15
[ "https://Stackoverflow.com/questions/67113324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14244437/" ]
If we need the same output as in `final_outcome` ``` library(dplyr) my_data %>% mutate(attempt = start - cumsum(change)) %>% arrange(age_grp) ``` -output ``` # age_grp start change final_outcome attempt #1 1 0.42 0.034 0.125 0.125 #2 2 0.42 0.027 0.159 0.159 #3 3 0.42 0.030 0.186 0.186 #4 4 0.42 0.032 0.216 0.216 #5 5 0.42 0.032 0.248 0.248 #6 6 0.42 0.027 0.280 0.280 #7 7 0.42 0.031 0.307 0.307 #8 8 0.42 0.029 0.338 0.338 #9 9 0.42 0.033 0.367 0.367 #10 10 0.42 0.020 0.400 0.400 ```
``` library(tidyverse) my_data %>% mutate(attempt = accumulate(change, ~ .x - .y, .init = start[1])[-1]) ``` Note: `accumulate` is from the `purrr` library that's part of the `tidyverse`. It also has a `.dir` argument where you can go `"forward"` or `"backward"`. Or in base `R` using `Reduce`: ``` within(my_data, attempt <- Reduce("-", change, init = start[1], accumulate = T)[-1]) ``` `Reduce` has an argument `right` that can also do the computation forwards or backwards. **Output** ``` age_grp start change final_outcome attempt 1 10 0.42 0.020 0.400 0.400 2 9 0.42 0.033 0.367 0.367 3 8 0.42 0.029 0.338 0.338 4 7 0.42 0.031 0.307 0.307 5 6 0.42 0.027 0.280 0.280 6 5 0.42 0.032 0.248 0.248 7 4 0.42 0.032 0.216 0.216 8 3 0.42 0.030 0.186 0.186 9 2 0.42 0.027 0.159 0.159 10 1 0.42 0.034 0.125 0.125 ```
67,113,324
I made a function that replaces multiple instances of a single character with multiple patterns depending on the character location. There were two ways I found to accomplish this: 1. This one looks horrible but it works: def xSubstitution(target\_string): ``` while target_string.casefold().find('x') != -1: x_finded = target_string.casefold().find('x') if (x_finded == 0 and target_string[1] == ' ') or (target_string[x_finded-1] == ' ' and ((target_string[-1] == 'x' or 'X') or target_string[x_finded+1] == ' ')): target_string = target_string.replace(target_string[x_finded], 'ecks', 1) elif (target_string[x_finded+1] != ' '): target_string = target_string.replace(target_string[x_finded], 'z', 1) else: target_string = target_string.replace(target_string[x_finded], 'cks', 1) return(target_string) ``` 2. This one technically works, but I just can't get the regex patterns right: import re def multipleRegexSubstitutions(sentence): ``` patterns = {(r'^[xX]\s'): 'ecks ', (r'[^\w]\s?[xX](?!\w)'): 'ecks', (r'[\w][xX]'): 'cks', (r'[\w][xX][\w]'): 'cks', (r'^[xX][\w]'): 'z',(r'\s[xX][\w]'): 'z'} regexes = [ re.compile(p) for p in patterns ] for regex in regexes: for match in re.finditer(regex, sentence): match_location = sentence.casefold().find('x', match.start(), match.end()) sentence = sentence.replace(sentence[match_location], patterns.get(regex.pattern), 1) return sentence ``` From what I figured it out, the only problem in the second function is the regex patterns. Could someone help me? EDIT: Sorry I forgot to tell that the regexes are looking for the different x characters in a string, and replace an X in the beggining of a word for a 'Z', in the middle or end of a word for 'cks' and if it is a lone 'x' char replace with 'ecks'
2021/04/15
[ "https://Stackoverflow.com/questions/67113324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14244437/" ]
``` my_data$final <- my_data$start - cumsum(my_data$change) ```
``` library(tidyverse) my_data %>% mutate(attempt = accumulate(change, ~ .x - .y, .init = start[1])[-1]) ``` Note: `accumulate` is from the `purrr` library that's part of the `tidyverse`. It also has a `.dir` argument where you can go `"forward"` or `"backward"`. Or in base `R` using `Reduce`: ``` within(my_data, attempt <- Reduce("-", change, init = start[1], accumulate = T)[-1]) ``` `Reduce` has an argument `right` that can also do the computation forwards or backwards. **Output** ``` age_grp start change final_outcome attempt 1 10 0.42 0.020 0.400 0.400 2 9 0.42 0.033 0.367 0.367 3 8 0.42 0.029 0.338 0.338 4 7 0.42 0.031 0.307 0.307 5 6 0.42 0.027 0.280 0.280 6 5 0.42 0.032 0.248 0.248 7 4 0.42 0.032 0.216 0.216 8 3 0.42 0.030 0.186 0.186 9 2 0.42 0.027 0.159 0.159 10 1 0.42 0.034 0.125 0.125 ```
67,113,324
I made a function that replaces multiple instances of a single character with multiple patterns depending on the character location. There were two ways I found to accomplish this: 1. This one looks horrible but it works: def xSubstitution(target\_string): ``` while target_string.casefold().find('x') != -1: x_finded = target_string.casefold().find('x') if (x_finded == 0 and target_string[1] == ' ') or (target_string[x_finded-1] == ' ' and ((target_string[-1] == 'x' or 'X') or target_string[x_finded+1] == ' ')): target_string = target_string.replace(target_string[x_finded], 'ecks', 1) elif (target_string[x_finded+1] != ' '): target_string = target_string.replace(target_string[x_finded], 'z', 1) else: target_string = target_string.replace(target_string[x_finded], 'cks', 1) return(target_string) ``` 2. This one technically works, but I just can't get the regex patterns right: import re def multipleRegexSubstitutions(sentence): ``` patterns = {(r'^[xX]\s'): 'ecks ', (r'[^\w]\s?[xX](?!\w)'): 'ecks', (r'[\w][xX]'): 'cks', (r'[\w][xX][\w]'): 'cks', (r'^[xX][\w]'): 'z',(r'\s[xX][\w]'): 'z'} regexes = [ re.compile(p) for p in patterns ] for regex in regexes: for match in re.finditer(regex, sentence): match_location = sentence.casefold().find('x', match.start(), match.end()) sentence = sentence.replace(sentence[match_location], patterns.get(regex.pattern), 1) return sentence ``` From what I figured it out, the only problem in the second function is the regex patterns. Could someone help me? EDIT: Sorry I forgot to tell that the regexes are looking for the different x characters in a string, and replace an X in the beggining of a word for a 'Z', in the middle or end of a word for 'cks' and if it is a lone 'x' char replace with 'ecks'
2021/04/15
[ "https://Stackoverflow.com/questions/67113324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14244437/" ]
If we need the same output as in `final_outcome` ``` library(dplyr) my_data %>% mutate(attempt = start - cumsum(change)) %>% arrange(age_grp) ``` -output ``` # age_grp start change final_outcome attempt #1 1 0.42 0.034 0.125 0.125 #2 2 0.42 0.027 0.159 0.159 #3 3 0.42 0.030 0.186 0.186 #4 4 0.42 0.032 0.216 0.216 #5 5 0.42 0.032 0.248 0.248 #6 6 0.42 0.027 0.280 0.280 #7 7 0.42 0.031 0.307 0.307 #8 8 0.42 0.029 0.338 0.338 #9 9 0.42 0.033 0.367 0.367 #10 10 0.42 0.020 0.400 0.400 ```
``` my_data$final <- my_data$start - cumsum(my_data$change) ```
41,155,262
I have a JSON object in string that looks like `'{"key1":"value1", "key2": "value2", "key3": "value3"}'` I can use `json.loads` to make that into a JSON object, but when I try to print it in HTML, it prints the entire JSON object like `{"key1":"value1", "key2": "value2", "key3": "value3"}` my function looks like: ``` def jsonPretty(json_string): return json.loads(json_string) ``` and in HTML/Django: ``` {{kvpair|jsonLoadsPretty}} ``` However I want it to print `key1 value1 key2 value2 key3 value3` The format can vary a little, but I want each key-value pair to separate by a `\n`, and the brackets should be removed. What would be the best way of doing this? EDIT: I'm using `{% with kvpair|jsonPretty as kvjson %}` before running a for loop with ``` {% for k, v in kvjson.items %} <p> {{k}} {{v}}</p> ``` and now it works fine. Thanks for @Andrey Shipilov 's help!
2016/12/15
[ "https://Stackoverflow.com/questions/41155262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3450594/" ]
``` {% for key, value in kvpair %} <p>{{ key }} {{ value }}</p> {% endfor%} ``` <https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#for>
works {% for key, value in kvpair.**items** %}
23,438,364
Basically my question is whether or not there is way to validate a non-root element according to a given XSD schema. I am currently working on some legacy code where we have some C++ classes that generate XML elements in string format. I was thinking about a way to unit test these classes by verifying the generated XML (I'm using Xerces C++ under the hood). The problem is that I can't reference an element from another schema different from the root. This is a more detailed description of what I'm doing: I have a class called BooGenerator that generates a 'booIsNotRoot' element defined in 'foo.xsd'. Note that 'boo' is not the root element :-) I have created a test.xsd schema, which references 'booIsNotRoot' in the following way: ``` <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://acme/2014/test" xmlns:foo="http://acme/2014/foo" targetNamespace="http://acme/2014/test" elementFormDefault="qualified"> <xsd:import namespace="http://acme/2014/foo" schemaLocation="foo.xsd"/> <xsd:complexType name="TestType"> <xsd:choice minOccurs="1" maxOccurs="1"> <xsd:element ref="foo:booIsNotRoot"/> </xsd:choice> </xsd:complexType> <xsd:element name="test" type="TestType"/> </xsd:schema> ``` Then I wrap the string generated by BooGenerator with a test element: ``` <test xmlns="xmlns="http://acme/2014/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:foo="http://acme/2014/foo xsi:schemaLocation="http://acme/2014/test test.xsd"> (code generated by BooGenerator prefixed with 'foo') </test> ``` but as I said before it doesn't work. If I reference the root element in foo.xsd it works. So I wonder if there is a way to work around this. Thanks in advance.
2014/05/02
[ "https://Stackoverflow.com/questions/23438364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1192525/" ]
``` Basically my question is whether or not there is way to validate a non-root element according to a given XSD schema. ``` Theoretically speaking, yes, [Section 5.2 Assessing Schema-Validity](http://www.w3.org/TR/xmlschema-1/#validation_outcome) of the XSD Recommendation allows for non-root element validity assessment. (Credit and thanks to [C. M. Sperberg-McQueen](https://stackoverflow.com/users/1477421/c-m-sperberg-mcqueen) for [pointing this out](https://stackoverflow.com/a/23464674/290085).) Practically speaking, no, not directly. XML Schema tools tend to validate against XML documents — not selected, individual elements — and XML documents must have a single root element. Perhaps you might embed the element you wish to validate within a rigged context that simulates the element's ancestry up to the proper root element for the document. > > If I reference the root element in foo.xsd it works. > > > The root element in foo.xsd had better be `xsd:schema`, actually. You probably mean to say > > If I reference an element **defined globally (under `xsd:schema`)** in foo.xsd it works. > > > That is also how `@ref` is defined to work in XML Schema — it cannot reference locally defined elements such as `foo:booIsNotRoot`. Furthermore, *any* globally defined element can serve as a root element. (In fact, *only* globally defined elements can serve as a root element.) So, your options include: 1. Rig a valid context in which to test your targeted element. 2. Make your targeted element globally defined in its XSD. 3. Identify an implementation-specific interface to your XSD validator that provides element-level validation.
A very late answer, but schema-aware XSLT and XQuery both have ways of validating an arbitrary element. In XSLT, `<xsl:copy-of select="//some-element" validation="strict"/>`. In XQuery, `validate strict {//some-element}`.
23,438,364
Basically my question is whether or not there is way to validate a non-root element according to a given XSD schema. I am currently working on some legacy code where we have some C++ classes that generate XML elements in string format. I was thinking about a way to unit test these classes by verifying the generated XML (I'm using Xerces C++ under the hood). The problem is that I can't reference an element from another schema different from the root. This is a more detailed description of what I'm doing: I have a class called BooGenerator that generates a 'booIsNotRoot' element defined in 'foo.xsd'. Note that 'boo' is not the root element :-) I have created a test.xsd schema, which references 'booIsNotRoot' in the following way: ``` <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://acme/2014/test" xmlns:foo="http://acme/2014/foo" targetNamespace="http://acme/2014/test" elementFormDefault="qualified"> <xsd:import namespace="http://acme/2014/foo" schemaLocation="foo.xsd"/> <xsd:complexType name="TestType"> <xsd:choice minOccurs="1" maxOccurs="1"> <xsd:element ref="foo:booIsNotRoot"/> </xsd:choice> </xsd:complexType> <xsd:element name="test" type="TestType"/> </xsd:schema> ``` Then I wrap the string generated by BooGenerator with a test element: ``` <test xmlns="xmlns="http://acme/2014/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:foo="http://acme/2014/foo xsi:schemaLocation="http://acme/2014/test test.xsd"> (code generated by BooGenerator prefixed with 'foo') </test> ``` but as I said before it doesn't work. If I reference the root element in foo.xsd it works. So I wonder if there is a way to work around this. Thanks in advance.
2014/05/02
[ "https://Stackoverflow.com/questions/23438364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1192525/" ]
Yes, it's entirely possible. XSD validation is defined as starting at some node in an XML document and validating it (which normally entails validating all of its descendants), so a request to validate a particular element against a specified element declaration or type definition is perfectly coherent. How you go about conveying such a request to an XSD validator is implementation-specific (and XSD does not prescribe a particular API or command-line interface, so conforming XSD validators are not obligated to support all of the methods of starting a validation episode defined in section 5.2 of the XSD spec); you will have to consult the implementation's documentation. I believe the most common way of supporting such validation is to call a method in the implementation's XSD library with appropriate XML element, schema, and type definition or element declaration objects. I have not seen any command-line interfaces to XSD validators that support starting validation elsewhere than at the root.
A very late answer, but schema-aware XSLT and XQuery both have ways of validating an arbitrary element. In XSLT, `<xsl:copy-of select="//some-element" validation="strict"/>`. In XQuery, `validate strict {//some-element}`.
10,735,381
I have some Data coming out of my DB Model. What I want to do is get the total amount of the PAYMENTS\_total and then times it by VAT (0.20) I'm assuming I need to creat some sort of FOR loop somewhere, But not too sure where? My Code for the controller is : ``` function vat_list() { if(isset($_POST['search_date'])) { $search_date = $this->input->post('search_date', TRUE); } else { $search_date = date('D j M Y', strtotime('today - 7 days')) . ' to ' . date('D j M Y'); } $my_result_data = $this->Invoices_model->read_vat($this->viewinguser->BUSINESSES_id, $search_date); $my_results = $my_result_data->result(); $vat_total = $my_results[0]->PAYMENTS_total; $vat_total = number_format($my_results[0]->PAYMENTS_total, 2, '.', '') * 0.20; $this->template->set('title', 'View VAT Reports'); $this->template->set('subtitle', $search_date); $this->template->set('vat_items', $my_results); $this->template->set('vat_total', $vat_total); $this->template->build('accounts/invoices/vat_list'); } ``` Thanks
2012/05/24
[ "https://Stackoverflow.com/questions/10735381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265431/" ]
**EDIT** Don't do this - don't use floating point arithmetic for dealing with monetary calculations. Use something that implements fixed-point (decimal) data types, there are several libraries available for this, such as <https://github.com/mathiasverraes/money> or <https://github.com/sebastianbergmann/money>. The original answer is left here for historical purposes only. --- Without knowing the structure of your `$my_results` array I can't say for sure, but I'm guessing this is what you're after: ``` // ... $my_results = $my_result_data->result(); // The VAT rate (you never know, it *might* go down at some point before we die) $vatPercent = 20; // Get the total of all payments $total = 0; foreach ($my_results as $result) { $total += $result->PAYMENTS_total; } // Calculate the VAT on the total $vat = $total * ($vatPercent / 100); // The total including VAT $totalIncVat = $total + $vat; // You can now number_format() to your hearts content $this->template->set('title', 'View VAT Reports'); // ... ```
Try this: ``` $my_results = $my_result_data->result(); foreach ($my_results as $result) { number_format($result->PAYMENTS_total, 2, '.', '') * 0.20; } ``` The result of number\_format can be returned back into $result\a new array\etc.
261,967
> > Power can be murder to resist. > > > This is the tagline of the novel and film *The Firm*. What does it mean for something to "be murder to resist"?
2015/07/24
[ "https://english.stackexchange.com/questions/261967", "https://english.stackexchange.com", "https://english.stackexchange.com/users/130356/" ]
"Murder to " do something means that it is very very hard. For example "That mountain is murder to climb", or "That course is murder to get an A in". In this case the tag is playing on the literal sense of murder also.
this is idiomatic and it means "Power can be very difficult to resist", which in turn means "When offered power, it can be very difficult to refuse to take it." 'Power' in this context means having influence over someone or something, rather than electrical power etc. The film also involves the crime of murder, so there is a play on words. Presumable the taking and exercise of power involves murder.
58,549,235
I can understand why `10 % "test"` returns `NaN`... because "test" is converted to a number first which gives `NaN` and then any subsequent arithmetic operation involving `NaN` results in `NaN` too. But why does ``` 10 % "0" ``` return `NaN` ? `"0"` is usually converted to a number as `0` e.g. in `1 * "0"`. If I try `10 / "0"` this gives `Infinity` which also makes sense. So... why does that expression `10 % "0"` return `NaN` ?! Any logic behind this?
2019/10/24
[ "https://Stackoverflow.com/questions/58549235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300597/" ]
Your guess is right, in all the *number only* operators, if used in strings, Javascript will try to convert them in numbers. The same also happens with the remainder operator: ```js const x = "10"%"3"; console.log('10 % 3 = ' + x); ``` So why you get `NaN` evaluating `10%"0"`? Well, it will be converted to `10%0`, but the remainder operator has no particualr meaning if used on 0 (you can't divide by 0 in first instance). So you get NaN: ```js const x = 10 % 0; // numeric only operation console.log('10 % 0 = ' + x); // NaN, the above operation has no meaning ```
`10 % 0` also returns `NaN` because you're asking what's the remainder when you divide by 0, and there's no meaningful answer to that.
55,021,817
i am finding to difficult to add values to list. i did many research but none it seems working. please find my below codes ``` public class Test(){ List <String> list=new ArrayList<>(String); // global public Object method1(){ // here am adding the values to list } String method2(){ if(list.Contains("somethig")) //true} } ``` when i call method2 directly through junit, the list is empty. how can i add values to list in junit? this is where exactly am difficult to add values. i tried below approcah but its not working. **it throws null pointer exception** ``` List<Test> obj=new ArrayList<Test>(); Test cObject=Mockito.mock(Test.class); cObject.list.add("something"); //getting error in this line obj.add(cObject); ``` how can i solve the problem without refactoring my code? where am i making mistakes?
2019/03/06
[ "https://Stackoverflow.com/questions/55021817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11022960/" ]
Try replacing the following lines of code : ``` let data8 = data["latitude"] as? [Double] let data9 = data["longitude"] as? [Double] ``` *Cause: Accessing data with wrong keys*
have you tried like below? ``` let data8 = data["latitude"] as? [Double] let data9 = data["longitude"] as? [Double] ``` Actually you are accessing data with wrong keys... "latitude" , "longitude" are valid keys but you are retrieving with "Latitude" , "Longitude" which does not exist in your data snapshot **Note** Please check when storing data you are sending it in form of array of double.
16,930,978
If I start a IronPyThon Engine in a C# thread, the python script will start a number of threads. However, when I kill the C# thread, all of the threads in the python script are still running. How can I kill all of the threads in the Python script?
2013/06/05
[ "https://Stackoverflow.com/questions/16930978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413174/" ]
The simple Idea will be to start it as a `Process`, after you kill the `Process` every `Thread` of it will also be killed.
If you're sure you want to kill them, what you do is walk the process list and check each process's parent ID. If the parent ID is the same as the ID of the IronPython process that you started, then you kill it. This will kill all of the threads associated with that process. Something like this, where processes is the full array of Processes and parent is the IronPython process that you started: ``` private static void killProcessAndChildProcesses(Process[] processes, Process parent) { foreach (Process p in processes) { if (p.GetParentProcessId() == parent.Id) { p.Kill(); } } parent.Kill() } ``` If you're concerned about the IP child processes spawning processes of their own, you will need to convert this into a recursive solution.
16,930,978
If I start a IronPyThon Engine in a C# thread, the python script will start a number of threads. However, when I kill the C# thread, all of the threads in the python script are still running. How can I kill all of the threads in the Python script?
2013/06/05
[ "https://Stackoverflow.com/questions/16930978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413174/" ]
The simple Idea will be to start it as a `Process`, after you kill the `Process` every `Thread` of it will also be killed.
1. If your thread loops executing something on each iteration, you can set a volatile boolean flag such that it exits after finishing the current iteration (pseudocode because I'm not familiar with python): ``` while shouldExit = false // do stuff ``` 2. Then just set the flag to true when you want the thread to stop and it will stop the next time it checks the condition. If you cannot wait for the iteration to finish and need to stop it immediately, you could go for Thread.Abort, but make absolutely sure that there is no way you can leave open file handles, sockets, locks or anything else like this in an inconsistent state.
16,930,978
If I start a IronPyThon Engine in a C# thread, the python script will start a number of threads. However, when I kill the C# thread, all of the threads in the python script are still running. How can I kill all of the threads in the Python script?
2013/06/05
[ "https://Stackoverflow.com/questions/16930978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413174/" ]
The simple Idea will be to start it as a `Process`, after you kill the `Process` every `Thread` of it will also be killed.
You can certainty do it in the reverse way. Since I don't know python I'll share the idea only. * Set a named event in the system (you are in windows, its really simple in c#, Search for `Mutex`) * share the name of the named event with your python main thread * In the main python thread set a termination flag, accessible by worker-python-threads * Set worker-python-threads to monitor this flag occasionaly * In the main python thread also, begin an infinite loop like below * Set the named event in the c# thread whenever you want them to die Pseudocode: ``` while (Not(isNamedEventSet) && otherThreadsStillBusy) { // Do some magic to check the status of the event isNamedEventSet = ... // rest for a while, // there is nothing better than a nap while other threads do all the hard work Sleep(100) } ``` I've done similar scenarios between c#/c++ and it has been a success in all cases till now. I hope it fits python though..
923,266
The result of a hypergeometric distribution question that I posted about [earlier this evening](https://math.stackexchange.com/questions/923163/hypergeometric-rv-what-is-the-sample-population) is what follows: $$\frac{{30 \choose 10}{20 \choose 5}}{{50 \choose 15}}$$ This becomes: $$\frac{\frac{30!}{10!20!}\frac{20!}{5!15!}}{ \frac{50!}{15!35!}}$$ $$\frac{30! \cdot 35!}{10!\cdot5!\cdot50!}$$ $$\frac{30! \cdot 35!}{10!\cdot5!\cdot50!}$$ I see that I can, for example, cancel out 35! on the numerator and then that makes the 50! become $50\cdot49\cdots36$, so you get: $$\frac{30!}{10!\cdot5!\cdot(50\cdot49\cdots36)}$$ and subsequently you can do: $$\frac{(30\cdot29\cdots11)}{5!\cdot(50\cdot49\cdots36)}$$, but is there some way to compute these if I didn't have a computer or a long time to perform the arithmetic? I know there are a few expansions but they seemed to be not particularly helpful either... Thanks
2014/09/08
[ "https://math.stackexchange.com/questions/923266", "https://math.stackexchange.com", "https://math.stackexchange.com/users/11086/" ]
For any ring $A$, commutative, with $1$, $GL(2,A)$ is the set of $2\times 2$ matrices with elements in $A$ with determinant an invertible element of $A$. For $A= \mathbb{Z}$ we get $GL(2,\mathbb{Z})$ the set of $2\times 2$ matrices with integral elements and determinant $\pm 1$. For $A=F$ a field we get us $GL(2,F)$ the $2\times 2$ matrices with elements in $F$ and determinant $\ne 0$. So yes,$\ GL(2,A)$ is a group.
The [general linear group](http://en.wikipedia.org/wiki/General_linear_group) $GL(2,\mathbb{Z})$ [of order 2 over the integers](http://groupprops.subwiki.org/wiki/General_linear_group:GL(2,Z)) is a proper subset of the $2\times 2$ integer matrices that are invertible as real or rational matrices. A $2\times 2$ matrix with integer entries may be invertible (nonzero determinant) but the inverse will have integer entries only if the determinant is $\pm 1$. The larger set of matrices do form [a cancellative monoid](http://en.wikipedia.org/wiki/Monoid). **Added:** Using the fact that determinant of a product is the product of determinants, one can easily show that for an integer $n\times n$ matrix to have an inverse that is also an *integer* $n\times n$ matrix the determinant must be an integer that is a unit, i.e. $\pm 1$. That is, if $BC = I$, then $|B| |C| = |I| = 1$, and if $C$ has integer entries, $|C|$ must be an integer. This easily generalizes to the case of entries restricted to a commutative ring $R$ with identity, in that the determinants must be units in the ring if the matrix inverse is to have entries in the ring $R$.
55,018,918
I am currently working on a project, where I am creating a feature model out of Xtext grammar. My task is to transform grammar syntax into a CSV file importable into eclipse plug-in pure::variants. Feature model is basicaly tree of features. These features are different types ( mandatory, optional, alternative etc. ). For constructing the tree, I am using generated ecore meta model of my xtext grammar syntax. This file ( .ecore ) is basically a XML file with objects of the grammar. It is consistent, simple and easy to create tree out of. My problem is, that I need to assign types ( mandatory, alternative etc. ) to the nodes of my created tree. These types of features correspond to a cardinality operators. These operators are written in xtext grammar like this: ´(no operator)´, ´?´, ´\*´ and ´+´ ( this can be seen in xtext user manual section 2.1.3 <https://www.eclipse.org/Xtext/documentation/1_0_1/xtext.pdf>). Problem is, that these cardinalities of xtext grammar don't seem to be anywhere to find. I thought that they would appear in .ecore or .genmodel files, but there are no cardinalities at all. I imagine that if xtext is able to check and control these cardinalities, it has to have some kind of meta model, where these cardinalities can be seen and are easily gettable ( something like .xml file similiar to .ecore or .genmodel file). So my question is: Is there some kind of xtext generated file, which contains these cardinalities? If there is not, I would have to somehow get these cardinalities out of grammar itself, but it would be unneccessarily time consuming and complicated, maybe even impossible, because written grammar doesn't fully correspond with ecore metamodel I am getting my feature tree out of and is really complex. Only generated file I was able to find, which contains something "maybe useful" is generated file XXXXGrammarAccess.java ( XXXX stands for name of the grammar ), which is complex generated file, with a lot of library depedencies and I have no idea how to get these cardinalities out of that or if it is even possible. I imagine that there is a possibility, because this file uses a lot of IGrammarAccess methods, such as getRule(), getKeyword() and more, but I am not able to use this file, or print something out of it, because it is a generated file and I am not able to run it on itself. If there is not some kind of meta model I am looking for, is there any possibility to somehow get these cardinalities different way during generating? Thank you very much for your answers.
2019/03/06
[ "https://Stackoverflow.com/questions/55018918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8198679/" ]
try this: ``` def main(): w= [1,2,3] x= [4,5,6] y= [7,8,9] z= [10,11,12] print map(list, zip(w, x, y, z)) ``` > > output : [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] > > >
What you want, is a transposed matrix like: ``` M = [w,x,y,z] [[row[i] for row in M] for i in range(len(w))] -> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] ```
55,018,918
I am currently working on a project, where I am creating a feature model out of Xtext grammar. My task is to transform grammar syntax into a CSV file importable into eclipse plug-in pure::variants. Feature model is basicaly tree of features. These features are different types ( mandatory, optional, alternative etc. ). For constructing the tree, I am using generated ecore meta model of my xtext grammar syntax. This file ( .ecore ) is basically a XML file with objects of the grammar. It is consistent, simple and easy to create tree out of. My problem is, that I need to assign types ( mandatory, alternative etc. ) to the nodes of my created tree. These types of features correspond to a cardinality operators. These operators are written in xtext grammar like this: ´(no operator)´, ´?´, ´\*´ and ´+´ ( this can be seen in xtext user manual section 2.1.3 <https://www.eclipse.org/Xtext/documentation/1_0_1/xtext.pdf>). Problem is, that these cardinalities of xtext grammar don't seem to be anywhere to find. I thought that they would appear in .ecore or .genmodel files, but there are no cardinalities at all. I imagine that if xtext is able to check and control these cardinalities, it has to have some kind of meta model, where these cardinalities can be seen and are easily gettable ( something like .xml file similiar to .ecore or .genmodel file). So my question is: Is there some kind of xtext generated file, which contains these cardinalities? If there is not, I would have to somehow get these cardinalities out of grammar itself, but it would be unneccessarily time consuming and complicated, maybe even impossible, because written grammar doesn't fully correspond with ecore metamodel I am getting my feature tree out of and is really complex. Only generated file I was able to find, which contains something "maybe useful" is generated file XXXXGrammarAccess.java ( XXXX stands for name of the grammar ), which is complex generated file, with a lot of library depedencies and I have no idea how to get these cardinalities out of that or if it is even possible. I imagine that there is a possibility, because this file uses a lot of IGrammarAccess methods, such as getRule(), getKeyword() and more, but I am not able to use this file, or print something out of it, because it is a generated file and I am not able to run it on itself. If there is not some kind of meta model I am looking for, is there any possibility to somehow get these cardinalities different way during generating? Thank you very much for your answers.
2019/03/06
[ "https://Stackoverflow.com/questions/55018918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8198679/" ]
try this: ``` def main(): w= [1,2,3] x= [4,5,6] y= [7,8,9] z= [10,11,12] print map(list, zip(w, x, y, z)) ``` > > output : [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] > > >
If all of the list's length are the same then: ``` result = [] for i in range(len(w)): result.append([w[i],x[i],y[i],z[i]]) ```
6,379,919
I'm trying to automate a secure application(with useragent - iphone) which asks for authentication when i open the site. I tried giving the credentials in the URL itself to bypass the authentication but it pops up a dialogbox for confirmation which i'm unable to handle it through code. ```java FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("general.useragent.override", "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1" + "(KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3)"); WebDriver driver = new FirefoxDriver(profile); String site = "http://akamai:[email protected]"; driver.get(site); ``` Any help on this is highly appreciated. Thanks, Bhavana
2011/06/16
[ "https://Stackoverflow.com/questions/6379919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745995/" ]
Mozilla blocks fishing attempts. Did you check [Network.http.phishy-userpass-length](http://kb.mozillazine.org/Network.http.phishy-userpass-length)? By the way, according to [Selenium's issue 34#8](http://code.google.com/p/selenium/issues/detail?id=34#c8), this should work: ```java FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("network.http.phishy-userpass-length", 255); driver = new FirefoxDriver(profile); driver.get("http://username:[email protected]/"); ``` Note: this question is almost the same as [BASIC Authentication in Selenium 2 - set up for FirefoxDriver, ChromeDriver and IEdriver](https://stackoverflow.com/q/5672407/413020).
You can use Selenium's new WebDriver to enter information into a dialog box of that type. However I haven't done it.
68,164
I am trying to self-study a bit of philosophy. I am an applied mathematician by trade, and am therefore drawn to Kant's work on the limits of human knowledge, in particular his exchange with Hume. I was wondering if anybody could clarify a point for me: As far as I understand it, Kant agrees with Hume to the extent that we can never know the true nature of things such as causation, which Hume argues may not exist at all. Now, Kant takes this skepticism a step further by saying that we don't even observe the "real world" at all, only a representation of it in our minds. However, in doing so, he somehow saves the existence of causation. This is where I could use some help. Here is my first attempt to understand what Kant is saying: What Kant is saying is that the mind has certain methods of structuring the data it receives ("forms of intuition") in order to paint our mental pictures. These include notions of space, time, causation, etc. From here, he uses a sort of Descartes "I think therefore I am" to these forms of intuition. That is, causation is a fundamental tool for structuring how I perceive the world, therefore causation exists, at least in this sense. Is this a rough idea of what is going on? Thanks in advance!
2019/11/02
[ "https://philosophy.stackexchange.com/questions/68164", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/34713/" ]
Perhaps the major difference is that Hume derives from experience whatever categories he uses - or supposes that he does so. To take causation as a star example: Hume derives the category of causation from experience in the following way. When event A is prior to event B (priority); when A and B are close in space and time (contiguity); and when A-type events are regularly followed by B-type events (constant conjunction): then by the association of ideas we assume that event A causes event B. This is Hume's essential picture. Kant's picture is radically different. For Kant, we do not *derive* the category of causation from experience. Rather, it is a part of the cognitive apparatus of the mind that we *bring to* experience. It is only by means of an inherent network of categories, such as causation, that coherent experience is possible for us. In other words, for Kant, Hume is precisely wrong. There is not, first experience and then the derivation of the category of causation from experience. On the contrary there is first the category of causation and this structures (or plays a role in structuring) experience in such a way that we can even think of A-type or B-type events. Causation, involving (unless we get into really technical science) the *priority* of the cause to the effect, and *contiguity*, closeness in space and time, between cause and effect, presuppose space and time: these 'forms of intuition' (or roughly 'forms of representation') are not empirical in origin and we do not derive them from experience. On the contrary, again, unless we *already* had these forms of intuition we could not order or locate events in time and space. This is a highly brief account, with endless details missing, but it may serve to the fundamentally different approach between Hume and Kant as regards experience and the empirical.
The answer to "Is this [as you described it] a rough idea of what is going on [with Kantiam metaphysics] is an unequivocal: Yes. Though your characterization "From here, he uses a sort of Descartes "I think therefore I am" to these forms of intuition" is ambiguous -- but if if what you mean is this and only this instantiates thought as we homo sapiens know it, then yes. Kant identifies the forms (innate intuitions) of space and time, and twelve pure concepts of the understanding (ontological predicates): unity, plurality, and totality for concept of quantity; reality, negation, and limitation, for the concept of quality; inherence and subsistence, cause and effect, and community for the concept of relation; and possibility-impossibility, existence-nonexistence, and necessity and contingency for the concept of modality.
68,164
I am trying to self-study a bit of philosophy. I am an applied mathematician by trade, and am therefore drawn to Kant's work on the limits of human knowledge, in particular his exchange with Hume. I was wondering if anybody could clarify a point for me: As far as I understand it, Kant agrees with Hume to the extent that we can never know the true nature of things such as causation, which Hume argues may not exist at all. Now, Kant takes this skepticism a step further by saying that we don't even observe the "real world" at all, only a representation of it in our minds. However, in doing so, he somehow saves the existence of causation. This is where I could use some help. Here is my first attempt to understand what Kant is saying: What Kant is saying is that the mind has certain methods of structuring the data it receives ("forms of intuition") in order to paint our mental pictures. These include notions of space, time, causation, etc. From here, he uses a sort of Descartes "I think therefore I am" to these forms of intuition. That is, causation is a fundamental tool for structuring how I perceive the world, therefore causation exists, at least in this sense. Is this a rough idea of what is going on? Thanks in advance!
2019/11/02
[ "https://philosophy.stackexchange.com/questions/68164", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/34713/" ]
**Hume** was deeply skeptical of metaphysics. For a non-philosopher this includes topics such as being, essence, substance, space, time, the self, and causation. For example: in *A Treatise of Human Nature* Hume argues that we have no innate concept of Cause and Effect (C\E) and that C\E is not rationally known but instead we develop the concept of it through the near universal juxtaposition of two events. For Hume our knowledge of metaphysical subjects is not rational, but is caused by non-rational mechanisms in the mind and we do rely on them, especially time, space, C\E, and the self. But they are not uniquely privileged and thus cannot provide certainty for our beliefs. Also,they may properly be subjected to skeptical critique. This has significant implications for both science and religion. And the religious authorities of his day saw his work on causation as an attack on the foundations of religious belief. That was before he published his work on miracles, or his famous polemics against popular religion. **Kant** read at least books I & II of Hume's *Treatise*(in translation) but he was not entirely persuaded and wanted to save metaphysics. At least a little bit. Kant argued in *The Critique of Pure Reason* that for us to have an experience, the mind must impose certain structures on incoming sensory data. These impositions are "known" *a priori* (before experience) and thus are metaphysical, and to an extent privileged. There aren't many of these beliefs but they include time, extension (space), the self, and Cause and Effect. Kant also believed in universal and immutable laws, something Hume denied. Speaking broadly: Hume tried to trash metaphysics while Kant tried to save parts of it. Kant's theory of *a priori* truths --especially his theory of synthetic *a priori* truths-- is fundamentally incompatible with Hume's more empirical approach. Hume is traditionally seen as the more skeptical of the two. Also, Hume, before Kant, argued that we cannot get to the object-in-itself, even if he did not use that terminology. For Hume the mind operates on impressions and ideas. They start with sensory perceptions, but there is no guarantee that this are correct or accurate. Here is an exert from Hume's *Treatise* Book I, Part II, Section VI: *The Idea of existence and of external existence.* "nothing is really present with the mind but its perceptions or impressions and ideas, and that external objects become known to us only by those perceptions they occasion [...] it follows that tis impossible for us so much as to conceive or form an idea or anything specifically different from ideas and impressions [...] the farthest we can go towards a conception of external objects ...is to form a relative idea of them without pretending to comprehend the related objects." You aren't a lone in struggling with Kant. He was a terrible writer. I once heard a Kantian say that every English translation of the Critique sucks, because the German sucks. Despite that, make sure you are reading a decent translation. Guyer/wood is recommended or Pluhar. Kemp Smith is considered dated at this point, but his translation was the standard for at least a generation or two of Kantian scholars. Reference to secondary literature may help. *The Blackwell Companion to Kant* may be a good place to start. Or the [Stanford Encyclopedia of Philosophy](https://plato.stanford.edu/)
The answer to "Is this [as you described it] a rough idea of what is going on [with Kantiam metaphysics] is an unequivocal: Yes. Though your characterization "From here, he uses a sort of Descartes "I think therefore I am" to these forms of intuition" is ambiguous -- but if if what you mean is this and only this instantiates thought as we homo sapiens know it, then yes. Kant identifies the forms (innate intuitions) of space and time, and twelve pure concepts of the understanding (ontological predicates): unity, plurality, and totality for concept of quantity; reality, negation, and limitation, for the concept of quality; inherence and subsistence, cause and effect, and community for the concept of relation; and possibility-impossibility, existence-nonexistence, and necessity and contingency for the concept of modality.
68,164
I am trying to self-study a bit of philosophy. I am an applied mathematician by trade, and am therefore drawn to Kant's work on the limits of human knowledge, in particular his exchange with Hume. I was wondering if anybody could clarify a point for me: As far as I understand it, Kant agrees with Hume to the extent that we can never know the true nature of things such as causation, which Hume argues may not exist at all. Now, Kant takes this skepticism a step further by saying that we don't even observe the "real world" at all, only a representation of it in our minds. However, in doing so, he somehow saves the existence of causation. This is where I could use some help. Here is my first attempt to understand what Kant is saying: What Kant is saying is that the mind has certain methods of structuring the data it receives ("forms of intuition") in order to paint our mental pictures. These include notions of space, time, causation, etc. From here, he uses a sort of Descartes "I think therefore I am" to these forms of intuition. That is, causation is a fundamental tool for structuring how I perceive the world, therefore causation exists, at least in this sense. Is this a rough idea of what is going on? Thanks in advance!
2019/11/02
[ "https://philosophy.stackexchange.com/questions/68164", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/34713/" ]
Perhaps the major difference is that Hume derives from experience whatever categories he uses - or supposes that he does so. To take causation as a star example: Hume derives the category of causation from experience in the following way. When event A is prior to event B (priority); when A and B are close in space and time (contiguity); and when A-type events are regularly followed by B-type events (constant conjunction): then by the association of ideas we assume that event A causes event B. This is Hume's essential picture. Kant's picture is radically different. For Kant, we do not *derive* the category of causation from experience. Rather, it is a part of the cognitive apparatus of the mind that we *bring to* experience. It is only by means of an inherent network of categories, such as causation, that coherent experience is possible for us. In other words, for Kant, Hume is precisely wrong. There is not, first experience and then the derivation of the category of causation from experience. On the contrary there is first the category of causation and this structures (or plays a role in structuring) experience in such a way that we can even think of A-type or B-type events. Causation, involving (unless we get into really technical science) the *priority* of the cause to the effect, and *contiguity*, closeness in space and time, between cause and effect, presuppose space and time: these 'forms of intuition' (or roughly 'forms of representation') are not empirical in origin and we do not derive them from experience. On the contrary, again, unless we *already* had these forms of intuition we could not order or locate events in time and space. This is a highly brief account, with endless details missing, but it may serve to the fundamentally different approach between Hume and Kant as regards experience and the empirical.
**Hume** was deeply skeptical of metaphysics. For a non-philosopher this includes topics such as being, essence, substance, space, time, the self, and causation. For example: in *A Treatise of Human Nature* Hume argues that we have no innate concept of Cause and Effect (C\E) and that C\E is not rationally known but instead we develop the concept of it through the near universal juxtaposition of two events. For Hume our knowledge of metaphysical subjects is not rational, but is caused by non-rational mechanisms in the mind and we do rely on them, especially time, space, C\E, and the self. But they are not uniquely privileged and thus cannot provide certainty for our beliefs. Also,they may properly be subjected to skeptical critique. This has significant implications for both science and religion. And the religious authorities of his day saw his work on causation as an attack on the foundations of religious belief. That was before he published his work on miracles, or his famous polemics against popular religion. **Kant** read at least books I & II of Hume's *Treatise*(in translation) but he was not entirely persuaded and wanted to save metaphysics. At least a little bit. Kant argued in *The Critique of Pure Reason* that for us to have an experience, the mind must impose certain structures on incoming sensory data. These impositions are "known" *a priori* (before experience) and thus are metaphysical, and to an extent privileged. There aren't many of these beliefs but they include time, extension (space), the self, and Cause and Effect. Kant also believed in universal and immutable laws, something Hume denied. Speaking broadly: Hume tried to trash metaphysics while Kant tried to save parts of it. Kant's theory of *a priori* truths --especially his theory of synthetic *a priori* truths-- is fundamentally incompatible with Hume's more empirical approach. Hume is traditionally seen as the more skeptical of the two. Also, Hume, before Kant, argued that we cannot get to the object-in-itself, even if he did not use that terminology. For Hume the mind operates on impressions and ideas. They start with sensory perceptions, but there is no guarantee that this are correct or accurate. Here is an exert from Hume's *Treatise* Book I, Part II, Section VI: *The Idea of existence and of external existence.* "nothing is really present with the mind but its perceptions or impressions and ideas, and that external objects become known to us only by those perceptions they occasion [...] it follows that tis impossible for us so much as to conceive or form an idea or anything specifically different from ideas and impressions [...] the farthest we can go towards a conception of external objects ...is to form a relative idea of them without pretending to comprehend the related objects." You aren't a lone in struggling with Kant. He was a terrible writer. I once heard a Kantian say that every English translation of the Critique sucks, because the German sucks. Despite that, make sure you are reading a decent translation. Guyer/wood is recommended or Pluhar. Kemp Smith is considered dated at this point, but his translation was the standard for at least a generation or two of Kantian scholars. Reference to secondary literature may help. *The Blackwell Companion to Kant* may be a good place to start. Or the [Stanford Encyclopedia of Philosophy](https://plato.stanford.edu/)
47,613,633
Hi all, I have pretty awfull query, that needs optimizing. I need to select all records where date of created matches NOW - 35days, but the minutes and seconds can be any. So I have this query here, its ugly, but working: Any optimisation tips are welcome! ``` SELECT * FROM outbound_email oe INNER JOIN (SELECT `issue_id` FROM `issues` WHERE 1 ORDER BY year DESC, NUM DESC LIMIT 0,5) as issues ON oe.issue_id = issues.issue_id WHERE year(created) = year( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND month(created) = month( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND day(created) = day( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND hour(created) = hour( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND campaign_id IN (SELECT id FROM campaigns WHERE initial = 1) ```
2017/12/02
[ "https://Stackoverflow.com/questions/47613633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2411192/" ]
So what I learnt in the process of debugging this issue was that: * During the creation of a Kubernetes Cluster you can specify permissions for the GCE nodes that will be created. * If you for example enable Datastore access on the cluster nodes during creation, you will be able to access Datastore directly from the Pods without having to set up anything else. * If your cluster node permissions are disabled for most things (default settings) like mine were, you will need to create an appropriate Service Account for each application that wants to use a GCP resource like Datastore. * Another alternative is to create a new node pool with the `gcloud` command, set the desired permission scopes and then migrate all deployments to the new node pool (rather tedious). So at the end of the day I fixed the issue by creating a Service Account for my application, downloading the JSON authentication key, creating a Kubernetes secret which contains that key, and in the case of Datastore, I set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of the mounted secret JSON key. This way when my application starts, it checks if the `GOOGLE_APPLICATION_CREDENTIALS` variable is present, and authenticates Datastore API access based on the JSON key that the variable points to. Deployment YAML snippet: ``` ... containers: - image: foo name: foo env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /auth/credentials.json volumeMounts: - name: foo-service-account mountPath: "/auth" readOnly: true volumes: - name: foo-service-account secret: secretName: foo-service-account ```
After struggling some hours, I was also able to connect to the datastore. Here are my results, most of if from [Google Docs](https://cloud.google.com/kubernetes-engine/docs/tutorials/authenticating-to-cloud-platform): 1. Create Service Account `gcloud iam service-accounts create [SERVICE_ACCOUNT_NAME]` 2. Get full iam account name `gcloud iam service-accounts list` The result will look something like this: `[SERVICE_ACCOUNT_NAME]@[PROJECT_NAME].iam.gserviceaccount.com` 3. Give owner access to the project for the service account `gcloud projects add-iam-policy-binding [PROJECT_NAME] --member serviceAccount:[SERVICE_ACCOUNT_NAME]@[PROJECT_NAME].iam.gserviceaccount.com --role roles/owner` 4. Create key-file `gcloud iam service-accounts keys create mycredentials.json --iam-account [SERVICE_ACCOUNT_NAME]@[PROJECT_NAME].iam.gserviceaccount.com` 5. Create `app-key` Secret `kubectl create secret generic app-key --from-file=credentials.json=mycredentials.json` This `app-key` secret will then be mounted in the deployment.yaml 6. Edit deyployment file deployment.yaml: ``` ... spec: containers: - name: app image: eu.gcr.io/google_project_id/springapplication:v1 volumeMounts: - name: google-cloud-key mountPath: /var/secrets/google env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /var/secrets/google/credentials.json ports: - name: http-server containerPort: 8080 volumes: - name: google-cloud-key secret: secretName: app-key ```
47,613,633
Hi all, I have pretty awfull query, that needs optimizing. I need to select all records where date of created matches NOW - 35days, but the minutes and seconds can be any. So I have this query here, its ugly, but working: Any optimisation tips are welcome! ``` SELECT * FROM outbound_email oe INNER JOIN (SELECT `issue_id` FROM `issues` WHERE 1 ORDER BY year DESC, NUM DESC LIMIT 0,5) as issues ON oe.issue_id = issues.issue_id WHERE year(created) = year( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND month(created) = month( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND day(created) = day( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND hour(created) = hour( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND campaign_id IN (SELECT id FROM campaigns WHERE initial = 1) ```
2017/12/02
[ "https://Stackoverflow.com/questions/47613633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2411192/" ]
So what I learnt in the process of debugging this issue was that: * During the creation of a Kubernetes Cluster you can specify permissions for the GCE nodes that will be created. * If you for example enable Datastore access on the cluster nodes during creation, you will be able to access Datastore directly from the Pods without having to set up anything else. * If your cluster node permissions are disabled for most things (default settings) like mine were, you will need to create an appropriate Service Account for each application that wants to use a GCP resource like Datastore. * Another alternative is to create a new node pool with the `gcloud` command, set the desired permission scopes and then migrate all deployments to the new node pool (rather tedious). So at the end of the day I fixed the issue by creating a Service Account for my application, downloading the JSON authentication key, creating a Kubernetes secret which contains that key, and in the case of Datastore, I set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of the mounted secret JSON key. This way when my application starts, it checks if the `GOOGLE_APPLICATION_CREDENTIALS` variable is present, and authenticates Datastore API access based on the JSON key that the variable points to. Deployment YAML snippet: ``` ... containers: - image: foo name: foo env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /auth/credentials.json volumeMounts: - name: foo-service-account mountPath: "/auth" readOnly: true volumes: - name: foo-service-account secret: secretName: foo-service-account ```
I was using a minimalistic Dockerfile like: ``` FROM SCRATCH ADD main / EXPOSE 80 CMD ["/main"] ``` which kept my go app in an indefinite "hanging" state when trying to connect to the GCP Datastore. After LOTS of playing I figured out that the SCRATCH Docker image might be missing certain environment tools / variables / libraries which the Google cloud library requires. Using this Dockerfile now works: ``` FROM golang:alpine RUN apk add --no-cache ca-certificates ADD main / EXPOSE 80 CMD ["/main"] ``` It does not require me to provide the google credentials environment variable. The library seems to automatically understand where it's running in (maybe from the context.Background() ?) and automatically uses a default service account which Google creates for you when you create your cluster on GKE.
47,613,633
Hi all, I have pretty awfull query, that needs optimizing. I need to select all records where date of created matches NOW - 35days, but the minutes and seconds can be any. So I have this query here, its ugly, but working: Any optimisation tips are welcome! ``` SELECT * FROM outbound_email oe INNER JOIN (SELECT `issue_id` FROM `issues` WHERE 1 ORDER BY year DESC, NUM DESC LIMIT 0,5) as issues ON oe.issue_id = issues.issue_id WHERE year(created) = year( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND month(created) = month( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND day(created) = day( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND hour(created) = hour( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND campaign_id IN (SELECT id FROM campaigns WHERE initial = 1) ```
2017/12/02
[ "https://Stackoverflow.com/questions/47613633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2411192/" ]
After struggling some hours, I was also able to connect to the datastore. Here are my results, most of if from [Google Docs](https://cloud.google.com/kubernetes-engine/docs/tutorials/authenticating-to-cloud-platform): 1. Create Service Account `gcloud iam service-accounts create [SERVICE_ACCOUNT_NAME]` 2. Get full iam account name `gcloud iam service-accounts list` The result will look something like this: `[SERVICE_ACCOUNT_NAME]@[PROJECT_NAME].iam.gserviceaccount.com` 3. Give owner access to the project for the service account `gcloud projects add-iam-policy-binding [PROJECT_NAME] --member serviceAccount:[SERVICE_ACCOUNT_NAME]@[PROJECT_NAME].iam.gserviceaccount.com --role roles/owner` 4. Create key-file `gcloud iam service-accounts keys create mycredentials.json --iam-account [SERVICE_ACCOUNT_NAME]@[PROJECT_NAME].iam.gserviceaccount.com` 5. Create `app-key` Secret `kubectl create secret generic app-key --from-file=credentials.json=mycredentials.json` This `app-key` secret will then be mounted in the deployment.yaml 6. Edit deyployment file deployment.yaml: ``` ... spec: containers: - name: app image: eu.gcr.io/google_project_id/springapplication:v1 volumeMounts: - name: google-cloud-key mountPath: /var/secrets/google env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /var/secrets/google/credentials.json ports: - name: http-server containerPort: 8080 volumes: - name: google-cloud-key secret: secretName: app-key ```
I was using a minimalistic Dockerfile like: ``` FROM SCRATCH ADD main / EXPOSE 80 CMD ["/main"] ``` which kept my go app in an indefinite "hanging" state when trying to connect to the GCP Datastore. After LOTS of playing I figured out that the SCRATCH Docker image might be missing certain environment tools / variables / libraries which the Google cloud library requires. Using this Dockerfile now works: ``` FROM golang:alpine RUN apk add --no-cache ca-certificates ADD main / EXPOSE 80 CMD ["/main"] ``` It does not require me to provide the google credentials environment variable. The library seems to automatically understand where it's running in (maybe from the context.Background() ?) and automatically uses a default service account which Google creates for you when you create your cluster on GKE.
11,568,187
I have the following tables: ``` tweets retweets ----------------- ---------------- user_id retweets user_id (etc...) ----------------- ---------------- 1 0 1 2 0 1 1 2 2 ``` I want to count the number of retweets per user and update tweets.retweets accordingly: ``` UPDATE users SET retweets = ( SELECT COUNT(*) FROM retweets WHERE retweets.user_id = users.user_id ) ``` I have been running this query two times, but it times out (on tables that are not that large). Is my query wring? Also see the SQL Fiddle (although it apparently doesn't allow `UPDATE` statements): <http://www.sqlfiddle.com/#!2/f591e/1>
2012/07/19
[ "https://Stackoverflow.com/questions/11568187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330271/" ]
This solution should be much faster than using subqueries for getting the count of tweets of each user (your correlated subquery will execute for ***each*** user): ``` UPDATE users a LEFT JOIN ( SELECT user_id, COUNT(1) AS retweet_count FROM retweets GROUP BY user_id ) b ON a.user_id = b.user_id SET a.retweets = COALESCE(b.retweet_count, 0) ```
If your retweets table is not changing dynamically why not to gather data at first and then update destination table like this: ``` create table retweets_hist AS SELECT COUNT(*) AS retweets,user_id FROM retweets group by user_id; ``` then ``` UPDATE users SET retweets = NVL( SELECT retweets FROM retweets_hist WHERE retweets_hist.user_id = users.user_id ),0) ``` If it is dynamic, then I think using triggers is better. The main issue here is **when there is a user which has never retweeted ever** counting it's retweets is time-consuming. In answer to your question, Yes counting takes a fraction but counting something which never existed take time! this is the problem! May this one would have better timing: ``` UPDATE users SET retweets = NVL( SELECT retweets FROM retweets WHERE retweets.user_id = users.user_id),0) WHERE EXISTS(select * FROM retweets WHERE retweets.user_id = users.user_id) ``` But then again you have to update **never retweets** to Zero. \*\*Keyword EXISTS is in Oracle I don't know if mysql supports it
3,826
I'm designing an Arduino style board with built-in LEDs for several of the pins. To simplify assembly of the board and save on components, I was wondering whether it would be safe for those LEDs to share a single resistor, as in this diagram: ![schematic](https://i.stack.imgur.com/jWXVT.png) Obviously, the power dissipated through the resistor (3mA per pin @ 3V) is not a real problem. The reason I was hesitating is that LEDs in a parallel configuration should not share resistors, but is it safe to think that separate microcontroller pins don't count as a common anode, even if both pins are high?
2014/08/17
[ "https://arduino.stackexchange.com/questions/3826", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/353/" ]
> > **Can** two LEDs attached to different pins share their resistor? > > > * **can** : yes * **should** : probably not Your resistor act here as a current limiter, say to *3mA* If you light one LED at a time, you give 3mA to *that* LED If you light 2 LEDs, you give 3mA for both of them (more of less 1.5mA each) If you light 3 LEDs, you give 3mA for all of them (*on average* 1mA each) Things are even a little bit more subtle, as different LED might have different forward voltage, so one LED might very well drain 10% more current than an other. As "Amps made LED bright", less Amp is less light. On LED light with that setup will give "full light on", and more LED you add, less would bright each one. --- As an edit to that answer, there is one case I might consider that arrangement for "multi-LED lighting". This is if you are [multiplexing your LEDs](http://en.wikipedia.org/wiki/Multiplexed_display) That is lighting only one at a time, but cycling fast enough from one LED to the next so that the human eye would *see* them all lit at once.
Your circuit is safe from the electronic viewpoint, so long as the LEDs used can withstand a back-emf of 4v or so. If only one LED is on at a time, all will be sweet. But if two or more are on, the brightness will drop and the brightness between LEDS will probably be inconsistent. The forward voltage drop of individual LEDS tend to vary a little, so one is likely to hog most of the available current. A separate resistor per LED is probably best.
2,935,229
I am considering generating a unique form token and storing it in a session, and embedding it as a hidden input in my forms. Could I make this work for pages containing multiple forms, is it still safe to use the same token for each form? I'm looking to detect bot requests on my website, can these form tokens really safely replace CAPTCHAs?
2010/05/29
[ "https://Stackoverflow.com/questions/2935229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138251/" ]
Apache is one of the most hardened software projects on the face of the planet. Finding a vulnerability in Apache's HTTPD would be no small feat and I recommend cutting your teeth on some easier prey. By comparison it is more common to see vulnerabilities in other HTTPDs such as this one in [Nginx](http://www.securityfocus.com/archive/1/511556) that I saw today (no joke). There have been other source code disclosure vulnerablites that are very similar, I would look at [this](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-0642) and here is [another](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-1587). [lhttpd](http://sourceforge.net/projects/lhttpd/) has been abandoned on sf.net for almost a decade and there are known buffer overflows that affect it, which makes it a fun application to test. When attacking a project you should look at what kind of vulnerabilities have been found in the past. Its likely that programmers will make the same mistakes again and again and often there are patterns that emerge. By following these patterns you can find more flaws. You should try searching vulnerablites databases such as [Nist's search for CVEs](http://web.nvd.nist.gov/view/vuln/search). One thing that you will see is that apache modules are most commonly compromised. A project like Apache has been heavily fuzzed. There are fuzzing frameworks such as [Peach](http://peachfuzzer.com/). Peach helps with fuzzing in many ways, one way it can help you is by giving you some nasty test data to work with. Fuzzing is not a very good approach for mature projects, if you go this route I would target [apache modules](http://sourceforge.net/search/?type_of_search=soft&words=%2Bapache+%2Bmod&search=Search) with as few downloads as possible. (Warning projects with *really* low downloads might be broken or difficult to install.) When a company is worried about secuirty often they pay a lot of money for an automated source analysis tool such as Coverity. The Department Of Homeland Security gave Coverity a ton of money to test open source projects and [Apache is one of them](http://scan.coverity.com/rung1.html). I can tell you first hand that I have found [a buffer overflow](http://www.milw0rm.com/exploits/8470) with fuzzing that Coverity didn't pick up. Coverity and other source code analysis tools like the [open source Rats](http://www.fortify.com/security-resources/rats.jsp) will produce a lot of false positives and false negatives, but they do help narrow down the problems that affect a code base. (When i first ran RATS on the Linux kernel I nearly fell out of my chair because my screen listed thousands of calls to strcpy() and strcat(), but when i dug into the code all of the calls where working with static text, which is safe.) Vulnerability resarch an exploit development is [a lot of fun](http://www.milw0rm.com/author/677). I recommend exploiting PHP/MySQL applications and exploring [The Whitebox](http://code.google.com/p/thewhitebox/). This project is important because it shows that there are some real world vulnerabilities that cannot be found unless you read though the code line by line manually. It also has real world applications (a blog and a shop) that are very vulnerable to attack. In fact both of these applications where abandoned due to security problems. A web application fuzzer like [Wapiti](http://wapiti.sourceforge.net/) or acuentix will rape these applications and ones like it. There is a trick with the blog. A fresh install isn't vulnerable to much. You have to use the application a bit, try logging in as an admin, create a blog entry and then scan it. When testing a web application application for sql injection make sure that error reporting is turned on. In php you can set `display_errors=On` in your php.ini. Good Luck!
Depending on what other modules you have hooked in, and what else activates them (or is it only too-large requests?), you might want to try some of the following: * Bad encodings - e.g. overlong utf-8 like you mentioned, there are scenarios where the modules depend on that, for example certain parameters. * parameter manipulation - again, depending on what the modules do, certain parameters may mess with them, either by changing values, removing expected parameters, or adding unexpected ones. * contrary to your other suggestion, I would look at data that is *just barely short enough*, i.e. one or two bytes shorter than the maximum, but in different combinations - different parameters, headers, request body, etc. * Look into [HTTP Request Smuggling](http://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf) (also [here](http://www.owasp.org/index.php/HTTP_Request_Smuggling) and [here](http://www.securiteam.com/securityreviews/5GP0220G0U.html)) - bad request headers or invalid combinations, such as multiple Content-Length, or invalid terminators, *might* cause the module to misinterpret the command from Apache. * Also consider gzip, chunked encoding, etc. It is likely that the custom module implements the length check and the decoding, out of order. * What about partial request? e.g requests that cause a 100-Continue response, or range-requests? * The fuzzing tool, [Peach](http://peachfuzzer.com/), recommended by @TheRook, is also a good direction, but don't expect great ROI first time using it. * If you have access to source code, a focused security code review is a great idea. Or, even an automated code scan, with a tool like Coverity (as @TheRook mentioned), or a better one... * Even if you don't have source code access, consider a security penetration test, either by experienced consultant/pentester, or at least with an automated tool (there are many out there) - e.g. appscan, webinspect, netsparker, acunetix, etc etc.
425,725
With the `auth-user-pass filename` option is it possible to create a plain text file with username and passphrase. Is it possible to have the username and passphrase directly in the client.conf?
2012/09/09
[ "https://serverfault.com/questions/425725", "https://serverfault.com", "https://serverfault.com/users/34187/" ]
Not without recompiling `openvpn`. It's made this way to discourage putting them there. If you want to have automatic VPN channel negotiation you really should use certificates and private keys. There should be an `easy-rsa` directory in documentation with scripts that will make it easier to set up single-purpose CA. If you can't reconfigure the server (because you're not its administrator) then you really shouldn't keep your passwords in plain-text files...
You would have to recompile openvpn. Take a look [here](http://community.openvpn.net/openvpn/wiki/BuildingOnWindows) to build on Windows. It is always better to use certificates and private keys instead of plain text passwords
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
``` char oneByte; int r=read(fd, &oneByte, 1); ``` Yes, should work.
That depends if you want to read a stream (ie, a FILE \*) or a file descriptor. For a stream, you have ``` getc(FILE *stream); ``` For a file descriptor, you can use a byte variable as a buffer,something like ``` unsigned char b; //or signed if you prefer read(fd, &b, 1); ```
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
``` char oneByte; int r=read(fd, &oneByte, 1); ``` Yes, should work.
You can use `getchar()` to get a single byte from standard input, or `fgetc()` to get it from an arbitrary file handle (stream), such as one of: ``` int ch = getchar(); // Assuming ch >= 0, you have your byte ``` or: ``` FILE *in = fopen ("input.txt", "r"); // should check for NULL return int ch = fgetc (in); // Assuming ch >= 0, you have your byte ``` If you have a file descriptor rather than a handle, you can use `read()` instead, something like: ``` int fd = open ("input.txt", O_RDONLY, 0); // should check fd for -1 char ch; ssize_t quant = read (fd, &ch, 1); // Assuming quant > 0, ch will hold your byte ```
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
``` char oneByte; int r=read(fd, &oneByte, 1); ``` Yes, should work.
Regarding the answers that suggest using read(), it should look like this: ``` char b; int r; while((r=read(fd,&b,1))==-1 && errno==EINTR) {} if(r==..... ``` The reason is that in case of delivery of a signal read() gets interrupted and needs to be restarted. If you do not test for EINTR you may face random, hard to find bugs.
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
That depends if you want to read a stream (ie, a FILE \*) or a file descriptor. For a stream, you have ``` getc(FILE *stream); ``` For a file descriptor, you can use a byte variable as a buffer,something like ``` unsigned char b; //or signed if you prefer read(fd, &b, 1); ```
You can use `getchar()` to get a single byte from standard input, or `fgetc()` to get it from an arbitrary file handle (stream), such as one of: ``` int ch = getchar(); // Assuming ch >= 0, you have your byte ``` or: ``` FILE *in = fopen ("input.txt", "r"); // should check for NULL return int ch = fgetc (in); // Assuming ch >= 0, you have your byte ``` If you have a file descriptor rather than a handle, you can use `read()` instead, something like: ``` int fd = open ("input.txt", O_RDONLY, 0); // should check fd for -1 char ch; ssize_t quant = read (fd, &ch, 1); // Assuming quant > 0, ch will hold your byte ```
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
That depends if you want to read a stream (ie, a FILE \*) or a file descriptor. For a stream, you have ``` getc(FILE *stream); ``` For a file descriptor, you can use a byte variable as a buffer,something like ``` unsigned char b; //or signed if you prefer read(fd, &b, 1); ```
Regarding the answers that suggest using read(), it should look like this: ``` char b; int r; while((r=read(fd,&b,1))==-1 && errno==EINTR) {} if(r==..... ``` The reason is that in case of delivery of a signal read() gets interrupted and needs to be restarted. If you do not test for EINTR you may face random, hard to find bugs.
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
Regarding the answers that suggest using read(), it should look like this: ``` char b; int r; while((r=read(fd,&b,1))==-1 && errno==EINTR) {} if(r==..... ``` The reason is that in case of delivery of a signal read() gets interrupted and needs to be restarted. If you do not test for EINTR you may face random, hard to find bugs.
You can use `getchar()` to get a single byte from standard input, or `fgetc()` to get it from an arbitrary file handle (stream), such as one of: ``` int ch = getchar(); // Assuming ch >= 0, you have your byte ``` or: ``` FILE *in = fopen ("input.txt", "r"); // should check for NULL return int ch = fgetc (in); // Assuming ch >= 0, you have your byte ``` If you have a file descriptor rather than a handle, you can use `read()` instead, something like: ``` int fd = open ("input.txt", O_RDONLY, 0); // should check fd for -1 char ch; ssize_t quant = read (fd, &ch, 1); // Assuming quant > 0, ch will hold your byte ```
18,263,585
Here is a **[fiddle](http://jsfiddle.net/zCFr5/)**. I'm trying to create a countdown object that uses [moment.js](http://momentjs.com/) (a plugin that I prefer over using Date()) ``` var Countdown = function(endDate) { this.endMoment = moment(endDate); this.updateCountdown = function() { var currentMoment, thisDiff; currentMoment = moment(); thisDiff = (this.endMoment).diff(currentMoment, "seconds"); if (thisDiff > 0) console.log(thisDiff); else { clearInterval(this.interval); console.log("over"); } } this.interval = setInterval(this.updateCountdown(), 1000); } ``` I then create a instance of the countdown like so: ``` var countdown = new Countdown("January 1, 2014 00:00:00"); ``` However the function only seems to run one time. Any ideas? Should I be using setTimeout() instead?
2013/08/15
[ "https://Stackoverflow.com/questions/18263585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179207/" ]
You should pass a *reference* to function, not the result of its execution. Also, you need some additional "magic" to call a method this way. ``` var me = this; this.interval = setInterval(function () { me.updateCountdown(); }, 1000); ```
You can either store your `this` context as a local variable like the following: ``` var Countdown = function(endDate) { var self = this; this.endMoment = moment(endDate); this.updateCountdown = function() { var currentMoment, thisDiff; currentMoment = moment(); thisDiff = (self.endMoment).diff(currentMoment, "seconds"); if (thisDiff > 0) console.log(thisDiff); else { clearInterval(self.interval); console.log("over"); } } this.interval = setInterval(this.updateCountdown, 1000); } ``` Or you can just use your variables directly such as: ``` var Countdown = function(endDate) { var endMoment = moment(endDate); this.updateCountdown = function() { var currentMoment, thisDiff; currentMoment = moment(); thisDiff = (endMoment).diff(currentMoment, "seconds"); if (thisDiff > 0) console.log(thisDiff); else { clearInterval(interval); console.log("over"); } } var interval = setInterval(this.updateCountdown, 1000); } ``` I prefer the second approach - [fiddle](http://jsfiddle.net/XYnPf/)
41,151,365
My stored procedure always returns a null value when I try to select it. I did some research and I have to specify somewhere OUTPUT. Not sure where or how to do that. ``` delimiter $$ Create Procedure ClientPurchases (IN idClient INT, outClientAvgPurchases DECIMAL (4,2)) BEGIN DECLARE PurchasesAvg DECIMAL(4,2) ; set PurchasesAvg= (SELECT AVG(PurchaseAmount) FROM Purchase inner join Client on idClient=Client_idClient); SET outClientAvgPurchases= PurchasesAvg; END$$ CALL ClientPurchase(3, @purchase ); SELECT @purchase as 'Purchase Total'; ```
2016/12/14
[ "https://Stackoverflow.com/questions/41151365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6221064/" ]
You simply missed to add the `/s` option to the `dir` command: ``` @echo off setlocal EnableExtensions EnableDelayedExpansion set "FOLDER=" & set /P FOLDER="" for /f "tokens=3" %%A in (' dir /S /A:-D /-C "!FOLDER!" ') do ( set "SIZE=!FREE!" set "FREE=%%A" ) echo free space is %free% bytes echo size is %size% bytes endlocal ```
To see size of folders on the Desktop. ``` for /f "skip=2 tokens=3" %A in ('Reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop"') do set doc=%A for /f "usebackq tokens=2* delims= " %i IN (`dir "%doc%" /a /s ^|findstr /i /v "\/"`) DO @echo %j&echo. ``` To see size of folders the System32 folder. ``` for /f "usebackq tokens=2* delims= " %i IN (`dir "%windir%\system32" /a /s ^|findstr /i /v "\/"`) DO @echo %j&echo. ``` See `Findstr /?`
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
Edit: ----- Ah wait, I misread the question. You want to do it without turning off the CSRF protection? Like Bharat Geleda said: You can make a route that returns only the token and manually copy it in a `_token` field in postman. But I would recommend excluding your api calls from the CSRF protection like below, and addin some sort of API authentication later. *Which version of laravel are you running?* Laravel 5.2 and up: ------------------- Since 5.2 the CSRF token is only required on routes with `web` middleware. So put your api routes outside the group with `web` middleware. See the "The Default Routes File" heading in the [documentation](https://laravel.com/docs/5.2/routing#basic-routing) for more info. Laravel 5.1 and 5.2: -------------------- You can exclude routes which should not have CSRF protection in the `VerifyCsrfToken` middleware like this: ``` class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', ]; } ``` See the "Excluding URIs From CSRF Protection" heading [documentation](https://laravel.com/docs/5.1/routing#csrf-excluding-uris) for more info.
In laravel, 5.3. Go to `app/Http/Kernel.php` find `middlewareGroups` then comment VerifyCsrfToken. Because it executes all middleware before service your request. ``` protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ***// \App\Http\Middleware\VerifyCsrfToken::class,*** \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; ```
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
Edit: ----- Ah wait, I misread the question. You want to do it without turning off the CSRF protection? Like Bharat Geleda said: You can make a route that returns only the token and manually copy it in a `_token` field in postman. But I would recommend excluding your api calls from the CSRF protection like below, and addin some sort of API authentication later. *Which version of laravel are you running?* Laravel 5.2 and up: ------------------- Since 5.2 the CSRF token is only required on routes with `web` middleware. So put your api routes outside the group with `web` middleware. See the "The Default Routes File" heading in the [documentation](https://laravel.com/docs/5.2/routing#basic-routing) for more info. Laravel 5.1 and 5.2: -------------------- You can exclude routes which should not have CSRF protection in the `VerifyCsrfToken` middleware like this: ``` class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', ]; } ``` See the "Excluding URIs From CSRF Protection" heading [documentation](https://laravel.com/docs/5.1/routing#csrf-excluding-uris) for more info.
1.You can create a new route to show the csrf token using your controller with help of the function below. (Use a Get request on the route) ``` public function showToken { echo csrf_token(); } ``` 2.Select the Body tab on postman and then choose x-www-form-urlencoded. 3.Copy the token and paste in postman as the value of the key named \_token. 4.Execute your post request on your URL/Endpoint
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
Edit: ----- Ah wait, I misread the question. You want to do it without turning off the CSRF protection? Like Bharat Geleda said: You can make a route that returns only the token and manually copy it in a `_token` field in postman. But I would recommend excluding your api calls from the CSRF protection like below, and addin some sort of API authentication later. *Which version of laravel are you running?* Laravel 5.2 and up: ------------------- Since 5.2 the CSRF token is only required on routes with `web` middleware. So put your api routes outside the group with `web` middleware. See the "The Default Routes File" heading in the [documentation](https://laravel.com/docs/5.2/routing#basic-routing) for more info. Laravel 5.1 and 5.2: -------------------- You can exclude routes which should not have CSRF protection in the `VerifyCsrfToken` middleware like this: ``` class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', ]; } ``` See the "Excluding URIs From CSRF Protection" heading [documentation](https://laravel.com/docs/5.1/routing#csrf-excluding-uris) for more info.
If you store your sessions in Cookies, you can grab the Cookie from an auth request in Developer Tools. [![enter image description here](https://i.stack.imgur.com/Tj1Hq.png)](https://i.stack.imgur.com/Tj1Hq.png) Copy and paste that Cookie in the Header of your POSTMAN or Paw requests. [![enter image description here](https://i.stack.imgur.com/f8zha.png)](https://i.stack.imgur.com/f8zha.png) This approach allows you to limit your API testing to your current session.
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
Edit: ----- Ah wait, I misread the question. You want to do it without turning off the CSRF protection? Like Bharat Geleda said: You can make a route that returns only the token and manually copy it in a `_token` field in postman. But I would recommend excluding your api calls from the CSRF protection like below, and addin some sort of API authentication later. *Which version of laravel are you running?* Laravel 5.2 and up: ------------------- Since 5.2 the CSRF token is only required on routes with `web` middleware. So put your api routes outside the group with `web` middleware. See the "The Default Routes File" heading in the [documentation](https://laravel.com/docs/5.2/routing#basic-routing) for more info. Laravel 5.1 and 5.2: -------------------- You can exclude routes which should not have CSRF protection in the `VerifyCsrfToken` middleware like this: ``` class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', ]; } ``` See the "Excluding URIs From CSRF Protection" heading [documentation](https://laravel.com/docs/5.1/routing#csrf-excluding-uris) for more info.
In the headers, add the cookies, before making request, the XSRF-TOKEN cookie and the app cookie. I.e yourappname\_session
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
1.You can create a new route to show the csrf token using your controller with help of the function below. (Use a Get request on the route) ``` public function showToken { echo csrf_token(); } ``` 2.Select the Body tab on postman and then choose x-www-form-urlencoded. 3.Copy the token and paste in postman as the value of the key named \_token. 4.Execute your post request on your URL/Endpoint
In laravel, 5.3. Go to `app/Http/Kernel.php` find `middlewareGroups` then comment VerifyCsrfToken. Because it executes all middleware before service your request. ``` protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ***// \App\Http\Middleware\VerifyCsrfToken::class,*** \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; ```
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
If you store your sessions in Cookies, you can grab the Cookie from an auth request in Developer Tools. [![enter image description here](https://i.stack.imgur.com/Tj1Hq.png)](https://i.stack.imgur.com/Tj1Hq.png) Copy and paste that Cookie in the Header of your POSTMAN or Paw requests. [![enter image description here](https://i.stack.imgur.com/f8zha.png)](https://i.stack.imgur.com/f8zha.png) This approach allows you to limit your API testing to your current session.
In laravel, 5.3. Go to `app/Http/Kernel.php` find `middlewareGroups` then comment VerifyCsrfToken. Because it executes all middleware before service your request. ``` protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ***// \App\Http\Middleware\VerifyCsrfToken::class,*** \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; ```
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
In the headers, add the cookies, before making request, the XSRF-TOKEN cookie and the app cookie. I.e yourappname\_session
In laravel, 5.3. Go to `app/Http/Kernel.php` find `middlewareGroups` then comment VerifyCsrfToken. Because it executes all middleware before service your request. ``` protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ***// \App\Http\Middleware\VerifyCsrfToken::class,*** \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; ```
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
If you store your sessions in Cookies, you can grab the Cookie from an auth request in Developer Tools. [![enter image description here](https://i.stack.imgur.com/Tj1Hq.png)](https://i.stack.imgur.com/Tj1Hq.png) Copy and paste that Cookie in the Header of your POSTMAN or Paw requests. [![enter image description here](https://i.stack.imgur.com/f8zha.png)](https://i.stack.imgur.com/f8zha.png) This approach allows you to limit your API testing to your current session.
1.You can create a new route to show the csrf token using your controller with help of the function below. (Use a Get request on the route) ``` public function showToken { echo csrf_token(); } ``` 2.Select the Body tab on postman and then choose x-www-form-urlencoded. 3.Copy the token and paste in postman as the value of the key named \_token. 4.Execute your post request on your URL/Endpoint
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
If you store your sessions in Cookies, you can grab the Cookie from an auth request in Developer Tools. [![enter image description here](https://i.stack.imgur.com/Tj1Hq.png)](https://i.stack.imgur.com/Tj1Hq.png) Copy and paste that Cookie in the Header of your POSTMAN or Paw requests. [![enter image description here](https://i.stack.imgur.com/f8zha.png)](https://i.stack.imgur.com/f8zha.png) This approach allows you to limit your API testing to your current session.
In the headers, add the cookies, before making request, the XSRF-TOKEN cookie and the app cookie. I.e yourappname\_session
20,780,766
Basically i want to create translate animation but for some reason i cannot use TranslateAnimation class. Anyway this is my code main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> </RelativeLayout> ``` MainActivity.java ``` package com.test2; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.ImageView; public class MainActivity extends Activity { private RelativeLayout layout; private ImageView image; private LayoutParams imageParams; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layout = (RelativeLayout) findViewById(R.id.layout); image = (ImageView) findViewById(R.id.image); imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); image.setLayoutParams(imageParams); layout.setOnClickListener(new ClickHandler()); } class ClickHandler implements OnClickListener { public void onClick(View view) { // This is the animation part for (int i = 0; i < 100; i++) { imageParams.leftMargin = i; image.setLayoutParams(imageParams); // repaint() in java try { Thread.sleep(100); } catch (Exception e) { } } } } } ``` My problem is I need to do repaint() before using Thread.sleep otherwise the animation will not work and the object will just move to its final position. I've tried invalidate, requestLayout, requestDrawableState but none works. Any suggestion? EDIT: main.xml ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> </RelativeLayout> ``` MainActivity.java ``` public class MainActivity extends Activity { private RelativeLayout layout; private ImageView image; private LayoutParams imageParams; private Timer timer; private int i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layout = (RelativeLayout) findViewById(R.id.layout); image = new ImageView(this); image.setImageResource(R.drawable.ic_launcher); imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); image.setLayoutParams(imageParams); layout.addView(image); i = 0; timer = new Timer(); runOnUiThread ( new Runnable() { public void run() { timer.scheduleAtFixedRate ( new TimerTask() { @Override public void run() { imageParams.leftMargin = i; image.setLayoutParams(imageParams); i++; if (i == 15) { timer.cancel(); timer.purge(); } } }, 0, 100 ); } } ); } } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20780766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3135962/" ]
``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > </RelativeLayout> package com.example.example; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.widget.ImageView; import android.widget.RelativeLayout; import android.app.Activity; public class MainActivity extends Activity { ImageView imageView; RelativeLayout.LayoutParams params; int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView=new ImageView(this); RelativeLayout main=(RelativeLayout)findViewById(R.id.main); params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); imageView.setBackgroundResource(R.drawable.ic_launcher); imageView.setLayoutParams(params); main.addView(imageView); final Timer timer=new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { params.leftMargin=i; imageView.setLayoutParams(params); i++; if(i>=100){ timer.cancel(); timer.purge(); } } }); } }, 0, 100); } } ```
``` you can use timer task instead of sleep Like:- int i=0; Timer timer=new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub imageParams.leftMargin = i; image.setLayoutParams(imageParams); i++; if(i==100){ timer.cancel(); timer.purge(); } } }, 0, 1000); ```
70,507
I am hiring a PHP developer to build me a website. Their rate is 70$ an hour. He seems to have a good portfolio and experience. How do I know that I get a good website that is scalable and easy to maintain? Do I ask them to give me code samples so I can review it (I am a programmer but I did not do much PHP)? What are good credentials for a PHP developer? experience with Drupal? LAMP?
2011/04/22
[ "https://softwareengineering.stackexchange.com/questions/70507", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/23599/" ]
It is the same thing as when you go to the mechanic? How do you know that they are actually fixing something and not causing more problems for repeat business? The answer lies in asking for references. See if he will give you the names of people he's done work for and then get into contact with them. If you do not know PHP then asking for code samples won't do you much good.
I don't know the wage level where you are, but $70/h doesn't seem too bad to me. You can't compare this directly to the wage of a normal job, there is a lot of unbillable hours and little job security. In any case, be sure to do frequent reviews where he show you what he have done and you give feedback. If the job is "done" the first time you see it there is very little chance that it's done right. Check-list qualifications ain't worth a lot, there are lots of people out there who know a lot of different languages and frameworks (or at least claim so), it doesn't mean that they can do a good job in any of them. Years of experience doesn't guarantee anything either. So what's left to look at is the portfolio.
70,507
I am hiring a PHP developer to build me a website. Their rate is 70$ an hour. He seems to have a good portfolio and experience. How do I know that I get a good website that is scalable and easy to maintain? Do I ask them to give me code samples so I can review it (I am a programmer but I did not do much PHP)? What are good credentials for a PHP developer? experience with Drupal? LAMP?
2011/04/22
[ "https://softwareengineering.stackexchange.com/questions/70507", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/23599/" ]
(I'm a PHP/jQuery/Javascript Drupal/WolfCMS developer) 1. Credentials: Look at the sites, email their owners, confirm that they did what they say they did. Ask the previous clients about their experiance, how the site is working out for them. Important: A web developer that does simple sites is not nesseseraly good at portals, the revers also holds true. 2. Ask them what CMS they'll be using. If they say Joomla, run (no self respecting developer will ever work with joomla). If you have a simple site Drupal is NOT the way to go. If you have a portal Drupal IS the way to go. If it's a blog than it's Wordpress. 3. First impression: Remember your first impression and how and what they say. 4. Did they ask about your target audience? Did they analyse your company? Your products? If not, leave. Did they ask about your target audience? Did they analyse your company? Your products? If not, leave. Thing to remember is, putting up a site requires very little or no (php) coding (you only code really obscure or customised site functions, the rest has already been coded by the community) So there wont be "code snipets" to review. (But it still requires a LOT of knowledge). You should be able to get a professional developer for 40$/h. Also make shur you make a good plan at the start. Listen to the developer. Avoid corrections. I could tell you exactly what to ask if you specified your project. But most importantly look at the credentials and TRUST YOUR GUT.
I don't know the wage level where you are, but $70/h doesn't seem too bad to me. You can't compare this directly to the wage of a normal job, there is a lot of unbillable hours and little job security. In any case, be sure to do frequent reviews where he show you what he have done and you give feedback. If the job is "done" the first time you see it there is very little chance that it's done right. Check-list qualifications ain't worth a lot, there are lots of people out there who know a lot of different languages and frameworks (or at least claim so), it doesn't mean that they can do a good job in any of them. Years of experience doesn't guarantee anything either. So what's left to look at is the portfolio.
70,507
I am hiring a PHP developer to build me a website. Their rate is 70$ an hour. He seems to have a good portfolio and experience. How do I know that I get a good website that is scalable and easy to maintain? Do I ask them to give me code samples so I can review it (I am a programmer but I did not do much PHP)? What are good credentials for a PHP developer? experience with Drupal? LAMP?
2011/04/22
[ "https://softwareengineering.stackexchange.com/questions/70507", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/23599/" ]
If the guy is good and gets you a scalable and easy to maintain site, for $70/hour, you got the best deal in town. Let's assume 50 weeks of work, at 50 hours a week, or 50\*50\*70= $175,000. The site will incude a database, framework, dev and prod environments, automated deployment, an admin interface, an API, templates, css, jQuery, and a good-looking site. If you tried to hire the skillset for that in a regular company, you would be looking at * DBA: 95K/year * Sysadmin: 80K/year * UI Engineer: 75K/year. * PHP Developer: 60K/year * Project Manager: 75K/year ...for a total of 385,000 in salaries. Multiply by 1.5 for the overhead (Employer taxes, health insurance contributions, office space rent (these people don't work in dusty warehouses), 401K, computer equipment, hiring costs (your HR person isn't free), etc) and you're looking at $577,000. Now, I guarantee that the project won't be done in a year. It will take 2 months to ramp up, 2 months to get the servers up and provisioned (I'm being optimistic in my estimates), 2 months to nail down the requirements (with the team in place, can't write it all down and expect people to read it. You need meetings.), 2 months to design a passably scalable system, 8 months of coding, 2 months of testing, 1 months for deployment... Oh shit, I forgot, you need an architect for the scalability part: $135,000/year--No? Ok, no architect. So we're looking at a minimum of 19 months. The bill is now $ 912,000 That's assuming nothing goes wrong, meaning, nobody leaves the team halfway. What happens if your PHP coder leaves at 90% completion of the framework? (Knowing full well the remaining 10% takes another 90%) and, huh, you gotta pay salaries to the rest of your team while you find a competent PHP developer who is willing to take over the custom framework-from-hell. Let's say you're lucky and you find this guy, and I'll be nice and say you can hire him and put him in a cube in 2 months. By now, though, you're paying $100,000 for the php guy--you learned from your mistake. He takes 2 months to familiarize himself with the project, go over the code base, and learn the server setups. That's not a lot of time. 40 business days. So this adds 4 months to the schedule. So the interim 2 months period cost you: $81,000 His 2 months ramp up period cost you: $106,000 So, realistic scenario: your website cost you $1,100,000, and takes 23 months. And if you look around and ask people who have done this stuff, you will find that I'm not out on left field. So at $175,000 your guy is providing the site for 15.9% of the normal cost. Imagine if he charged you $300 an hour. That would be $750,000, and gets done in 1 year. You would still save a 350,000 dollars and have your site done a year earlier. If the guy can deliver, he's worth 4 times what you're paying him. Any question?
I don't know the wage level where you are, but $70/h doesn't seem too bad to me. You can't compare this directly to the wage of a normal job, there is a lot of unbillable hours and little job security. In any case, be sure to do frequent reviews where he show you what he have done and you give feedback. If the job is "done" the first time you see it there is very little chance that it's done right. Check-list qualifications ain't worth a lot, there are lots of people out there who know a lot of different languages and frameworks (or at least claim so), it doesn't mean that they can do a good job in any of them. Years of experience doesn't guarantee anything either. So what's left to look at is the portfolio.
15,452,832
**Table1** ``` HolId 1 Package17 2,1,5 2 Package13 5,4,3 ``` **Table 2** ``` HolId1 1 New Years Day 2013-01-01 00:00:00.000 2 Republic Day 2013-01-26 00:00:00.000 3 Holi 2013-04-27 00:00:00.000 4 Memorial Day 2013-05-27 00:00:00.000 5 US Independence 2013-07-04 00:00:00.000 7 Labour Day 2013-09-02 00:00:00.000 ``` I want to display data like below ``` HolId HolId1 Package17 2 2 Republic Day 2013-01-01 00:00:00.000 Package17 1 1 New Years Day 2013-04-27 00:00:00.000 Package17 5 5 US Independence 2013-05-27 00:00:00.000 Package13 5 5 US Independence 2013-07-04 00:00:00.000 Package13 4 4 Memorial Day 2013-05-27 00:00:00.000 Package13 3 3 Holi 2013-04-27 00:00:00.000 ``` My grid will be displayed as follows which i have figured out ``` Package17 Republic Day 2013-01-01 00:00:00.000 New Years Day 2013-04-27 00:00:00.000 US Independence 2013-05-27 00:00:00.000 Package13 US Independence 2013-07-04 00:00:00.000 Memorial Day 2013-05-27 00:00:00.000 Holi 2013-04-27 00:00:00.000 ```
2013/03/16
[ "https://Stackoverflow.com/questions/15452832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823528/" ]
This is solution for `MySQL`: ``` SELECT T1.Pkg, T2.* FROM Table2 T2 JOIN Table1 T1 ON FIND_IN_SET(T2.HolID1, T1.HolID) ``` **[SQL FIDDLE DEMO](http://sqlfiddle.com/#!2/30c3c/4)** and this is for `SQL SERVER` ``` SELECT T1.Pkg, T2.* FROM Table2 T2 JOIN Table1 T1 ON CHARINDEX(CAST(T2.HolID1 as varchar), T1.HolID) > 0 ``` **[SQL FIDDLE DEMO](http://sqlfiddle.com/#!3/314dd/1)**
Better to de-normalize your table, then just one join you can get your result. If you have to use the current schema. Hope the following code help you. ``` declare @tempTable table ( Package_Name varchar(100), Holid int ) declare @SQLString varchar(max) declare @package_name varchar(100) set @SQLString = '' DECLARE @X XML while @SQLString is not null begin set @SQLString = null select top 1 @package_name=package_name, @SQLString = Holid from Package where package_name not in (select package_name from @tempTable) if @SQLString is null break SET @X = CAST('' + REPLACE(@SQLString, ',', '') + '' AS XML) insert into @tempTable SELECT @package_name, t.value('.', 'INT') FROM @x.nodes('/A') as x(t) end select * from @tempTable select A.**, B.\*** from @tempTable A inner join HolID1 B on A.Holid = B.HolID1 ```
48,299,218
I've written the following function in the spider to scrape info in a website. I've enabled the Image pipelines to even scrape the image along with the associated scraped data. With this piece of code i'm able to yield either the images or the `scraped_data` (which is commented in the last second line). Can anyone please help me with this as how can i yield both the images and the `scraped_info`? ``` def parse_info(self, response): url = response.url title = str(response.xpath('//*[@dataitem="itemTitle"]/text()').extract_first()) img_url_1 = response.xpath("//img[@id='icImg']/@src").extract_first() scraped_info = { 'title' : title, } yield {'image_urls': [img_url_1]} ``` I've checked running this code for scraping images which was successful. Thus, there's no error in `settings.py` or `items.py`. I'm concerned about scraping the images with the scraped data together. Any help?
2018/01/17
[ "https://Stackoverflow.com/questions/48299218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4393262/" ]
As per [documentation](https://doc.scrapy.org/en/latest/topics/media-pipeline.html#using-the-images-pipeline) to Image Pipeline, items that you yield have to contain field `image_urls` (as a list). The Image Pipeline will download the images and populate another field of the item - `images` - with information about downloaded images. Thus, you have to modify your code like this (showing only the relevant part): ``` def parse_info(self, response): item = response.meta.get('item') url=response.url title=str(response.xpath('//*[@id="itemTitle"]/text()').extract_first()) img_urls=response.xpath("//img[@id='icImg']/@src").extract() scraped_info = { 'url' : url, 'title' : title, 'image_urls' : img_urls } yield scraped_info ```
You should just yield an item that contains both the info and the image urls: ``` yield { 'url' : url, 'title' : title, 'image_urls': [img_url_1] } ```
49,863,232
**Disclaimer: I'm really new to WPF.** After looking around online I've understood that the HttpClient should be used as a singleton, shared between windows in WPF. However, I can't seem to find a *clear* startup entry-point as you'd find in MVC (startup, duh!). ***Where should I instantiate my HttpClient, and how can I use it across multiple windows?*** Currently I have two windows; Login and MainWindow. Both really basic. Example: ``` public partial class Login : Window { public Login() { InitializeComponent(); } private void BtnLoginSubmit_Click(object sender, RoutedEventArgs e) { } } ``` --- In my App.xaml.cs I've instantiated a HttpClient object which I can access from my MainWindow: App.xaml.cs: ``` public partial class App : Application { public HttpClient httpClient { get; set; } } ``` MainWindow.xaml.cs: ``` public partial class MainWindow : Window { private static ObservableCollection<string> states; public static void Add(string state) { states.Add(state); } public MainWindow() { InitializeComponent(); ((App)Application.Current).httpClient = new HttpClient(); states = new ObservableCollection<string>(); states.Add("Initialized"); states.CollectionChanged += states_CollectionChanged; LblStates.ItemsSource = states; Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch); } static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e) { if (e.Reason == SessionSwitchReason.SessionLock) { } MainWindow.Add(e.Reason.ToString()); } void states_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) { LblStates.Items.Refresh(); } } } ```
2018/04/16
[ "https://Stackoverflow.com/questions/49863232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5986941/" ]
The most basic approach would be to add a static class that holds a static instance of HttpClient. ``` internal static class HttpClientManager { public static HttpClient Client = InititializeHttpClient(); } ``` You can then reference the client from anywhere, like `HttpClientManager.HttpClient`.
I don't see why you'd need to necessarily share the `HttpClient` across different windows - the best approach would be to invoke it whenever you need it, unless there is some need to preserve the state. That said, you can create your HttpClient at app-level, and define a `HttpClient` there. You can define it in `App.xaml.cs` and re-use whenever necessary. It doesn't necessarily need to be static, you just need to refer to the specific instantiated entity.
32,084,741
Hey i want on my Page a Random BG everytime a User visit that Page. At the moment i simple use ``` <body background="./images/bgs/random/<?php echo rand(1,13); ?>.jpg"> ``` But now when a User logs in -> or a other Page Reload ... the Background changes too and thats a but ugly. So my Question is there a better way or a solve so that the bg is loading only once ? with sessions or something idk Every Answer is welcome thanks! :)
2015/08/19
[ "https://Stackoverflow.com/questions/32084741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5221267/" ]
Use a `$_SESSION`. Make sure that you use `session_start()` before any headers are sent. ``` <?php session_start(); if(!isset($_SESSION['background'])){ $_SESSION['background'] = rand(1,13); // now just use $_SESSION['background'] } ?> ```
``` <?php session_start(); if(!isset($_SESSION['bg'])) { $_SESSION['bg'] = rand(1, 13); } ?> <!-- background is very old, use css for this ;) --> <body background="./images/bgs/random/<?php echo $_SESSION['bg']; ?>.jpg"> ``` Also with `session_destroy()` you can reset your own session.
12,113
What do you do when notes from a chord in the left hand overlap with notes from a melody in the right hand? Do you drop notes? Do you change notes in the chord? This is my biggest frustration right now trying to play from fake books.
2013/09/29
[ "https://music.stackexchange.com/questions/12113", "https://music.stackexchange.com", "https://music.stackexchange.com/users/7166/" ]
This kind of playing (reading from lead sheets/fake books) is inherently improvisatory, so the prevailing wisdom should always be **"do what sounds good"**. There are a billion ways to play any given chart in a fake book, so keep in mind that you're not looking for one right answer. If you're working on a specific voicing technique, then the first thing I might try would be to either drop the bass by an octave or raise the melody up by an octave, in order to give yourself some room to work with. You shouldn't "change notes" in the chord, but you could change the chord voicing, or leave out nonessential notes. As anyone will tell you, the most important notes in most jazz chords are the 3rd and the 7th, so as long as the voicing has some indication of that specific tension, you're probably okay. Case in point: a dominant 7th chord can be outlined in the space of a tritone: `F - G - B` (G7), so you do have the option of being very economical with your space. The voicing you mention, with chords in the left hand and melody in the right, isn't all that typical of solo jazz piano playing as far as I'm concerned. You'd see that in stride piano or when soloing over your own chords, certainly, but a lot more common would be to put just a bass note in the left hand, and chords in the right hand *that track the melody as the top note in the chord*. It's usually pretty hard to run into that kind of trouble when you're voicing that way, since you can have the bass note WAY far away from your melody and chords.
Usually, when this happens, it's good enough to just hit the overlapping note again when it occurs in the melody, and just let it ring throughout the chord by holding it with the left hand.
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
First of all download the smartWizard.js from <https://github.com/mstratman/jQuery-Smart-Wizard> then add it in your workspace and give the reference in your html/jsp. ``` <script type="text/javascript" src="js/jquery.smartWizard-2.1.js"></script> ``` then, ``` <script type="text/javascript"> $(document).ready(function(){ // Smart Wizard $('#wizard').smartWizard(); //$('#range').colResizable(); function onFinishCallback(){ $('#wizard').smartWizard('showMessage','Finish Clicked'); } }); </script> ``` Then in the jquery.smartWizard-2.1.js search for onFinish, Just try giving alert and then whatever you want to add you can add it directly in the .js file.
// Changing Label of finish button $('#wizard').smartWizard.defaults.labelFinish = "confirm & Buy";
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
First of all download the smartWizard.js from <https://github.com/mstratman/jQuery-Smart-Wizard> then add it in your workspace and give the reference in your html/jsp. ``` <script type="text/javascript" src="js/jquery.smartWizard-2.1.js"></script> ``` then, ``` <script type="text/javascript"> $(document).ready(function(){ // Smart Wizard $('#wizard').smartWizard(); //$('#range').colResizable(); function onFinishCallback(){ $('#wizard').smartWizard('showMessage','Finish Clicked'); } }); </script> ``` Then in the jquery.smartWizard-2.1.js search for onFinish, Just try giving alert and then whatever you want to add you can add it directly in the .js file.
add your custom function like below. ``` onFinish: function () { alert("Finish Clicked!") }, // triggers when Finish button is clicked ```
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
First of all download the smartWizard.js from <https://github.com/mstratman/jQuery-Smart-Wizard> then add it in your workspace and give the reference in your html/jsp. ``` <script type="text/javascript" src="js/jquery.smartWizard-2.1.js"></script> ``` then, ``` <script type="text/javascript"> $(document).ready(function(){ // Smart Wizard $('#wizard').smartWizard(); //$('#range').colResizable(); function onFinishCallback(){ $('#wizard').smartWizard('showMessage','Finish Clicked'); } }); </script> ``` Then in the jquery.smartWizard-2.1.js search for onFinish, Just try giving alert and then whatever you want to add you can add it directly in the .js file.
Use the following code, your form will be submitted. I hope this will help you. ``` var Myform=$('#saveForm'); $(document).on('click','.btn-finish',function(e){ $('#saveForm')[0].submit(); }); ```
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
First of all download the smartWizard.js from <https://github.com/mstratman/jQuery-Smart-Wizard> then add it in your workspace and give the reference in your html/jsp. ``` <script type="text/javascript" src="js/jquery.smartWizard-2.1.js"></script> ``` then, ``` <script type="text/javascript"> $(document).ready(function(){ // Smart Wizard $('#wizard').smartWizard(); //$('#range').colResizable(); function onFinishCallback(){ $('#wizard').smartWizard('showMessage','Finish Clicked'); } }); </script> ``` Then in the jquery.smartWizard-2.1.js search for onFinish, Just try giving alert and then whatever you want to add you can add it directly in the .js file.
You can listen for an onclick event on the toolbar extra buttons. ``` // Toolbar extra buttons var btnFinish = $("<button></button>") .text("Finish") .addClass("btn btn-primary") .on("click", function () { alert("Finish Clicked"); }); var btnCancel = $("<button></button>") .text("Cancel") .addClass("btn btn-secondary") .on("click", function () { $("#wizard").smartWizard("reset"); }); // Initiate wizard $("#wizard").smartWizard({ selected: 0, theme: "default", autoAdjustHeight: true, transition: { animation: "slide-horizontal", }, toolbarSettings: { toolbarPosition: "bottom", toolbarExtraButtons: [btnFinish, btnCancel], }, }); ```