qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
53,650,746
If my character collided in an Object, I want my camera position y to move down a bit. I have tried to program it like this : ``` void OnTriggerEnter2D(Collider other) { float x = Camera.main.transform.position.x; float y = Camera.main.transform.position.y; Vector3 origPOS = new Vector3(x, (Mathf.Lerp(y, -3, 3 * Time.deltaTime)), 0); Camera.main.transform.position = origPOS; } ``` but it does not behave like I want to. Can you guys help me? This is the image of the original position of the Camera: [![enter image description here](https://i.stack.imgur.com/DBOFE.png)](https://i.stack.imgur.com/DBOFE.png) This the desired position of my Camera when my character collided in an object and perform the function that will move my Camera: [![enter image description here](https://i.stack.imgur.com/2xCfC.png)](https://i.stack.imgur.com/2xCfC.png)
2018/12/06
[ "https://Stackoverflow.com/questions/53650746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9896379/" ]
I think you simple need : ``` UPDATE t1 SET t1.code = t2.code FROM t1 INNER JOIN t2 ON t1.FULL_NAME = t2.FIRST_NAME + ' ' + t2.LAST_NAME WHERE t1.code IS NULL; ```
Here's the answer: ``` UPDATE IMPORT_DATA.RDBS_DATA_STORAGE SET child_iin = pd.iin FROM IMPORT_DATA.RDBS_DATA_STORAGE INNER JOIN nedb.PERSONAL_DATA pd ON child_iin LIKE '%' + pd.LAST_NAME + '%' + ' ' + '%' + pd.FIRST_NAME + '%' WHERE LEN(child_iin) < 1; ``` `N`'s were unnecessary
10,721,443
I have a static list: ``` public static List<IMachines>mList =new List<IMachines>(); ``` The list intakes two different types of objects(machines) in it: ``` IMachines machine = new AC(); IMachines machine = new Generator(); ``` If after adding items to the list, I want to search for a particular machine by its name property then after using the foreach loop for traversal if that item is found in list ... how am I supposed to know if the item is of `AC` type or `Generator` type?
2012/05/23
[ "https://Stackoverflow.com/questions/10721443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407560/" ]
You can use the [`is` operator](http://msdn.microsoft.com/en-us/library/scekt9xw.aspx): > > Checks if an object is compatible with a given type > > > For example: ``` if(item is AC) { // it is AC } ```
``` interface IVehicle { } class Car : IVehicle { } class Bicycle : IVehicle { } static void Main(string[] args) { var v1 = new Car(); var v2 = new Bicycle(); var list = new List<IVehicle>(); list.Add(v1); list.Add(v2); foreach (var v in list) { Console.WriteLine(v.GetType()); } } ```
28,970,289
I have a situation when a msg fails and I would like to replay that msg with the highest priority using python boto package so he will be taken first. If I'm not wrong SQS queue does not support priority queue, so I would like to implement something simple. **Important note**: when a msg fails I no longer have the message object, I only persist the receipt\_handle so I can delete the message(if there was more than x retries) / change timeout visibility in order to push him back to queue. Thanks!
2015/03/10
[ "https://Stackoverflow.com/questions/28970289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2965630/" ]
I don't think there is any way to do this with a single SQS queue. You have no control over delivery of messages and, therefore, no way to impose a priority on messages. If you find a way, I would love to hear about it. I think you could possibly use two queues (or more generally N queues where N is the number of levels of priority) but even this seems impossible if you don't actually have the message object at the time you determine that it has failed. You would need the message object so that the data could be written to the *high-priority* queue. I'm not sure this actually qualifies as an answer 8^)
As far as I know AWS SQS does not provide a native way or doing a priority queue (single queue priority). If you are open to considering other options, RabbitMQ can do this. Client can specify a priority of 0-255 in the message, and the queue will prioritize a higher priority message gets to the customer first. For more information, please look at <https://www.rabbitmq.com/priority.html>
45,069,328
I am very new to Maven builds. I have created a maven project and running it using maven build. It is running fine using tomcat7:run as goal but then I am finding it hard to stop the server. I am getting following error when I try to run again. ``` java.net.BindException: Address already in use: JVM_Bind <null>:8080 ``` Any suggestions ?
2017/07/12
[ "https://Stackoverflow.com/questions/45069328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684818/" ]
If the process is still running, you should be able to see it in your console. If you see a stop button (like *1*), just press it and that should stop the tomcat server. If you happen to have had more than one service running, then the button in *2* should be activated. That will show all the running and stopped services you have. Select the one for your Tomcat and then press the stop button. [![enter image description here](https://i.stack.imgur.com/XhmLO.png)](https://i.stack.imgur.com/XhmLO.png)
You can use `mvn tomcat7:shutdown` command to stop. > > Shuts down all possibly started embedded tomcat servers. This will be automatically down through a shutdown hook or you may call this Mojo to shut them down explictly. > > > Here is the [documentation](http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/plugin-info.html).
143,700
Is there a term that can be used to refer to both the prefix and suffix of a word? For example, *unenjoyable*. I'm looking for a collective word that described BOTH *un* and *able*.
2013/12/30
[ "https://english.stackexchange.com/questions/143700", "https://english.stackexchange.com", "https://english.stackexchange.com/users/60849/" ]
I think the word you are looking for is [affix](http://en.wikipedia.org/wiki/Affix), though that also includes "-fixes" other than just "suffix" and "prefix". > > [Noun: affix (plural affixes)](http://en.wiktionary.org/wiki/affix) > > > (linguistics) A bound morpheme added to a word’s stem; formerly applied only to suffixes (also called postfixes), the term as now used comprises prefixes, suffixes, infixes, circumfixes, and suprafixes. > > >
Like the other answers mentioned, the general word referring to prefixes, suffixes and similar, is *affix*. However, [Wikipedia](http://en.wikipedia.org/wiki/Infix) also mentions *adfix* as joint name for prefixes and suffixes but **not** any other kind of affix: > > It [infix] contrasts with adfix, a rare term for an affix attached to > the end of a stem, such as a prefix or suffix. > > > See the [definition of *adfix* in Wiktionary](http://en.wiktionary.org/wiki/adfix).
12,097,243
Consider I am given a specific range (0 to 5,000,000) and I should generate 2,500,000 unique random numbers from this range. What is an efficient way to do this? I understand that is tough to get true random numbers. I tried by checking if a number exists so that I can generate a new random number. But it takes hours to compute. Is there a better way to do this. The reason behind this is, I have a vector of size 5,000,000. I want to shrink the vector exactly by half. i.e. delete random 50% of the elements from the vector. ``` #include <iostream> #include <vector> #include <stdlib.h> #include <algorithm> using namespace std; #define NUMBER 2500000 #define RAND_START 0 #define RAND_END 5000000 unsigned int generate_random_number(int min, int max) { return min + (rand() % (unsigned int)(max - min + 1)); } int main(int argc, char* argv[]) { unsigned int count = 0, random_number; vector<unsigned int> rand_vector; do { count++; random_number = generate_random_number(RAND_START,RAND_END); // Tried to manually add a different number each time. But still not a considerable improvement in performance. if (std::find(rand_vector.begin(), rand_vector.end(), random_number) != rand_vector.end()) { if(random_number > count) random_number = random_number - count; else random_number = random_number + count; } rand_vector.push_back(random_number); sort(rand_vector.begin(), rand_vector.end()); rand_vector.erase(unique (rand_vector.begin(), rand_vector.end()), rand_vector.end()); }while (rand_vector.size() != NUMBER); for (unsigned int i =0; i < rand_vector.size(); i++) { cout<<rand_vector.at(i)<<", "; } cout<<endl; return 0; } ``` Any better approach by which I can do this?
2012/08/23
[ "https://Stackoverflow.com/questions/12097243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73137/" ]
Easiest way to code it: ``` std::random_shuffle(vectoshrink.begin(), vectoshrink.end()); vectoshrink.resize(vectoshrink.size() / 2); ``` If you want to maintain the order of the elements in `vectoshrink` use AndreyT's answer. If you really do want to select the indexes in advance: ``` std::vector<size_t> vec(vectoshrink.size()); // iota is C++11, but easy to do yourself std::iota(vec.begin(), vec.end(), size_t(0)); std::random_shuffle(vec.begin(), vec.end()); vec.resize(vec.size() / 2); // optionally std::sort(vec.begin(), vec.end()); ``` Now, you could use those indexes to shrink your original vector by copying the elements at the indexes in `vec` into a new vector, and swap the result with the original. In both cases, `random_shuffle` does more than is strictly required, since it shuffles the whole vector, whereas actually we only need to "shuffle" half of it. If you read how a Fisher-Yates shuffle works, though, it's easy to see that if you code it yourself then the only modification required is to do half as many steps as the full shuffle. C++ doesn't have a standard `partial_random_shuffle`, though. Finally, beware that the default random source might not be very good, so you might want to use the three-argument version of `random_shuffle`. Your `generate_random_number` function is quite biassed for certain values of `min` and `max`, so you might want to research a bit more on the general theory of random number generation.
Generate 1st number <5M, 2nd number <(5M-1), etc. Each time after you remove element, you'll have one element less and you don't care if it's the same number. ;-) This doesn't answer your question about unique numbers, but about halving your vector. And you will not have to generate more numbers than you need.
656,079
I created a basic test PostgreSQL RDS instance in a VPC that has a single public subnet and that should be available to connect over the public internet. It uses the default security group, which is open for port 5432. When I try to connect, it fails. I must be missing something very straightforward -- but I'm pretty lost on this. Here're the database settings, note that it's marked as `Publicly Accessible`: ![RDS Settings](https://i.stack.imgur.com/x3RJn.png) Here're the security group settings, note it's wide open (affirmed in the RDS settings above by the green "authorized" hint next to the endpoint): ![Security Group settings](https://i.stack.imgur.com/Cla5s.png) Here's the command I'm trying to use to connect: ``` psql --host=myinstance.xxxxxxxxxx.us-east-1.rds.amazonaws.com \ --port=5432 --username=masteruser --password --dbname=testdb ``` And this is the result I'm getting when trying to connect from a Yosemite MacBook Pro (note, it's resolving to a 54.\* ip address): ``` psql: could not connect to server: Operation timed out Is the server running on host "myinstance.xxxxxxxxxx.us-east-1.rds.amazonaws.com" (54.xxx.xxx.xxx) and accepting TCP/IP connections on port 5432? ``` I do not have any kind of firewall enabled, and am able to connect to public PostgreSQL instances on other providers (e.g. Heroku). Any troubleshooting tips would be much appreciated, since I'm pretty much at a loss here. **Update** Per comment, here are the inbound ACL rules for the Default VPC: ![Network ACL configuration](https://i.stack.imgur.com/TR1Y2.png)
2015/01/03
[ "https://serverfault.com/questions/656079", "https://serverfault.com", "https://serverfault.com/users/86294/" ]
The issue was that the inbound rule in the Security Group specified a security group as the source. Changing it to a CIDR that included my IP address fixed the issue. Open the database security group in AWS; and choose "Edit inbound rules"; "Add rule". There is a "My IP" option in the dropdown menu; select that option to auto-populate with your computer's public IP address in CIDR notation [![edit security group, edit its inbound rules, add a rule, choose "My IP" option in the "Source" column](https://i.stack.imgur.com/guNqP.png)](https://i.stack.imgur.com/guNqP.png)
Was facing similar issue, and this is how I resolved it: Click on the security group for the RDS instance and check the inbound rules. You might see something like this: [![enter image description here](https://i.stack.imgur.com/lgoNh.png)](https://i.stack.imgur.com/lgoNh.png) Have to set the IP range to contain your IP or just select "Anywhere" in the Source dropdown, to make it accessible from localhost or anywhere: [![enter image description here](https://i.stack.imgur.com/X3KZm.png)](https://i.stack.imgur.com/X3KZm.png)
50,100,211
In angular i want to check the component containing any input value is changed or Not. Example. i have a page with 5 controls (3 text box and 2 drop downs ) if the value got changed on textbox or drop down,i want to identify that is any value is changed or it is as previous. please help me,if any one can..
2018/04/30
[ "https://Stackoverflow.com/questions/50100211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291499/" ]
If you're using [`ReactiveForms`](https://angular.io/api/forms/ReactiveFormsModule) you can use [`valueChanges`](https://angular.io/api/forms/AbstractControl#valueChanges) like: ``` this.myFormGroup.valueChanges .debounceTime(500) // optional .subscribe(data => { // do some stuff with `data` }); ```
In input field write `(ngModelChange)="findchanges(inputValue)"`. Then in ts file get changes of that input field.
49,962,583
I want to write a function that extracts n number of elements from the start of a list in Haskell. I know it can be done using the built-in 'take' function and I have done it, which works. However, I can't seem to write a function without take. This is my code. ``` takeElem' :: Int -> [t] -> [t] takeElem' _ [] = [] takeElem' n (x:xs) = [x] ++ takeElem' (n-1) xs ``` This code complies fine but when I test it for example ``` takeElem' 3 "hello" ``` It returns "hello" instead of "hel" Any idea what could be wrong?
2018/04/22
[ "https://Stackoverflow.com/questions/49962583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9483263/" ]
I didn't add what should happen in the case when n is zero. I just added ``` takeElem' 0 list = [] ``` it works now.
It should be 0 \_ instead of \_ []. Because you are saying it is [] when you took everything of the list instead of [] when your n reaches 0.
22,125,096
I am preparing for an entry-level job interview. I am trying to reverse the order of words in a string, but my output is a bunch of junk that makes no sense. I think the problem may be because I'm using "char\*" for my functions? Anyways, heres my code ``` #include <iostream> #include <string> using namespace std; char* reverse(char* str, int a, int b); char* reversewords(char* str); int main() { char str[] = "The interview is"; cout<<"Reverse is: "<<reversewords(str); cin.ignore(); return 0; } char* reverse(char* str, int a, int b) { int length = a-b; for (int i=a; i<b+1; i++) { char c =str[length-i-1]; str[length-i-1]=str[i]; str[i] = c; } return str; } char* reversewords(char* str) { int length = strlen(str); int a=0; int b=0; while (b<length) { if (str[b]==' ' || b==length-1) { b=b-1; reverse(str, a, b); a=b+2; b=a; } b++; } return str; } ```
2014/03/02
[ "https://Stackoverflow.com/questions/22125096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3370198/" ]
let me recommend a different approach. If youre using char pointers: 1. split the string using `strtok` into an array of `char*`s. 2. iterate over this array of words from the end backwards and reassemble the string. If you opt to use strings and STL containers, refer to this question as for splitting the string to tokens, and reassembling them nicely: [Split a string in C++?](https://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) Its always a better idea not to reinvent the wheel. Use library functions, dont manipulate the chars yourself.
``` #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void split(string &str, vector<string> &v, char ch); int main() { string str; std::getline(std::cin, str); vector <string> stringVec; split(str, stringVec, ' '); vector <string>::reverse_iterator it; for (auto it = stringVec.rbegin(); it != stringVec.rend(); ++it) { cout << *it << " "; } return 0; } void split(string &str, vector<string> &v, char ch) { size_t pos = str.find(" "); size_t initialpos = 0; v.clear(); while (pos != string::npos) { v.push_back(str.substr(initialpos, pos - initialpos)); initialpos = pos + 1; pos = str.find(ch,initialpos); } v.push_back(str.substr(initialpos, (std::min(pos, str.size()) - initialpos + 1))); } ```
58,358,936
Despite a ton of searching, I can't find any method equivalent in the Firebase Realtime Database to the increment method available in Firestore. The problem I am trying to solve is that I have a ticketing app which increments a counter on Firebase for attendees at the event; however if a user went offline and was registering attendees with the persistent database, while another user who is online was also doing so, when the first user comes back online, they overwrite the value for the counter using their stored value plus any additional attendees they validated before coming back online. This does not take into account the fact that the value of the counter had changed before they came back online. There will be 6 people validating event tickets, so this value will always be wrong if someone reconnects and overwrites values registered by the other users. So if there is an increment method like this one: ``` increment = firebase.firestore.FieldValue.increment(1); ``` Can you please let me know what it is? If not, how would you approach my issue with data persistence on the device in Swift? **N.B.** I am using the Realtime Database as opposed to Firestore because it was recommended for speed and data use when you are in a situation where you are doing a ton of small updates to the database -- which obviously will be the case when you are processing tickets for thousands of people.
2019/10/12
[ "https://Stackoverflow.com/questions/58358936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1072220/" ]
There's a new method `ServerValue.increment()`in firebase Swift SDK It's better for performance and cheaper since no round trip is required. API Docs [here](https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/ServerValue) Usage example: ``` firebase.database() .ref('somePath') .child('someCounter') .set(firebase.database.ServerValue.increment(1)) ``` Or you can decrement, just put `-1` as function arg like so: ``` firebase.database() .ref('somePath') .child('someCounter') .set(firebase.database.ServerValue.increment(-1)) ```
Realtime Database does seem to have this feature now. The API reference is here: <https://firebase.google.com/docs/reference/js/firebase.database.ServerValue#increment> Basically in a `ref.update()` you will provide `database.ServerValue.increment(n)` on the field you wish to increment. For example: ``` ref.update({ counter: database.ServerValue.increment(1) }); ``` You may also provide a negative value to decrement: ``` ref.update({ counter: database.ServerValue.increment(-1) }); ```
5,345,253
I have written my own module, mainly handling a filefield for a django site. After messing around with some things related to mod\_wsgi (solved by updating to 3.3), i got my code to run. Right after all the necessary imports, before defining any classes or functions, i test for the availability of sox, an audiocommandlinetool essential to some of my modules functions: ``` sox = 'path/to/sox' test=subprocess.Popen([sox,'-h'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) error=test.communicate()[1] if error: raise EnvironmentError((1,'Sox not installed properly'),) ``` This worked fine. Now i have updated ubuntu from 8.04 to 10.04 and the code aborts on the line of the call to subprocess.Popen, throwing the following error message: ``` File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child raise child_exception OSError: [Errno 8] Exec format error ``` I already looked for execution rights of sox, i have no other idea where to look for a solution of this. Can subprocess execution rights be limited? Any hints what could be going on here?
2011/03/17
[ "https://Stackoverflow.com/questions/5345253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/581421/" ]
`||` says: if any condition is true, It'll return true, without looking at the ones after it. So `true || false` is true, `false || true` is true. In your case, you say "if strExt is not equal to **wav** and is not equal to **mp3**, then execute the code". In case that one of them is true, it executes. I'm thinking that you're looking for the `&&` symbol. The `logical and` says "I'll return true only if every condition is true" - when it hits a false, it returns false. What I think your code should look like: ``` if (strExt!='wav' && strExt!='mp3') ```
If you want to get into second `if`, when `strExt` is not equal to both `'wav'` and `'mp3'` you need to use an `&&` operator. ``` if (strExt!='wav' || strExt!='mp3') ``` when `strExt='wav'` => `strExt!='wav'` = false; `strExt!='mp3'` = true => false or true = true and gets into `if` statement and is the case is similar when `strExt='mp3'` .
5,605,092
I would like to get the physical address of Linux "jiffies" variable so that I can read it by just reading the contents of this memory address.
2011/04/09
[ "https://Stackoverflow.com/questions/5605092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703810/" ]
For kernel code, use the functions defined in `include/linux/jiffies.h`. (`get_jiffies_64` for example). [Kernel command using Linux system calls](http://www.ibm.com/developerworks/linux/library/l-system-calls/) illustrates syscall handling in Linux with a userspace syscall that reads jiffies. Could be what you're after. [Linux obtain current of jiffies since reboot](https://superuser.com/questions/88820/linux-obtain-current-of-jiffies-since-reboot) over at superuser also has some information you could be interested in. [Converting jiffies to milli seconds](https://stackoverflow.com/questions/2731463/converting-jiffies-to-milli-seconds) is also something to keep in mind.
If you have the sources installed, ``` locate jiffies ``` schould reveal the .c and .h files, as in: ``` /usr/src/linux-headers-$(uname -r)/include/linux/jiffies.h ```
59,857,971
I keep running into an issue where I am awaiting data from a prop to do something within it inside my created hook. It keeps throwing errors such as "this.value is not defined" (As it has not yet loaded from prop) I have fixed some of these issues using `v-if` and only using as needed. However in some cases I wanted to use that prop info within my created and when that happens, I end up getting errors and am not sure how to best tell that part of the created to "wait" for the data before running. Any advice? -- *Update to add some example code.* On the App.js page, I am calling in the "userInfo" and setting it in data like so. I am doing this for two reasons. First to check if user is logged in, and secondly taking the time to save the users info as it will be used later on throughout the app. (Please note, user and userInfo are different and contain different info. User is email/password whilst userInfo is username, bio, etc.) ``` data() { return { user: null, userInfo: null, } }, created(){ //let user = firebase.auth().currentUser firebase.auth().onAuthStateChanged((user) => { if(user){ this.user = user let ref = db.collection('users') .where('user_id', '==', this.user.uid) ref.get().then(snapshot => { snapshot.forEach(doc => { this.userInfo = doc.data() }) }) } else { this.user = null } }) }, ``` Now, I pass this information down within the using v-bind. and then call it in areas I need some info using props. The issue comes when I want to do something such as - ``` if(this.userInfo) { value = true } ``` Calling this.userInfo throws an error "this.userInfo is null" (I set it to null in the data() of the page as default).
2020/01/22
[ "https://Stackoverflow.com/questions/59857971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9469439/" ]
The accepted answer provides a great solution, which set `v-if` on entire Child component in Parent component. However there's still some edge cases where your prop literally becomes empty or null if the API returns so, which eventually ends up never rendering your Child component at all though you might need to show some default texts/styles, or maybe you're working on some projects that you don't have control over the parent component. In those cases, you could internally handle this problem just fine by checking if the prop has already available in the created hook, if not, you should dynamically watch this prop until it becomes available. ``` // your component export default { props: ['userInfo'], created() { // check if the prop userInfo available or not if (this.userInfo) { // do your thing } else { // start watching this prop const unwatch = this.$watch('userInfo', () => { // do your thing when userInfo is available // tear down this watcher as you now no longer need it unwatch() }) } } } ```
There are at least two approaches I can think of: 1. Dependency injection ----------------------- The parent/root to `provide` the data/object down the component tree and the receiving end (children) to `inject` them. **Parent** ```js { data: () => ({ userInfo: null }), created() { // Populates data via Firebase // Code omitted for brevity... this.userInfo = doc.data(); }, provide() { return Object.defineProperty({}, 'userInfo', { get: () => this.userInfo }) } } ``` **Children** ```js // Children { inject: ['userInfo'], created() { if (this.userInfo) { // Do something } }, mounted() { if (this.userInfo) { // Do something } }, // Any lifecycle hooks, methods or virtually anywhere needing a reference to this object } ``` 2. Vuex store ------------- Rather than passing props and having to deal with possible asynchrony issues; you could let Vuex take care of synchronizing the states for you and stop worrying about the data being `null` or `undefined`. **Store** ```js export default { state: { userInfo: null }, mutations: { UPDATE_USER(state, payload) { state.userInfo = payload; } } } ``` **Parent/App.js** ```js export default { created() { // On firebase success callback this.$store.commit('UPDATE_USER', doc.data()); } } ``` **Children** ```js import { mapState } from 'vuex'; export default { computed: { ...mapState([ 'userInfo' ]) }, created() { }, mounted() { }, methods() { if (this.userInfo) { // Do something safely } }, // Anywhere } ```
811,711
![enter image description here](https://i.stack.imgur.com/zLzZn.png) I am having issues identifying if the following are reflexive/symmetric/antisymmetric/transitive. Could anybody help me out? I have the book definitions but I'm confused on really the application of the definition.
2014/05/27
[ "https://math.stackexchange.com/questions/811711", "https://math.stackexchange.com", "https://math.stackexchange.com/users/152086/" ]
The answer is no. Indeed,for $ k \in N$ let $\mu\_k$ be a Dirac measure concentrated at $x=0$(we consider measures on the real axis $R$). Then $\sum\_{k \in N}\mu\_k$ is not atomic measure in the above-mentioned sense
It seems that the answer is positive: If $(\mu\_n)\_{n \in \mathbb{N}}$ is a sequence of atomic measures, then the sum $\sum\_{n \in \mathbb{N}} \mu\_n$ is atomic. This has been shown by P. Capek in his paper *The atoms of a countable sum of set functions* (Mathematica Slovaca 1989, No. 1, p.81-89; [link](http://dml.cz/dmlcz/130769)).
120,121
Given two lists that contain no duplicate elements `a` and `b`, find the crossover between the two lists and output an ASCII-Art Venn Diagram. The Venn Diagram will use a squarified version of the traditional circles for simplicity. Example ======= **Given:** ``` a = [1, 11, 'Fox', 'Bear', 333, 'Bee'] b = ['1', 333, 'Bee', 'SchwiftyFive', 4] ``` **Output (Order is 100% arbitrary, as long as the Venn Diagram is correct):** ``` +-----+----+-------------+ |11 |333 |SchwiftyFive | |Fox |Bee |4 | |Bear |1 | | +-----+----+-------------+ ``` The program may either consider `'1' == 1` or `'1' != 1`, up to your implementation. You may also choose to just handle everything as strings, and only accept string input. --- **Given:** ``` a=[] b=[1,2,3] ``` **Output (Notice how the two empty parts still have the right-pad space):** ``` +-+-+--+ | | |1 | | | |2 | | | |3 | +-+-+--+ ``` --- **Given:** ``` a=[1] b=[1] ``` **Output:** ``` +-+--+-+ | |1 | | +-+--+-+ ``` Rules ===== * Elements of the Venn Diagram are left-aligned and padded to the max length entry plus 1. * The ordering of the elements within sub-sections of the Venn-Diagram are arbitrary. * Corners of the Venn Diagram (where `|` meets `-`) must be represented by a `+`. * You are garuanteed that `a.join(b).length() > 0`, if both are empty, you may do whatever. + You may even print a picture of Abe Lincoln, don't care. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") and [set-theory](/questions/tagged/set-theory "show questions tagged 'set-theory'"). Bonus ===== Charcoal renders boxes like this naturally, but the whole set theory part... Don't know how well it does that. +100 bounty for the shortest charcoal submission before I am able to add a bounty to the question (2 days from being asked).
2017/05/11
[ "https://codegolf.stackexchange.com/questions/120121", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/59376/" ]
[Husk](https://github.com/barbuz/Husk), ~~72~~ 58 bytes ======================================================= ``` mṙ1₁Fz+m(₁TT' Ṡ:→S:öR'-→▲mL)TTømėF`-FnF- Ṡz:(`:'+:'+R'|-2L ``` [Try it online!](https://tio.run/##yygtzv7/P/fhzpmGj5oa3aq0czWAdEiIusLDnQusHrVNCrY6vC1IXRfIejRtU66PZkjI4R25R6a7Jei65bnpcgFVVVlpJFipawNRkHqNrpHP////o6OVDJV0lAxBhFt@BZB0Sk0sAlLGxsZgTqpSrA5EDUJERyk4OaM8M62k0i2zDMQ1UYqNBQA "Husk – Try It Online") Husk does not support arrays of multiple types, so the arguments must be string arrays. I am not sure whether I want to explain this monstrosity. Due to it's sheer size, it takes about 28 secs(due to type inference) for the first test case mentioned. Without some of the type inference issues, this could be a lot shorter. -14 bytes with a lot of adjustments(I got better at Husk).
[Python 2](https://docs.python.org/2/), ~~221~~ ~~210~~ 212 bytes ================================================================= ```python m=map A,B=m(set,input()) d=A-B,B&A,B-A e=[max(m(len,s))+1for s in d] p,i,n='+|\n' o=b=p+p.join(m('-'.__mul__,e))+p+n while sum(m(len,d)):o+=i+i.join(m(str.ljust,[len(s)and s.pop()or''for s in d],e))+i+n print o+b ``` [Try it online!](https://tio.run/nexus/python2#TY3NboMwEITvfgqfura8ICF6quQDHPICPVKESHGUjfCPsGlSqe9OHZpKuexodme@3ay2Y2ANttqKaBKSC2sSUrJJN0WL7Us@FQ0zurPjTVgxG4dRSlWd/MIjJ8enngUkdBrUz4cD5vVRBxXKiyeXC1BAOQx2nYcBTS4G5dj1TLPhcbUP4CTlm1eaFP23YlrK@bLGhF0OiChHN/FYBh@E9AvA0/edSpkaFnKJe3Xctq6DCpBDtc@Dv92lNeNy17qu/6yBHh/Bp12W98/zlU7p@0Bfu3@Fvv8F "Python 2 – TIO Nexus")
73,065,922
I am trying to use Unix's comm command to compare two files in Tcl. I tried the below to no avail: ``` exec bash -c {comm -2 -3 <(sort file1) <(sort file2) > only_in_file1} exec {comm -2 -3 <(sort file1) <(sort file2) > only_in_file1} ``` It is one of the quick way that I know to do so but if there is a method in Tcl, I would like to be introduced. In general, I would need to compare two files and find unique lines in only one of the files when the two files are lines of text of 10~100K lines.
2022/07/21
[ "https://Stackoverflow.com/questions/73065922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18627911/" ]
Using boolean arithmetics: ``` N = 3 m1 = df['values'].le(0) m2 = df.groupby(m1.cumsum())['values'].transform('count').gt(N) df['period'] = (m1&m2).cumsum().where((~m1)&m2) ``` output: ``` values period 1 0 NaN 2 8 NaN 3 1 NaN 4 0 NaN 5 5 1.0 6 6 1.0 7 4 1.0 8 7 1.0 9 0 NaN 10 2 2.0 11 9 2.0 12 1 2.0 13 0 NaN ``` intermediates: ``` values m1 m2 CS(m1) m1&m2 CS(m1&m2) (~m1)&m2 period 1 0 True False 1 False 0 False NaN 2 8 False False 1 False 0 False NaN 3 1 False False 1 False 0 False NaN 4 0 True True 2 True 1 False NaN 5 5 False True 2 False 1 True 1.0 6 6 False True 2 False 1 True 1.0 7 4 False True 2 False 1 True 1.0 8 7 False True 2 False 1 True 1.0 9 0 True True 3 True 2 False NaN 10 2 False True 3 False 2 True 2.0 11 9 False True 3 False 2 True 2.0 12 1 False True 3 False 2 True 2.0 13 0 True False 4 False 2 False NaN ```
You can try ```py sign = np.sign(df['values']) m = sign.ne(sign.shift()).cumsum() # continuous same value group df['period'] = (df[sign.eq(1)] # Exclude non-positive numbers .groupby(m) ['values'].filter(lambda col: len(col) >= 3) .groupby(m) .ngroup() + 1 ) ``` ``` print(df) values period 1 0 NaN 2 8 NaN 3 1 NaN 4 0 NaN 5 5 1.0 6 6 1.0 7 4 1.0 8 7 1.0 9 0 NaN 10 2 2.0 11 9 2.0 12 1 2.0 13 0 NaN ```
6,888,297
``` public class Car { public char color; public char getColor() { return color; } public void setColor(char color) { this.color = color; } } public class MyCar { private Car car = null; public MyCar() { this.car = new Car(); car.color = 'R'; } } ``` Which OOPS principle does the above code violate? • Abstraction • Encapsulation • Polymorphism • None of the above I understand that Encapsulation is the answer to this problem. Just wanted to know if other option is also true.
2011/07/31
[ "https://Stackoverflow.com/questions/6888297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778896/" ]
Well, I would view it in these terms: * Encapsulation: by allowing direct access to the `color` *field*, the `Car` class is exposing an implementation detail. Ignacio has shown that he doesn't view this type of violation as one of encapsulation, but of data hiding - my own view of the word "encapsulation" is that it includes data hiding. That just goes to show how these words can be used in different ways. * Polymorphism: judging by the names `MyCar` and `Car` should potentially implement a common interface or have a common base class. At least, the classes given can't be used polymorphically. * Abstraction: I would argue that using `char` as the abstraction for a color is inappropriate. Whether that's an abstraction violation or not again depends on what you mean by "abstraction violation".
Information hiding is violated in Car. I think other principles are formally respected, ie. nothing stops me from having a MyCar class wrapping the Car class if the two classes are not intended to be used polymorphically. One could argue that it is just bad design, and I would agree. The same applies to using char as a color: it's probably bad design, but IMHO nothing formally against OOP principles.
33,177
Is there an Android app that enables hand-writing / drawing on a word document? I want to draw and write on the text. I don't want to edit the document, but write on the top of it. Instead of typing the letters using the keyboard, I want to draw on the text. Just like writing / drawing on a picture, I would like to draw on a word document. I have been looking for this everywhere, can anyone suggest me a good app that can do this? Thanks.
2012/11/10
[ "https://android.stackexchange.com/questions/33177", "https://android.stackexchange.com", "https://android.stackexchange.com/users/23432/" ]
In the Play store there is a 'installed' tab which as the name implies is of currently installed applications. The 'all' tab shows apps which have ever been installed on the device. If you don't want a application to show up in this list, then from the phone open Play store, go into your My Apps and on the All tab you can click the circular remove icon to the right of the app will remove it from your Play account. [This is what it should look like.](https://i.stack.imgur.com/JH8RX.png)
Deleting cache and data of the Play store app solved the problem for me.
4,896,446
I've written a application and using 6 timers that must start after each other but these timers don't work properly. I don't know much about timers. For example, timer1 start and something happen in application. then timer1 must stop forever and timer2 must start immediately and something happen in application. Then timer2 must stop forever and timer3 must start and so on. Please help. Here is my code: ``` int yyyy = 0; void move() { yyyy++; if (yyyy <= 1) { timer1.Start(); timer1.Interval = 15; timer1.Tick += new EventHandler(timer_Tick1); } if (yyyy <= 2) { timer2.Start(); timer2.Interval = 15; timer2.Tick += new EventHandler(timer_Tick2); } if (yyyy <= 3) { timer3.Start(); timer3.Interval = 15; timer3.Tick += new EventHandler(timer_Tick3); } if (yyyy <= 4) { timer4.Start(); timer4.Interval = 15; timer4.Tick += new EventHandler(timer_Tick4); } if (yyyy <= 5) { timer5.Start(); timer5.Interval = 15; timer5.Tick += new EventHandler(timer_Tick5); } if (yyyy <= 6) { timer6.Start(); timer6.Interval = 15; timer6.Tick += new EventHandler(timer_Tick6); } } ``` and: (for timer2 for example). ( all timers have exactly same below code). ``` int t = 0; private void timer_Tick2(object sender, EventArgs e) { t++; if (t <= 150) { // do somthing } else timer2.Stop(); } ```
2011/02/04
[ "https://Stackoverflow.com/questions/4896446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602869/" ]
It sounds like you don't need six timers - you need *one* timer, which does one of six actions when it fires, depending on the current state. I think that would lead to much simpler code than starting up multiple timers.
The first thing to consider here, is that if all 6 timers have the *exact* same code, I'm certain that your better of using only one timer, and instead keep a state that let's you know if you are in mode 1,2,3,4,5 or 6. This will also remove the need to stop the first timer, and start the new one. So have a class variable called State that starts out as 1. When *something* happens in the application, set the state to 2, and let the original timer keep on running. Having 6 code blocks that are identical will almost guarantee you that some time when you change the code, you will make a mistake in at least 1 of those 6 duplicates.
61,987,967
So I have this assignment where I have to create a Winforms table data and display it. I have created first form (DataGridView) to display the detail of the product view with function add, modify buttons to it, and the second form which allows me to enter the product id and product name and save the data as well. But while putting my code on the second form and put the: if (validation section) I got an error if it doesn't exist or I need a definition to it. However I will following a guide example step by step but I'm not sure how they fix or overcame that issues. ``` namespace TravelProduct { public partial class frmModifyProduct : Form { public bool isAdd; // main form sets it - is it Add or Modify? public Product currentProduct; // main form sets it - the current products public frmModifyProduct() { InitializeComponent(); } private void frmModifyProduct_Load(object sender, EventArgs e) { if (isAdd) { txtproductid.Enabled = true; txtproductid.Focus(); // focus of the first text box } else { DisplayCurrentProduct(); // display data of the current product txtproductid.Enabled = false; // code is not updatable txtproductname.Focus(); // focus on description } } private void DisplayCurrentProduct() { txtproductid.Text = currentProduct.ProductId.ToString(); txtproductname.Text = currentProduct.ProdName; } private void ClearTextBoxes() { txtproductid.Text = ""; txtproductname.Text = ""; } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void btnSave_Click(object sender, EventArgs e) { if (isAdd) { (this part is where I have error on the validation part, where I have to select using system or fix variable or something) if (Validator.IsPresent(txtproductid, "Productid") && Validator.IsInt32(txtproductid, "Productid") && Validator.IsCorrectLength(txtproductname, "ProductName", 10) && ) { Product newProduct = new Product // object initiallizer { ProductId = Convert.ToInt32(txtproductid.Text), ProdName = txtproductname.Text }; using (ProductDataContext dbContext = new ProductDataContext()) { // insert through data context object dbContext.Products.InsertOnSubmit(newProduct); dbContext.SubmitChanges(); // submit to the database } DialogResult = DialogResult.OK; } else // validation failed { DialogResult = DialogResult.Cancel; } } else // it is Modify { if (Validator.IsInt32(txtproductid, "Productid") && Validator.IsPresent(txtproductname, "ProdName") ) { try { using (ProductDataContext dbContext = new ProductDataContext()) { // get the product with Code from the current text box Product prod = dbContext.Products.Single (p => p.ProductId == Convert.ToInt32(txtproductid.Text));// lambda expression if (prod != null) { prod.ProdName = txtproductname.Text; dbContext.SubmitChanges(); } } } catch (ChangeConflictCollection) { MessageBox.Show("Another user changed or deleted the current record", "Concurrency Exception"); DialogResult = DialogResult.Retry; } catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString()); } } else // validation failed { DialogResult = DialogResult.Cancel; } } } } } ```
2020/05/24
[ "https://Stackoverflow.com/questions/61987967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12815504/" ]
The method is exposed as part of the `DocumentPrototype` object, accessible under `window.Document.prototype`: The `window.document` instance only inherits it from the `Document` class. ```js console.log( Document.prototype.getElementById ); Document.prototype.getElementById = (val) => 'gotcha ' + val; console.log( document.getElementById( 'foo' ) ); ``` Now, the native function being a native function, browsers don't give us access to it, and certainly, it's not even a JS function.
It will depend on native code (probably in C++) that is part of the browser. You could search for getElementById in the source code of a web browser to look at it. JavaScript is an interpreted language; every web browser has a JavaScript interpreter. When you write JavaScript yourself, you can define methods on objects. However, what you can't do from JavaScript is write native methods; these have to be provided as part of the browser. If you try to print the source of these functions from JavaScript with toSource, you see a note indicating that these functions are in fact native. ```js console.log((function(){}).toSource()); console.log(alert.toSource()); ``` The point of native code is that it can access things which are deliberately inaccessible to JS code. For example, events can be scheduled with `window.setTimeout` despite there being absolutely no way to implement `setTimeout` in plain JS. Browsers have huge codebases, none of which I'm familiar with, so it's difficult to express in a short answer exactly they work. However, to give you a taste of their workings, [Chromium's element.cc](https://github.com/chromium/chromium/blob/d99d67668633c97b87bd605f715f4a3afc5fa18a/third_party/blink/renderer/core/dom/element.cc) contains implementations for familiar methods like `setAttribute` and [in container\_node.cc](https://github.com/chromium/chromium/blob/5b81f8730e3f6c960fc7ebb870c5a155c30b1609/third_party/blink/renderer/core/dom/container_node.cc#L1565) there is an implementation of `getElementById`.
26,433,561
I can search exact matches from Google by using quotes like `"system <<-"`. How can I do the same thing for GitHub?
2014/10/17
[ "https://Stackoverflow.com/questions/26433561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170931/" ]
If your search term is a filename or other substring which contains punctuation characters, a partial workaround to get GitHub's code search to return instances of that substring is to (1) replace the punctuation characters in your search term with spaces, and (2) enclose the search term in quotes. For example, instead of using the search term: * `repo:my_repo my_image_asset_1.svg` Try: * `repo:my_repo "my image asset 1 svg"` This might not be a perfect solution in all cases; I imagine it might also match filenames like `my-image-asset-1.svg`. But depending on your use case, it might be "good enough"?
If you **quickly want to search inside a specific repo**, try that: * Press `.` while viewing the repo to open it inside a browser-based VS Code window * Enter your search term into the menu on the left * Enable indexing [![enter image description here](https://i.stack.imgur.com/8Z5apm.png)](https://i.stack.imgur.com/8Z5apm.png)
2,255,008
Using my not-outstanding Google skills, I have not been able to find a decent tutorial on Groovy for Ruby programmers. There are a lot of political pieces (Ruby is great! Groovy is great!) and tiny little contrasts, but I really don't care which is better. I know Ruby (and Java) relatively well, and I'd like to learn Groovy. Would anybody care to (either provide an amazing link or) mark some differences between the two languages in terms of how to do things (syntactic, class declaration, loops, blocks, etc.)? For my purposes you can assume full Java competence to explain. Again, I am not interested in knowing which is better. Just need to know how to do stuff....
2010/02/12
[ "https://Stackoverflow.com/questions/2255008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
Did you see [this](http://blog.headius.com/2008/04/converting-groovy-to-ruby.html) and [this](http://www.glenstampoultzis.net/blog/?p=61)? Relatively short posts, I know. You're right; there doesn't appear to be much... update: [two](http://www.javabeat.net/articles/16-introduction-to-groovy-scripting-language-1.html) more [links](http://groovy.codehaus.org/Differences+from+Java).
We need more questions like this one. Three years after the question, there's still a comparitive lack of information on this moving betwen these two similar languages. I did find this Slide Share presentation, which covers a lot of basic ground. * **[Comparing groovy and (j)ruby](http://fr.slideshare.net/dnosenko/comparing-groovy-andjrubynealford)** And this blog post was helpful with 'simple' stuff because it give a bit more background: * **[Thoughts on Groovy](http://smellsblue.blogspot.com.au/2008/06/thoughts-on-groovy.html)** The reasons to switch between languages usually have more to do with project needs than a language itself and I feel its important able to swap and compare between tools. One standard resource for this kind of question is: **[Rosetta Code](http://rosettacode.org/wiki/Groovy)**. Hope to see some more tips added to this list. Cheers, Will
3,098,737
> > Prove that $\lim\_{(x,y)\to(0,0)}(xy+y^{3})=0$. > > > I am trying to determine how to set the $\delta$. Here is my rough work, which isn't much: $|f(x,y)-0|=|xy+y^{3}|\leq |y||x+y^{2}|$ I am not sure whether I should separate $y$ or separate $xy$ and $y^{3}$ to make it $|xy| + |y^{3}|$. Any ideas how to finish?
2019/02/03
[ "https://math.stackexchange.com/questions/3098737", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
**Hint** For $\vert x \vert, \vert y \vert \le 1$, you have $$\vert xy+y^3 \vert \le \vert x \vert \vert y \vert + \vert y \vert^3 \le \vert x \vert \vert y \vert + \vert y \vert\le 2 \vert y \vert$$
Using polar coordinates (not really necessary here, but useful in harder cases): $$|xy + y^3| = |r^2\cos\theta\sin\theta + r^3\sin^3\theta|\le r^2 + r^3,$$ and $r = \|(x,y)\|$ (euclidean norm), so...
43,407
I am trying to make a transportable charger for iPhones, but before I can start this I need to know how much power my iPhone uses when I make an emergency call. If nobody knows this, I will be glad to have any information related to this.
2012/03/12
[ "https://apple.stackexchange.com/questions/43407", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/20006/" ]
[Anandtech](http://www.anandtech.com/show/4971/apple-iphone-4s-review-att-verizon/15) has some nice charts detailing the wattage of the iPhone 4S running various apps, which could be a good starting point for you. You may also want to check out existing kits/projects, such as [MintyBoost](http://www.ladyada.net/make/mintyboost/) - they seem to work reasonably well with iPhones. There's a specific MintyBoost [page](http://www.ladyada.net/make/mintyboost/icharge.html) detailing Apple device charging that may also yield some useful info.
The power use is going to vary somewhat depending on external factors on the RF side. Network mode in use (GSM/3G) and the power required to establish a stable connection to the cell site in use together with any other usage on the device (speaker/bluetooth/GPS) Best guess is that your baseline should be the specified 1A required to charge the device and work up/down from there with a meter connected
3,430,447
I'm new to MVC and I'm implementing the Nerd Dinner MVC sample app in MS MVC2. I'm on step 10, "Ajax enabling RSVPs accepts". I've added the new RSVP controller and added the Register action method like so: ``` public class RSVPController : Controller { DinnerRepository dinnerRepository = new DinnerRepository(); // // AJAX: /Dinners/RSVPForEvent/1 [Authorize, AcceptVerbs(HttpVerbs.Post)] public ActionResult Register(int id) { Dinner dinner = dinnerRepository.GetDinner(id); if (!dinner.IsUserRegistered(User.Identity.Name)) { RSVP rsvp = new RSVP(); rsvp.AttendeeName = User.Identity.Name; dinner.RSVPs.Add(rsvp); dinnerRepository.Save(); } return Content("Thanks - we'll see you there!"); } } ``` I added the references to both Ajax script libraries and added the code below to the Details view as described in the article: ``` <div id="rsvpmsg"> <% if(Request.IsAuthenticated) { %> <% if(Model.IsUserRegistered(Context.User.Identity.Name)) { %> <p>You are registred for this event!</p> <% } else { %> <%= Ajax.ActionLink( "RSVP for this event", "Register", "RSVP", new { id=Model.DinnerID }, new AjaxOptions { UpdateTargetId="rsvpmsg"}) %> <% } %> <% } else { %> <a href="/Account/Logon">Logon</a> to RSVP for this event. <% } %> </div> ``` When I click the "RSVP for this event" link I get a 404 eror saying the resource cannot be found: ``` The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /NerdDinner/RSVP/Register/24 Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4205 ``` When I step into the code it is finding the Register action method correctly. After playing around with it I removed the "AcceptVerbs(HttpVerbs.Post)" from the constraint on the Register method, and it then worked. However it didn't reload the page it just displayed the "Thanks - we'll see you there" message on a new blank page. Looking at the html in the details page there is no Form submit taking place, so I'm wondering does the Ajax code need something more to make the call a Post? Is there a known issue with this part of the Nerd Dinner app? I think the app was written in MVC1 and I'm using MVC2 - does this make a diference? TIA, Ciaran
2010/08/07
[ "https://Stackoverflow.com/questions/3430447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177347/" ]
This portion of your action explains why you just get the "see you there" message: ``` return Content("Thanks - we'll see you there!"); ``` That's all that's being returned. The reason you were getting a 404 to begin with is the use of an actionlink: ``` Ajax.ActionLink(... ``` That will create a URL link, a GET not a POST, and the `AcceptVerbs(HttpVerbs.Post)` would have forced no match. You should submit a form to do a post: ``` using (Ajax.BeginForm("Controller", "Action", new AjaxOptions { UpdateTargetId = "f1" } )) { %> <div id="f1"> <!-- form fields here --> <input type="submit" /> </div> <% } %> ```
As an additional comment to debugging issues with this problem, being a Java/JSF developer, I ran into a hard lesson that ``` <script src="/Scripts/MicrosoftAjax.js" type="text/javascript" /> ``` and ``` <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script> ``` are processed differently. The first not working at all and the second working correctly.
59,037,856
im trying to create a component in react native. The example of the component is: ```js import React from 'react' import PropTypes from 'prop-types' import { View, Text, Image } from 'react-native' const MyComponent = ({Text, Image}) => { return ( <Text>{Text}</Text> <Image source={require('../../assets/images/HeaderLogo.png')} /> ) } MyComponent.propTypes = { Text: PropTypes.string, Image: PropTypes.string, } export default MyComponent ``` If i remove the component, everything works nice and well, but when i try with the image component, it returns the error on the following image: [![enter image description here](https://i.stack.imgur.com/cqzb3.png)](https://i.stack.imgur.com/cqzb3.png) (It works with a icon, but not with a image.) the component is imported as follow: ```js import MyComponent from './MyComponent' ``` If i change the import to: ```js import { MyComponent } from './MyComponent' ``` i get another error (As following): [![enter image description here](https://i.stack.imgur.com/4Iw0T.png)](https://i.stack.imgur.com/4Iw0T.png)
2019/11/25
[ "https://Stackoverflow.com/questions/59037856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12368797/" ]
You are passing **Text** and **Image** as arguments (props) to your function. 1. Not sure where you are using the image prop; if you aren't you should remove it. 2. **As for the Text argument, you need to change this to *text* with lowercase *t***. Anything you pass as prop is essentially an argument to a function. Using an Uppercase T conflicts with the JSX Text element, which is used in your render function and is typed **< Text >** in order to render the relevant UI element. in short, remove all capitalised references to the **text** and **image** arguments you pass in. Your code should look like this: ``` import React from 'react' import PropTypes from 'prop-types' import { View, Text, Image } from 'react-native' const MyComponent = ({text}) => { return ( <Text>{text}</Text> <Image source={require('../../assets/images/HeaderLogo.png')} /> ) } MyComponent.propTypes = { text: PropTypes.string, } export default MyComponent ```
Try importing and using Image like this ``` import myIMage from '../../sourcefile.png' const Component = (props) => { return ( <View> <View /> <Image source={myImage} style={{height: 100, width: 100}} /> //style is important here </View> export default Component; ```
16,092,951
Is it possible to exclude a column from my WebAPI's IQueryable function? e.g. How would I exclude the property "FirstName" from my people entity: ``` [HttpGet] public IQueryable<Contact> GetPeople() { return _contextProvider.Context.People; } ``` pseudocoded: ``` [HttpGet] public IQueryable<Contact> GetPeople() { return _contextProvider.Context.People.ExcludeColumn("FirstName"); } ```
2013/04/18
[ "https://Stackoverflow.com/questions/16092951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612628/" ]
Project results manually to `Contact` entity, and do not provide data for `FirstName` column: ``` [HttpGet] public IEnumerable<Contact> GetPeople() { return from p in _contextProvider.Context.People select new Contact { Id = p.Id, LastName = p.LastName }; } ``` BTW I'd create some other specific DTO object which don't have `FirstName` property.
Another method is to decorate the column with `Runtime.Serialization.IgnoreDataMember` like this. ``` [Runtime.Serialization.IgnoreDataMember] public string FirstName { get; set; } ```
66,868,663
I am having `jsconfig.json` in my root directory using `Nuxt.js` project. And I am having an error: ``` File '/home/mike/Documents/nuxt/node_modules/dotenv/types' not found. The file is in the program because: Root file specified for compilation ``` Actually 5 errors in a first line of `jsconfig.json`: [![Errors](https://i.stack.imgur.com/5G43x.png)](https://i.stack.imgur.com/5G43x.png) I don't even use `typescript` and I didn't set any `typescript` options while creating `Nuxt.js project` `jsconfig.json` content: ``` { "compilerOptions": { "baseUrl": ".", "paths": { "~/*": ["./*"], "@/*": ["./*"], "~~/*": ["./*"], "@@/*": ["./*"] } }, "exclude": ["node_modules", ".nuxt", "dist"] } ``` I don't understand where they come from. How do I get rid of this errors? There's no option `quick fix` so I can't `ignore errors for entire file`
2021/03/30
[ "https://Stackoverflow.com/questions/66868663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14923276/" ]
Just reload VSCode by typing `ctrl + shift + p` then type `reload window` and it should work.
I ran into this and just exiting and relaunching VSCode (from the icon) seemed to fix it. I'd originally started via `code .` so I'm thinking perhaps the instance with the error had picked up a weird env var from my terminal.
2,689,947
In particular I mean: $$\sin(x)^2 + \cos(x)^2$$ $$=\left(\sum\_{n=0}^{\infty} (-1)^n \frac{x^{2n+1}}{(2n+1)!}\right)^2 + \left(\sum\_{n=0}^{\infty} (-1)^n \frac{x^{2n}}{(2n)!}\right)^2$$ However I am not sure how you're supposed to correctly expand and recombine terms when dealing with the sum of two squared series, especially when there are factorials involved. Edit: To be clear, I am asking about manipulating the series I have just stated in order to show that they sum to $1$.
2018/03/13
[ "https://math.stackexchange.com/questions/2689947", "https://math.stackexchange.com", "https://math.stackexchange.com/users/539262/" ]
Absolutely. Power series actually multiply just like polynomials do: $$(a\_0+a\_1x+a\_2x^2+a\_3x^3+\ldots)(b\_0+b\_1x+b\_2x^2+\ldots)=\sum\_{n=0}^{\infty}\left(\sum\_{c=0}^na\_cb\_{n-c}\right)x^n.$$ Let $$\alpha(x)=\left(\sum\_{n=0}^{\infty} (-1)^n\frac{x^{2n+1}}{(2n+1)!}\right)^2$$ $$\beta(x)=\left(\sum\_{n=0}^{\infty} (-1)^n\frac{x^{2n}}{(2n)!}\right)^2.$$ First, it is clear that the constant term of $\alpha(x)+\beta(x)$ is indeed $1$, as we can check directly. Thus, we merely need to check that every other coefficient vanishes. Note that, either from the formula for products or by noting that both are even functions, all the coefficients of odd powers of $x$ in both $\alpha$ and $\beta$ and thus $\alpha+\beta$ vanish. Now, consider the coefficient of $x^{2n}$ in either. In $\beta$, the formula gives the coefficient of $x^{2n}$ as, where we use the variable $k$ to count only the even (non-zero) coefficients of $\cos(x)$: $$\sum\_{k=0}^n(-1)^c\cdot (-1)^{n-k}\cdot \frac{1}{(2n-2k)!}\cdot \frac{1}{(2k)!}=(-1)^n\cdot \sum\_{k=0}^n\frac{1}{(2k)!(2n-2k)!}.$$ The same can be done to find the coefficient of $x^{2n}$ in $\alpha$, using $k$ to enumerate odd coefficients of $\sin(x)$: $$\sum\_{k=0}^{n-1}(-1)^k\cdot (-1)^{n-k-1}\cdot \frac{1}{(2n-2k-1)!}\cdot \frac{1}{(2k+1)!}=(-1)^{n-1}\cdot \sum\_{k=0}^{n-1}\frac{1}{(2k+1)!(2n-2k-1)!}.$$ We are trying to show that the coefficient of $x^n$ in $\alpha+\beta$ is zero for $n>0$. This amounts to showing the following equality for all $n>0$: $$\sum\_{k=0}^{n-1}\frac{1}{(2k+1)!(2n-2k-1)!}=\sum\_{k=0}^n\frac{1}{(2k)!(2n-2k)!}.$$ Multiplying through by $(2n)!$ on both sides reduces this to a combinatorial equality: $$\sum\_{k=0}^{n-1}{2n\choose 2k+1} = \sum\_{k=0}^n{2n\choose 2k}.$$ This just says that the number of subsets of $2n$ with an odd number of elements equals the number of subsets of $2n$ with an even number of elements - but this is easy to show: We can define a bijection $\pi$ which takes a set $S\subseteq \{1,\ldots,2n\}$ and takes it to $S\cup \{1\}$ if $1\not\in S$ and $S\setminus \{1\}$ if $1\in S$. This places sets of odd and even parity into bijection, showing the desired equality.
Note that just using their series $$\sin^2 x + \cos^2 x=(\cos x+i\sin x)(\cos x-i\sin x)\stackrel{\text{by series}}=e^{ix}e^{-ix}=1$$
62,296,032
What is the time complexity of this code to find if the number is power of 2 or not. Is it **O(1)**? ``` bool isPowerOfTwo(int x) { // x will check if x == 0 and !(x & (x - 1)) will check if x is a power of 2 or not return (x && !(x & (x - 1))); } ``` ### [LeetCode 231](https://leetcode.com/problems/power-of-two/)
2020/06/10
[ "https://Stackoverflow.com/questions/62296032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8548556/" ]
Yes, It is O(1), but Time complexity for bitwiseAnd(10^9,1) bitwiseAnd(10,1) are not same even though they both are O(1). In reality, there are 4 basic operations involved in your equation itself, which we consider as basic and unit operations in terms of the power of computing that it does. But in reality, These basic operations also have a cost of 32 or 64 operations as 32 or 64 bits are used to represent a number in most of the cases. So this O(1) time complexity means that the worst time complexity is of 32 or 64 operations in terms of computing and since 32 and 64 both are very low values and thses operations are performed on machine level so that's why we do not think much about the time these unit steps require to perform their function.
Yes the code is time complexity O(1) because the running time is constant and does not depend on the size of the input.
31,289,296
I have been talking to less/css developers and they would like to do static code analysis on there less code. I was wondering if there is a plugin for sonar that can do this analysis on the less code instead of the generated css code?
2015/07/08
[ "https://Stackoverflow.com/questions/31289296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420578/" ]
The styling of the anchor's title is handled by the user agent. If you want to style a tool tip yourself, you would have to implement it. For more information see [here](http://www.w3.org/TR/html401/struct/global.html#adef-title)
It is impossible. But you could use something else, instead of "native" title. Add your own custom attribute and do some javascript/css to display a tooltip. ex: ``` <a href="linkstowhatyouwant" data-mytitlecustom="click here" class="tooltipped"> ``` and with jQuery/Javascript/CSS, you detect when mouse is over a **#tooltipped** element. And you display the tooltip that you can design **the way you want** with css. Or maybe just find such a plugin somewhere, I m sure it exists... e.g. <https://jqueryui.com/tooltip/>
45,229,032
``` #include<bits/stdc++.h> using namespace std; main() { vector<vector<int> > v; for(int i = 0;i < 3;i++) { vector<int> temp; for(int j = 0;j < 3;j++) { temp.push_back(j); } //cout<<typeid(temp).name()<<endl; v[i].push_back(temp); } } ``` I am trying to assign to a two dimensional vector. I am getting the following error ``` No matching function for call to std ::vector<int>::push_back(std::vector<int> &) ```
2017/07/21
[ "https://Stackoverflow.com/questions/45229032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6672853/" ]
**Problem:** Your vector `v` is empty yet and you can't access `v[i]` without pushing any vector in v. **Solution:** Replace the statement `v[i].push_back(temp);` with `v.push_back(temp);`
Just do it... ============= ``` #include<bits/stdc++.h> using namespace std; int main() { vector<vector<int> > v; for(int i = 0; i < 3; i++) { vector<int> temp; for(int j = 0; j < 3; j++) { temp.push_back(j); } v.push_back(temp);//use v instead of v[i]; } } ```
36,617,682
I'm having trouble importing an .sql dump file with docker-compose. I've followed the docs, which apparently will load the .sql file from docker-entrypoint-initdb.d. However, when I run `docker-compose up`, the sql file is not copied over to the container. I've tried stopping the containers with `-vf` flag, but that didn't work either. Am I doing something wrong in my .yml script? I have dump.sql in the directory database/db-dump/ in the root where my compose file is. ``` frontend: image: myimage ports: - "80:80" links: - mysql mysql: image: mysql ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: rootpass MYSQL_USER: dbuser MYSQL_PASSWORD: userpass MYSQL_DATABASE: myimage_db volumes: - ./database/db-dump:/docker-entrypoint-initdb.d ```
2016/04/14
[ "https://Stackoverflow.com/questions/36617682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1279007/" ]
After many attempts with the volumes setting i found a workaround I created another image based on mysql with the following in the Dockerfile ``` FROM mysql:5.6 ADD dump.sql /docker-entrypoint-initdb.d ``` Then removed the volumes from compose and ran the new image ``` frontend: image: myimage ports: - "80:80" links: - mysql mysql: image: mymysql ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: rootpass MYSQL_USER: dbuser MYSQL_PASSWORD: userpass MYSQL_DATABASE: myimage_db ``` This way the dump is always copied over and run on startup
Mysql database dump **schema.sql** is residing in the **/mysql-dump/schema.sql** directory and it creates tables during the initialization process. docker-compose.yml: ``` mysql: image: mysql:5.7 command: mysqld --user=root volumes: - ./mysql-dump:/docker-entrypoint-initdb.d environment: MYSQL_DATABASE: ${MYSQL_DATABASE} MYSQL_USER: ${MYSQL_USER} MYSQL_PASSWORD: ${MYSQL_PASSWORD} MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} ```
16,543,528
I installed BB tools for Eclipse, just added and removed BB Nature to one of my projects. And now, I can't compile it (for Android). ![enter image description here](https://i.stack.imgur.com/Bpak7.jpg) Eclipse told me about some troubles in AndroidManifest.xml: **native-code: armeabi AndroidManifest.xml /VitocarsAndroidApp AndroidManifest.xml BlackBerry Verifying Problem** But the manifest is OK, no one line is highlighted: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.asap.vitocarsandroidapp" android:versionCode="5" android:versionName="1.04" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <application android:name="com.asap.vitocarsandroidapp.system.VitocarsApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.asap.vitocarsandroidapp.LoginActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.asap.vitocarsandroidapp.TableViewActivity" android:label="@string/title_activity_table_view" > </activity> <activity android:name="com.asap.vitocarsandroidapp.PartActivity" android:label="@string/title_activity_part" > </activity> <activity android:name="com.asap.vitocarsandroidapp.PhotoViewActivity" android:label="@string/title_activity_photo_view" > </activity> <activity android:name="com.asap.vitocarsandroidapp.UserRegisterActivity" android:label="@string/title_activity_user_register" > </activity> <activity android:name="com.asap.vitocarsandroidapp.ConfirmPhoneActivity" android:label="@string/title_activity_confirm_phone" > </activity> <activity android:name="com.asap.vitocarsandroidapp.OfficeActivity" android:label="@string/title_activity_office" > </activity> <activity android:name="com.asap.vitocarsandroidapp.PriceOfferActivity" android:label="@string/title_activity_price_offer" > </activity> <activity android:name="com.asap.vitocarsandroidapp.RegionOrderActivity" android:label="@string/title_activity_region_order" > </activity> <activity android:name="com.asap.vitocarsandroidapp.MapView" android:label="@string/title_activity_map_view" > </activity> </application> </manifest> ``` I already spent a lot of time, trying to solve it. Maybe, somebody can help me?
2013/05/14
[ "https://Stackoverflow.com/questions/16543528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331598/" ]
Following example shows a simplest way to serialize `struct` into `char` array and de-serialize it. ``` #include <iostream> #include <cstring> #define BUFSIZE 512 #define PACKETSIZE sizeof(MSG) using namespace std; typedef struct MSG { int type; int priority; int sender; char message[BUFSIZE]; }MSG; void serialize(MSG* msgPacket, char *data); void deserialize(char *data, MSG* msgPacket); void printMsg(MSG* msgPacket); int main() { MSG* newMsg = new MSG; newMsg->type = 1; newMsg->priority = 9; newMsg->sender = 2; strcpy(newMsg->message, "hello from server\0"); printMsg(newMsg); char data[PACKETSIZE]; serialize(newMsg, data); MSG* temp = new MSG; deserialize(data, temp); printMsg(temp); return 0; } void serialize(MSG* msgPacket, char *data) { int *q = (int*)data; *q = msgPacket->type; q++; *q = msgPacket->priority; q++; *q = msgPacket->sender; q++; char *p = (char*)q; int i = 0; while (i < BUFSIZE) { *p = msgPacket->message[i]; p++; i++; } } void deserialize(char *data, MSG* msgPacket) { int *q = (int*)data; msgPacket->type = *q; q++; msgPacket->priority = *q; q++; msgPacket->sender = *q; q++; char *p = (char*)q; int i = 0; while (i < BUFSIZE) { msgPacket->message[i] = *p; p++; i++; } } void printMsg(MSG* msgPacket) { cout << msgPacket->type << endl; cout << msgPacket->priority << endl; cout << msgPacket->sender << endl; cout << msgPacket->message << endl; } ```
Ok I will take the [example](http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/tutorial.html) from the boost web site as I don't understand what you can not understand from it. I added some comments and changes to it how you can transfer via network. The network code itself is not in here. For this you can take a look at [boost::asio](http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio.html). ``` int main() { // create and open a character archive for output // we simply use std::strinstream here std::stringstream ofs; // create class instance const gps_position g(35, 59, 24.567f); // save data to archive { boost::archive::text_oarchive oa(ofs); // write class instance to archive oa << g; // archive and stream closed when destructors are called } // now we have const char* ofs.str().c_str() // transfer those bytes via network // read them on the other machine gps_position newg; { // create and open an archive for input std::stringstream ifs(the_string_we_read_from_the_network); boost::archive::text_iarchive ia(ifs); // read class state from archive ia >> newg; // archive and stream closed when destructors are called } return 0; } ```
6,656,651
The documentation says that 160 dp (density-independent) equals 1 inch. And 72 pt is also 1 inch. So I don't see why android define a dp measurement while it seems to work the same as points. Can anybody explain that? Why should I use dp if I can use pt?
2011/07/11
[ "https://Stackoverflow.com/questions/6656651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839680/" ]
The Android documentation used to incorrectly state that 160 dp always equals 1 inch regardless of screen density. This was reported as a [bug](http://code.google.com/p/android/issues/detail?id=21159) which was accepted and the documentation updated. From the updated documentation: 160 dp will NOT always equal 1 inch, it will vary with different screen sizes and densities. On a screen with a density of 160dpi (mdpi), 160 dp will equal 1 inches. 1 pt will always equal 1/72 in, regardless of the screen density. The Android documentation for this is [here](http://developer.android.com/guide/topics/resources/more-resources.html#Dimension). **UPDATE:** I made a small application to try and verify the different sizes. It looks like what is above is correct, at least when shown on my HTC Aria. Here is a screenshot: ![HTC Aria resource type test](https://i.stack.imgur.com/5jTm3.png) It's interesting to note that these sizes did NOT match up exactly in the eclipse graphical editor. The dp and sp sizes wavered depending on the size of the screen and resolution in the editor. Here are some screenshots from the editor (left is 2.7in QVGA slider, right is 10.1in WXGA, clipped): ![enter image description here](https://i.stack.imgur.com/dRynh.png) It would be interesting to see if these editor renders match up with the actual devices. Can anyone verify these sizes? I'll attach my xml below in case anyone wants to help out. ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:padding="5sp" android:text="160dp"></TextView> <View android:id="@+id/view1" android:layout_height="20dip" android:layout_width="160dp" android:layout_marginLeft="20sp" android:background="#FF22FF22"></View> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:padding="5sp" android:text="72pt"></TextView> <View android:id="@+id/view2" android:layout_height="20dip" android:layout_width="72pt" android:layout_marginLeft="20sp" android:background="#FF22FF22"></View> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:padding="5sp" android:text="1in"></TextView> <View android:id="@+id/View01" android:layout_height="20dip" android:layout_width="1in" android:layout_marginLeft="20sp" android:background="#FF22FF22"></View> <TextView android:layout_width="wrap_content" android:textSize="22sp" android:layout_height="wrap_content" android:text="160sp" android:padding="5sp" android:id="@+id/TextView01"></TextView> <View android:layout_marginLeft="20sp" android:layout_width="160sp" android:id="@+id/View04" android:background="#FF22FF22" android:layout_height="20dip"></View> <TextView android:layout_width="wrap_content" android:textSize="22sp" android:layout_height="wrap_content" android:padding="5sp" android:id="@+id/TextView02" android:text="160px"></TextView> <View android:layout_marginLeft="20sp" android:id="@+id/View03" android:background="#FF22FF22" android:layout_height="20dip" android:layout_width="160px"></View> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:padding="5sp" android:text="25.4mm"></TextView> <View android:id="@+id/View02" android:layout_height="20dip" android:layout_marginLeft="20sp" android:background="#FF22FF22" android:layout_width="25.4mm"></View> </LinearLayout> ``` **Edit:** Added 2 more devices to John's example. On the left a Samsung Nexus S (OS 2.3.3). On the right, a Samsung Galaxy Tab 10.1 (OS 3.1). No mods. ![Samsung Nexus S](https://i.stack.imgur.com/D4Dhi.png) ![Samsung Galaxy Tab 10.1](https://i.stack.imgur.com/4wBWL.png) On the Nexus S, 160dp is slightly larger than 1 inch. All the normal physical units (in, mm, pt) are all the same size. I measured it with a ruler, and the 160 dp bar is about 1mm larger than it should. While the physical units are 1mm shorter than they should. On the Tab, all bars are exactly the same, and 1mm longer than what I measured with a ruler.
Out of curiosity, I tried the layout from John's answer on my two devices: Asus Transformer (10.1 in) and HTC Legend (3.2 in). The results were pretty interesting: Transformer (cropped): ![Transformer](https://i.stack.imgur.com/X0Eey.png) And Legend: ![Legend](https://i.stack.imgur.com/yhcSe.png)
43,020,393
[![Screen Image](https://i.stack.imgur.com/yHFD9.jpg)](https://i.stack.imgur.com/yHFD9.jpg) This method should only be accessed from tests or within private scope less... (Ctrl+F1) This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations. Examples of errors flagged by this inspection: Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen). Forgetting to invoke the overridden method (via super) in methods that require it Calling a method that requires a permission without having declared that permission in the manifest Passing a resource color reference to a method which expects an RGB integer value. <https://discussions.udacity.com/t/uri-downloadurl-tasksnapshot-getdownloadurl/232533?u=tahirs95>
2017/03/25
[ "https://Stackoverflow.com/questions/43020393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7559349/" ]
``` Uri downloadUrl = taskSnapshot.getStorage().getDownloadUrl(); ``` Change the variable name: ``` Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl(); ``` It will work.
Since you are on version 10.0.1 do this instead so it will work ``` @SuppressWarnings("VisibleForTesting") Uri downloadUrl = taskSnapshot.getDownloadUrl(); ```
45,262,038
I am using a `KSH` script to execute a binary (program) that has the following syntax to execute correctly: * `myprog [-v | --verbose (optional)] [input1] [input2]` The program prints nothing & returns exit code 0 (zero) on success. On failure it prints ERROR messages to `STDERR` & returns `exit status > 0`. If `-v` option is specified it prints verbose details to `STDOUT` both in case of success and failure. To make this usable and reduce chances of argument swapping and user controlled logging I used a ksh shell script to invoke this binary. The syntax to run the ksh shell script is as: * myshell.sh [-v (optional)] [-a input1] [-b input2] If `-v` option is specified, ksh redirects `STDOUT` to `<execution_date_time>_out.log` and `STDERR` to `<execution_date_time>_err.log`. My ksh script is as follows: myshell.sh : ``` #! /bun/ksh verbopt="" log="" arg1="" arg2="" dateTime=`date +%y-%m-%d_%H:%M:%S` while getopts "va:b:" arg do case $arg in v) # verbose output verbopt="-v" log="1>${dateTime}_out.log 2>${dateTime}_err.log" ;; a) # Input 1 arg1=$OPTARG ;; b) # Input 2 arg2=$OPTARG ;; *) # usage echo "USAGE: myshell.sh [-v] [-a input1] [-b input2]" exit 2 ;; esac done if [[ -z $arg1|| -z $arg2]] then echo "Missing arguments" exit 2 fi myprog $verbopt $arg1 $arg2 $log exit $? ``` The problem here is, all the output `STDERR` & `STDOUT` is printed on the screen (i.e, No redirection took place) as well as no `*.log` files were created after successful or unsuccessful execution (i.e, exit status: 0 or >0 respectively). Can anyone help me out on this? Thanks.
2017/07/23
[ "https://Stackoverflow.com/questions/45262038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050164/" ]
Rather than trying to monkey patch redirections into the command line, just redirect the streams when you parse the flags. That is: ``` while getopts "va:b:" arg do case $arg in v) # verbose output verbopt="-v" exec 1>${dateTime}_out.log 2>${dateTime}_err.log ;; ... ``` You need to be a little careful, since you do some error checking after this and you probably don't want your later error messages going to the \*\_err.log, but that's fairly trivial to fix. (eg, error check sooner, or do a `test -n "$verbopt" && exec > ...` after the error check, or similar)
The problem is that `>` is not expanded in the value of `$log`. I'm afraid you will need to use a conditional for this, for example: ``` cmd="myprog $verbopt $arg1 $arg2" if [ "$log" ]; then $cmd 1>${dateTime}_out.log 2>${dateTime}_err.log else $cmd fi ```
495,993
To be a 'silverlight' developer, is it basically asking for both programming and graphic skills? Or is it just a matter of implementing the graphics into the silverlight project? i.e. can you be a silverlight guru and yet not know heads from tails when it comes to graphic design?
2009/01/30
[ "https://Stackoverflow.com/questions/495993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
To be a silverlight developer, you really only need to know a .NET language, event driven programming, and how to use markup for XAML. It's pretty simple really; the XAML describes UI elements (which can all be handled by the designer) which can then be used in code as a .NET object is created for each UI element. Knowing graphic design is just a bonus.
It is not strictly necessary to be a good graphic designer, knowing how to develop .NET applications and XAML is sufficient. However, it's like drawing, all you have to do is to hold a pencil and move your hand, but if you have a good sense for art, the result will be better. Since in Silverlight your potential targets are Internet users and they're used rich user interfacese (maybe Flash based), if you know how to organize your elements, which are the best colors and things like that, your work will be easier.
67,554,315
New to react and hooks, I am trying to do a login module using hooks. However when I am not able to update the state of my Auth state. Read elsewhere that useState do not update immediately and needs to be coupled with useEffect() to have it updated. However I am using useState in a custom hook and not sure how to have updated either through useEffect or other means. Am I doing some kind of anti-pattern here? Anyone able to help? ```js const useAuth = () => { const [auth, setAuth] = useState( {} ); useEffect(()=>{ console.log(auth) },[]) return {auth, setAuth} } export const useHandleLogin = (props) => { const {auth, setAuth} = useAuth() const history = useHistory(); useEffect(()=>{ console.log(auth) },[]) const login = () => { console.log('login action called---- '); /* check if user is login */ if(localStorage.getItem('user')){ console.log('got user' ); } else { console.log('no user, calling backend to authenticate... ' ); // change to login api axios.get(`http://localhost:3001/projects`) .then(res => { console.log('call api' /* + JSON.stringify(res) */); }) localStorage.setItem('user', JSON.stringify({username:'abc',role:'123'})) console.log('login done' + JSON.stringify(auth)); console.log('login done2' + auth.authenticated); } setAuth({ authenticated: true, displayName: 'My Name', email: 'xxx@abc.com', role: 'admin' }) console.log("sending to success page" + auth + JSON.stringify(auth)) // Error is here. output is : sending to success page[object Object]{} ``` ```js import React, {useEffect} from "react"; import { useHandleLogin } from "./LoginUtil" const TestLoginPage = () => { const { auth, login } = useHandleLogin(); const Clogin = () => { console.log('auth: ' + auth) login(); }; return ( <React.Fragment> <div>login</div> <button onClick={Clogin} > Login </button> </React.Fragment> ); } export default TestLoginPage; ```
2021/05/16
[ "https://Stackoverflow.com/questions/67554315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14195732/" ]
At last i achieved this with the below solution ``` String vpnsBtn; if (check.equals("night")){ switch (status) { case "connect": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("disconnected.json"); logTv.setTextColor(getResources().getColor(R.color.font_color)); break; case "connecting": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("connectingg.json"); logTv.setTextColor(getResources().getColor(R.color.font_color)); break; case "connected": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("connected.json"); logTv.setTextColor(getResources().getColor(R.color.purple)); break; case "failed": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("disconnected.json"); break; } }else { switch (status) { case "connect": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("disconnected.json"); logTv.setTextColor(getResources().getColor(R.color.font_color)); break; case "connecting": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("connectingg.json"); logTv.setTextColor(getResources().getColor(R.color.font_color)); break; case "connected": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("connected.json"); logTv.setTextColor(getResources().getColor(R.color.purple)); break; case "failed": vpnBtn.setVisibility(View.VISIBLE); vpnsBtn = ("disconnected.json"); break; } } LottieAnimationView animationView = findViewById(R.id.vpnBtn); animationView.setImageAssetsFolder("vpnconnect"); animationView.setAnimation(vpnsBtn); animationView.loop(true); animationView.playAnimation(); ``` Hope this will help other who want to use dynamic button with Lottie on Android.
For using Lottie I did these: In `build.gradle(:app)` add this and sync: ``` implementation ‘com.airbnb.android:lottie:$lottieVersion’ ``` then, add `assets` file. Then, add the JSON files there. Then, go to `activity_main.xml` file, add: ``` <com.airbnb.lottie.LottieAnimationView android:id="@+id/lav_actionBar" android:layout_width="match_parent" android:layout_height="300dp" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:layout_marginEnd="0dp" android:scaleType="centerCrop" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:lottie_autoPlay="true" app:lottie_fileName="circle-load.json" --> add your JSON file name app:lottie_loop="true" /> ```
13,731,107
I have some simple classes that looks like this: ``` Class Favorites Guid UserId Guid ObjectId Class Objects Guid Id String Name ``` With Entity Framework I want to select all the Objects which has been marked as a favorite by a user. So I tried something like this ``` context.Objects.Where( x => x.Id == context.Favorite.Where(f => f.UserId == UserId) .Select(f => f.ObjectId).Any() ); ``` But I don't get it. I also tried with intersect, but what I understand it most be the same type. One User can have many Favorite objects
2012/12/05
[ "https://Stackoverflow.com/questions/13731107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909902/" ]
you could use join clause: ``` context.Favorite .Where(f => f.UserId == UserId) .Join(context.Objects, t => t.ObjectId, u => u.Id, (t, u) => t); ```
Use FirstOrDefault() instead of Any()
27,803,870
In Yii 1 it was possible to publish an asset with: ``` Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.MyWidget.assets')); ``` How can I publish an asset within a widget in Yii2?
2015/01/06
[ "https://Stackoverflow.com/questions/27803870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1714171/" ]
In your view of your widget: ``` app\assets\AppAsset::register($this); // $this == the View object ``` Check [the docs](http://www.yiiframework.com/doc-2.0/guide-structure-assets.html).
The problem for this case in the question. ========================================== In Yii2 AssetBandle should be unique because it avoids duplication on load same files on a web page. In Yii1 it was a problem. Almost all of the suggested answers here do not solve this problem. That why the answer should be like this: **You should create new asset bundle**(yii\web\AssetBundle) with a unique name that globally identifies it among all asset bundles used in an application. The unique name will be checked by [fully qualified class name](http://php.net/manual/en/language.namespaces.rules.php). After uses follow: ``` YourAsset::register($view); ``` or ``` $view->registerAssetBundle(InterrogateDeviceButtonAsset::class); ```
2,720,770
There is em dash and en dash. Is there an "en" equivalent to *&nbsp;* ? Is there an *en* equivalent to pure *Ascii 32*? I want a better way to write this: ``` 123<span class="spanen">&nbsp;</span>456<span class="spanen">&nbsp;</span>789 ``` or this: ``` 123<span class="spanen"> </span>456<span class="spanen"> </span>789 ```
2010/04/27
[ "https://Stackoverflow.com/questions/2720770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/89021/" ]
The Unicode character U+2002 *EN SPACE* (`&#x2002;`, `&#8194;` or as entity reference `&ensp;`) is a space with en width.
You could alter your CSS in such: ``` .spanen{word-spacing:.6em;} ```
36,203,469
I've created child themes before without issue however when I create one using Woocommerce Mystile theme it does not display properly with menu items missing and images resizing to be too large. I made the child theme by creating a new folder in the wp-content>themes folder called mystile-child and creating style.css with the contents ``` /* Theme Name: Mystile Child Description: Mystile Child Theme Template: mystile */ ``` I then created a functions.php file with the contents ``` <?php add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } ?> ``` this is what the parent theme looks like: [![Mystile Parent Theme](https://i.stack.imgur.com/rLOZc.png)](https://i.stack.imgur.com/rLOZc.png) This what the child theme looks like [![Mystile Child Theme](https://i.stack.imgur.com/IbMIf.png)](https://i.stack.imgur.com/IbMIf.png)
2016/03/24
[ "https://Stackoverflow.com/questions/36203469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026127/" ]
``` $('head').append('<link rel="stylesheet" href="style.css" type="text/css" />'); $('head').append('<script type=text/javascript" src="script.js" />'); ``` or if you want to add the code and not the file the: ``` $('body').append($("<script>alert('avascript!');<\/script>")[0]); $('body').append($("<style>.someclass{padding:10px;}<\/style>")[0]); ```
* If you only need to append different forms at a given time, you can put all the forms on the page and then hide/show them with jquery. * If the javascript is for validations purposes, you can write different functions that will be called depending on the form you are submitting. * Finally the css can be applied to each element by using css classes. So it is not necessary to append everything as it could be written in the page from the first time. This approach is a standard for ajax applications today. It's called [single page application](https://en.wikipedia.org/wiki/Single-page_application).
25,325,413
Suppose, we have the following HTML file: ### test.htm ``` <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <b>weight:</b> 120kg<br> <b>length:</b> 10cm<br> </body> </html> ``` How can I get the following data from it? ``` { 'weight' => '120kg', 'length' => '10cm', } ``` ### parser.pl ``` #!/usr/bin/perl use strict; use warnings; use utf8; use HTML::TreeBuilder; my $root = HTML::TreeBuilder->new; $root->parse_file('test.htm'); #what to do here? $root->delete( ); ```
2014/08/15
[ "https://Stackoverflow.com/questions/25325413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/789186/" ]
This gets you very close to what you want (you'll need to tweak the text strings you're getting for the keys and values slightly). But I think you'll find it far simpler using a tool like [Web:Scraper](https://metacpan.org/pod/Web::Scraper). ``` #!/usr/bin/env perl use strict; use warnings; use 5.010; use Data::Dumper; use HTML::TreeBuilder; my $root = HTML::TreeBuilder->new; $root->parse_file(\*DATA); my $data; foreach my $elem ($root->find('b')) { $data->{($elem->content_list)[0]} = $elem->right; } say Dumper $data; __END__ <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <b>weight:</b> 120kg<br> <b>length:</b> 10cm<br> </body> </html> ``` Output: ``` $VAR1 = { 'length:' => ' 10cm', 'weight:' => ' 120kg' }; ```
Two solutions using [`Mojo::DOM`](https://metacpan.org/pod/Mojo::DOM): ``` use strict; use warnings; use Mojo::DOM; use Data::Dump; my $dom = Mojo::DOM->new(do {local $/; <DATA>}); my %hash = do { my $text = $dom->find('body')->all_text(); split ' ', $text; }; dd \%hash; my %hash2 = map { $_->all_text() => $_->next_sibling() =~ s{^\s+|\s+$}{}gr } $dom->find('b')->each; dd \%hash2; __DATA__ <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <b>weight:</b> 120kg<br> <b>length:</b> 10cm<br> </body> </html> ``` Outputs: ``` { "length:" => "10cm", "weight:" => "120kg" } { "length:" => "10cm", "weight:" => "120kg" } ```
310,589
In our MOSS '07 site we have a page that contains just a Page Viewer web part in it that points to a site on another server. However, I've noticed that on that page (and any others that have a Page Viewer web part on it) our drop down menus and hover effects are **super slow** and completely max out the CPU on the visitor's computer (process is **IExplorer**.) Through testing, I was able to determine that it doesn't matter what URL the web part is pointed to...just having the Iframe on the page seems to cause it (just setting the viewer to load Google's homepage--which is probably the simplest site I know--still causes the problem). If I go and remove the web part, the menus start functioning just fine again. I attached a debugger to the process and stepped through the `Menu_HoverStatic` and called functions and it seems to have a hard time when assigning `panel.scrollTop` to zero in the `PopOut_Show` function. Has anyone else noticed this? ...perhaps found a solution to it? I can't find where to edit `PopOut_Show` function on our server (I think it's a resource in one of the .NET DLLs) or else I'd just comment out that line as I don't think it's really important anyway...at least on our site. I really like the ability to have web pages from another server hosted in our SharePoint site, but the performance on the hovers is agonizing... and, honestly, unacceptable. Depending on the resources of the user's computer, the hover effects can take 15 seconds to complete at times!!!! Any suggestions would be really appreciated!
2008/11/22
[ "https://Stackoverflow.com/questions/310589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30866/" ]
``` function loadJSInclude(scriptPath, callback) { var scriptNode = document.createElement('SCRIPT'); scriptNode.type = 'text/javascript'; scriptNode.src = scriptPath; var headNode = document.getElementsByTagName('HEAD'); if (headNode[0] != null) headNode[0].appendChild(scriptNode); if (callback != null) { scriptNode.onreadystagechange = callback; scriptNode.onload = callback; } } ``` And to use (I used swfObject as an example): ``` var callbackMethod = function () { // Code to do after loading swfObject } // Include SWFObject if its needed if (typeof(SWFObject) == 'undefined') loadJSInclude('/js/swfObject.js', callbackMethod); else callbackMethod(); ```
You might want to take a look at a real [DEMO](http://bachhoa24.com/ban-nha-di-an-bd-dt11x20m-gia-1-ty-200-cl-1002687.html#show_map) on real estate site. On the demo page, just click on the link [Xem bản đồ] to see the map loaded on demand. The map loaded only when the link be clicked not at the time of page load, so it can reduce page download time.
267,609
Outlook 2010. Want to create a rule that moves all mail from my inbox to another folder: * Has been read * Is older than X days I was looking at Auto-archiving, but it does not seem to let me be this specific with my criteria.
2011/04/07
[ "https://superuser.com/questions/267609", "https://superuser.com", "https://superuser.com/users/49303/" ]
The search folders are the answer, however the OP asked about mail *older than* a particular date. If you use "modified last week" then it shows everything within the last week and filters out things older than 1 week. For the inverse that, use language like: * 8 days ago * 1 week ago * etc... ![enter image description here](https://i.stack.imgur.com/kVvwn.png)
For the upcoming researchers, i have done the following using Developer tools ``` Public WithEvents olItems As Outlook.Items Sub Application_Startup() Set olItems = Session.GetDefaultFolder(olFolderInbox).Items End Sub Private Sub olItems_ItemChange(ByVal Item As Object) Dim deFolder As Folder 'Ensure the email marked as read If TypeOf Item Is MailItem And Item.UnRead = False Then 'Check the email subject and then move to specific folder 'You can change these conditions and folders as per your needs If InStr(LCase(Item.Subject), "test") > 0 Then Set deFolder = Session.GetDefaultFolder(olFolderInbox).Parent.Folders("Test") Item.Move deFolder End If If InStr(LCase(Item.Subject), "worklog") > 0 Then Set deFolder = Session.GetDefaultFolder(olFolderInbox).Parent.Folders("WorkLog") Item.Move deFolder End If If InStr(LCase(Item.Subject), "report") > 0 Then Set deFolder = Session.GetDefaultFolder(olFolderInbox).Parent.Folders("Report") Item.Move deFolder End If End Sub ``` After that, you should digitally sign this code. Use the built-in “Digital Certificates for VBA Projects” tool to create a new certificate.
40,684,698
Since November 8, 2016, we've seen a sudden increase in crashes from WebThread. We don't know what is causing the crash. We do have web articles and ads in the app. We did not have any App Release. There were no significant changes on the web or ads. Since crashes are happening on screens without articles, we are thinking it is happening on ads. Is anyone else seeing this? Any thoughts, ideas, anything? Stack trace: ``` Crashed: WebThread 0 WebCore 0x184b7e47c WTF::HashMap<WTF::String, WebCore::ApplicationCacheGroup*, WTF::StringHash, WTF::HashTraits<WTF::String>, WTF::HashTraits<WebCore::ApplicationCacheGroup*> >::remove(WTF::String const&) + 48 1 WebCore 0x184b7abbc WebCore::ApplicationCacheStorage::cacheGroupDestroyed(WebCore::ApplicationCacheGroup*) + 52 2 WebCore 0x184b7abbc WebCore::ApplicationCacheStorage::cacheGroupDestroyed(WebCore::ApplicationCacheGroup*) + 52 3 WebCore 0x184b70628 WebCore::ApplicationCacheGroup::~ApplicationCacheGroup() + 56 4 WebCore 0x184b70b10 WebCore::ApplicationCacheGroup::~ApplicationCacheGroup() + 12 5 WebCore 0x184b72334 WebCore::ApplicationCacheGroup::disassociateDocumentLoader(WebCore::DocumentLoader*) + 184 6 WebCore 0x184a024a0 WebCore::ApplicationCacheHost::~ApplicationCacheHost() + 48 7 WebCore 0x184a01ad0 WebCore::DocumentLoader::~DocumentLoader() + 168 8 WebKitLegacy 0x185976ba8 WebDocumentLoaderMac::~WebDocumentLoaderMac() + 84 9 WebCore 0x184e30a78 WebCore::FrameLoader::detachFromParent() + 324 10 WebKitLegacy 0x1859e0b08 __29-[WebView(WebPrivate) _close]_block_invoke + 348 11 WebCore 0x1857842c4 HandleRunSource(void*) + 368 12 CoreFoundation 0x180ab509c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 13 CoreFoundation 0x180ab4ab0 __CFRunLoopDoSources0 + 412 14 CoreFoundation 0x180ab2830 __CFRunLoopRun + 724 15 CoreFoundation 0x1809dcc50 CFRunLoopRunSpecific + 384 16 WebCore 0x1849ce108 RunWebThread(void*) + 456 17 libsystem_pthread.dylib 0x180763b28 _pthread_body + 156 18 libsystem_pthread.dylib 0x180763a8c _pthread_body + 154 19 libsystem_pthread.dylib 0x180761028 thread_start + 4 ```
2016/11/18
[ "https://Stackoverflow.com/questions/40684698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413594/" ]
**Answering my own question to add more details than comment area. Not marking as answered as I don't have solution.** Unfortunately, we were not able to solve issue. Fortunately, crash rate came down after 2-3 days. After spending 3 days, we were certain it was related to Google Ads. However, Why crash rate went up and down is still a mystery for us. Some notes/conclusion: * Are we doing something stupid when requesting/handling ads? + Possible, but chances are very thin as it was happening to existing stable release. * Is this happening to specific ad(s)? + crash rate went down because we are not serving that ad(s) anymore? * GoogleAds team came to rescue and acted like nothing happen? because... :) * Not a new issue - Crashlytics was showing first occurrence of this type of crash was months before.
Simply put, the crash you are experiencing is because of a memory leak. A variable or object is trying to access restricted memory, which will result in this crash. **My guess is that one of the advertising frameworks/APIs you are using did not handle the iOS 10.1.1 (Build 14B100) update which came out October 31st, 2016.** This could be the cuase of your crash. It also occurred to me that this seems to be happening during some sort of a call to a close/exit function. If so, **MAKE SURE** you are releasing objects, variables, and anything else that has been assigned memory, properly. If your code or program is releasing everything the correct way, then it is the advertisement framework/API causing your issues. Cheers!
8,224,422
I currently have a JFrame where on it's content pane I draw images on from a game loop at 60 frames per second. This works fine, but at the right side, I now have more Swing elements on which I want to display some info on when selecting certain parts of the content pane. That part is a static GUI and does not make use of a game loop. I'm updating it this way: ``` public class InfoPanel extends JPanel implements Runnable { private String titelType = "type: "; private String type; private JLabel typeLabel; private ImageIcon icon; public void update() { if (this.icon != null) this.typeLabel.setIcon(this.icon); if(this.type != null || this.type != "") this.typeLabel.setText(this.titelType + this.type); else this.typeLabel.setText(""); } public void run() { try { Thread.sleep(150); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.update(); } ``` (this method is only called when the player has actually moved, so it's just called once - not 60 times per second) I noticed that, when calling this update()-method from the game loop, I get flickering effects. I assume this is because updating the UI takes some time, so I decided to put it in a new thread. This reduced the flickering, but didn't solve it. Next, I decided to give the new thread low priority as the part of the screen which is redrawed 60 times a second is far more important. This reduced the flickering again, but it still happened. Then, I decided to use `Thread.sleep(150);` in the new thread before calling the update()-method, which solved the flickering effect on my system completely. However, when running it on other systems, it still happens. Not as often as before (maybe one time per 20 seconds), but it's still pretty annoying. Apparantly, just updating the UI in another thread doesn't solve the problem. Any ideas how to completely eleminate the flickering?
2011/11/22
[ "https://Stackoverflow.com/questions/8224422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618622/" ]
Call the `update()` in `SwingUtilities.invokeAndWait()` which stops the thread and updates UI in EDT.
Problem is that you are use `Thread.sleep(int)`, that stop and freeze GUI during `EventDispatchTread` more in the [Concurency in Swing](http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html), [example](https://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java) demonstrating freeze GUI by using `Thread.sleep(int)`, [example](https://stackoverflow.com/q/8084657/714968) for Runnable#Thread If you want to delay whatever in Swing then the best way is implements [javax.swing.Timer](http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html)
22,080,382
I was doing some MySQL test queries, and realized that comparing a string column with `0` (as a number) gives `TRUE`! ``` select 'string' = 0 as res; -- res = 1 (true), UNexpected! why!??!?! ``` however, comparing it to any other number, positive or negative, integer or decimal, gives `false` as expected (of course unless the string is the representation of the number as string) ``` select 'string' = -12 as res; -- res = 0 (false), expected select 'string' = 3131.7 as res; -- res = 0 (false), expected select '-12' = -12 as res; -- res = 1 (true), expected ``` Of course comparing the string with `'0'` as string, gives false, as expected. ``` select 'string' = '0' as res; -- res = 0 (false), expected ``` but why does it give true for `'string' = 0` ? why is that?
2014/02/27
[ "https://Stackoverflow.com/questions/22080382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385198/" ]
["Strings are automatically converted to numbers and numbers to strings as necessary."](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal) This means that in order to compare a string to a number, it tries to parse a number from the start of the string. In this case there is no number there, so it converts to 0, and 0 = 0 is true.
if you want to fix it you can compare two strings: ``` select 'string' = convert(0,char) as res --- res = 0 ```
25,797,320
I wanted to get every thing between first occurence of (\*) and (\n) **Here is the string:** **\*Set of classes with distinct scalable between plugs, cores, and logs and are with and test data.\*Maps of class distributions across the basin.\*Description of the origin of the various classes and their link to types.**\nTesting Start **\*Test New\*Test New**\nOneMore list **\*Set of classes with distinct scalable between plugs, cores, and logs and are with and test data.\*Maps of class distributions across the basin.\*Description of the origin of the various classes and their link to types.types.**\nend Text in bold is what I need to get.
2014/09/11
[ "https://Stackoverflow.com/questions/25797320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389485/" ]
The following should work: ``` result = subject.match(/\*[\s\S]*?\n(?!\*)/g); ``` Test it [live on regex101.com](http://regex101.com/r/tW3tW1/1).
Alternate, possibly quicker regex. ``` /\*[^\r\n]*\r?\n(?!\*)/g ```
22,203,661
So I have the following html: ``` <div class="btn-group pull-right"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">Export Features <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="#" data-toggle="modal" data-target="#myModal">CSV</a> </li> <li><a href="#">Excel</a> </li> </ul> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> <h3>Currently downloading: <small>feature-set-II.csv</small></h3> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%;"> 60% </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary" disbaled>Begin Download</button> </div> </div> </div> </div> ``` And when ever I click on CSV in the button drop down - what happens is it refreshes the page and the modal never opens, I believe its because of the `href="#"` part, but I am not sure, This shouldn't require any JS at all...
2014/03/05
[ "https://Stackoverflow.com/questions/22203661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3379926/" ]
Your code should works fine: **[Bootply Demo](http://www.bootply.com/119106)** Some things to note: * You need to include `jQuery` since Bootstrap js require `jQuery` to works. * You need to include Bootstrap CSS and JS files. * Include Bootstrap JS after you've included `jQuery` properly.
Your call to the modal should match IDs. Use something like this: ``` <a data-toggle="modal" href="#myModal">CSV</a> ``` Your first div for you modal should be something like this ``` <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> ``` That should fix it
146,695
I'm embarrassed how many times I've used ordinary BJT transistors in circuits that clearly would have been better suited to a FET, and even better a MOSFET. This is because as a lifelong hobbyist, I have a huge stash of common BJTs, and sadly the days of well stocked "neighborhood" electronic store are long gone. Experimenting always requires ordering parts first. Now I understand MOSFETS well enough to pour over specs and parameters and make choices, but maybe someone with more experience could point me to a short list of "general use" enhancement mode P and N channel mosfets that are both inexpensive and readily available as both SMT and through hole parts, that I basically couldn't go wrong ordering a supply of. I realize there are thousands of good choices, but if you consider that the old familiar (and cheap!) 2N2222 (NPN) and 2N2909 (PNP) BJTs have satisfied the bulk of my needs for simple switching or basic amplification apps for as long as I can remember, perhaps some parts will come to mind. I very seldom need to handle more that 500mA, and usually have low voltage and power requirements (15VDC, seldom more than 1W). Honestly most of my needs are for switching and about the only 'specialty" wishlist item I have is that the lowest "on resistance" would certainly be worth a few cents more. Suggestions welcome.
2015/01/05
[ "https://electronics.stackexchange.com/questions/146695", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/54964/" ]
First, you have to get over looking for parts that have thru hole variants. Hardly anything does anymore, and there's no point to them anyway. Soldering a SMD part is actually *easier* than soldering a thru hole part. My common N channel FET goto part for low voltages is the IRFML8244. This is a great little part. It's cheap, and better in just about all respects than its predecessor, the IRLML2502, which was my preferred jellybean part for such things before. The IRFML8244 can handle up to 25 V, 41 mΩ Rdson at 4.5 V gate drive, can pass a few amps, has relatively low gate charge, and comes in the common SOT-23 package. You can drive this FET directly from a processor pin without any additional parts in many cases. It's great for switching solenoids, motors, and the like. For high side switching, you have to look around. Do a search on Mouser for your requirements. You will find less parts that cover a variety of applications without more compromises or higher price.
MOSFETs are a little unlike BJTs in that while just about any BJT can be substituted for any other device (so long as the parameters are in the ballpark), MOSFET circuits typically depend on a particular Vt. This is because for the most part BJTs are characterized by the beta parameter, but it is considered poor design to assume a particular beta for a circuit, as significant variations can occur even given the same part number. This is different than MOSFET devices, where Vt can be (relatively) more precisely controlled. With that said however, the [2N7000](http://en.wikipedia.org/wiki/2N7000) is apparently notable enough to warrant its own Wikipedia page, so it must be pretty common.
18,350,662
I notice python won't let you add an instance of a class to itself as a static member at class definition. ``` >>> class Foo: ... A = Foo() ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in Foo NameError: name 'Foo' is not defined ``` However either of the following work: ``` >>> class Foo: ... pass ... >>> class Foo: ... A = Foo() ... >>> Foo.A <__main__.Foo instance at 0x100854440> ``` or ``` >>> class Foo: ... pass ... >>> Foo.A = Foo() >>> >>> Foo.A <__main__.Foo instance at 0x105843440> ``` I can't find any enlightening code examples or explanations. Why does python treat the first case differently? Where is A going in each of the two subsequent cases?
2013/08/21
[ "https://Stackoverflow.com/questions/18350662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1704140/" ]
Your first example doesn't work because you haven't created the class `Foo` yet. You're in the process of doing so (hence the `NameError`) Your second example works because you have a class called `Foo()`. You override it, but you still keep a copy of it. Take a look at this: ``` >>> class Foo: ... def __init__(self): ... print 'hi' ... >>> class Foo: ... A = Foo() ... hi >>> Foo.A <__main__.Foo instance at 0x101019950> >>> Foo.A.__init__ <bound method Foo.__init__ of <__main__.Foo instance at 0x101019950>> ``` `A` is an attribute that has the value of a class you overrode. As for your third example, you're simply making an attribute of a class that is an instance of the class.
At class definition time, the class itself doesn't exist yet, the contents of the indented block are executed and any names are resolved and functions are called. At that point, the name of the class, the base classes and a dictionary containing the names and values to store in the class are passed off to the metaclass which creates the actual class and binds it to the name specified. You can create a 'static' instance of a class at class initialization time via the use of a `metaclass`. This executes the code inside the class definition, passes the name, bases and dict to a metaclass function, which creates the class and creates an instance of the class inside it then binds it to the name. Consider: ``` def staticInstanceMetaclass(name, bases, dict_): ret=type(name, bases, dict_) for i in dict_: if dict_[i]=='STATICINSTANCE': setattr(ret,i,ret()) return ret class ClassWithStaticInstance(object): __metaclass__=staticInstanceMetaclass myStaticInstance='STATICINSTANCE' myFirstVar=5 print ClassWithStaticInstance.myStaticInstance ``` Note that in the above example, `dict_` contains ``` {'myStaticInstance': 'STATICINSTANCE', '__module__': '__main__', '__metaclass__': <function staticInstanceMetaclass at 0x1213668>, 'myFirstVar': 5} ``` That's about as close as you get to pre-creating static instances in python. For more info on metaclasses, and how the affect class creation, see [this](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) question.
37,576,078
I'm developing a C++ static library with Visual Studio 2015. I have the following struct: ``` struct ConstellationArea { // Constellation's abbrevation. std::string abbrevation; // Area's vertices. std::vector<std::string> coordinate; ConstellationArea(std::string cons) : abbrevation(cons) {} }; ``` I use it in a while (note that the method is not ended): ``` vector<ConstellationArea>ConstellationsArea::LoadFile(string filePath) { ifstream constellationsFile; vector<ConstellationArea> areas; string line; ConstellationArea area(""); string currentConstellation; // Check if path is null or empty. if (!IsNullOrWhiteSpace(filePath)) { constellationsFile.open(filePath.c_str(), fstream::in); // Check if I can open it... if (constellationsFile.good()) { // Read file line by line. while (getline(constellationsFile, line)) { vector<string> tokens = split(line, '|'); if ((currentConstellation.empty()) || (currentConstellation != tokens[0])) { currentConstellation = tokens[0]; areas.push_back(area); area(tokens[0]); } } } } return areas; } ``` I want to create a new `area` object when `tokens[0]` changes but I don't know how to do it. This statement `area(tokens[0]);` throws the following error: > > call an object of a class type without any conversion function or > operator () suitable for the type of function pointer > > > How can I create a new struct when I need it? I'm a C# developer and I can't figure out how to do it in C++.
2016/06/01
[ "https://Stackoverflow.com/questions/37576078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68571/" ]
`ConstellationArea(std::string cons)` is a constructor and must be called during initialization of an object. So it's legal to have `ConstellationArea area("foo")` because you are initializing the object. But `area("foo")` is not an [initialization](http://en.cppreference.com/w/cpp/language/initialization), actually it's an invocation of `operator()` on the object. In that situation the compiler is looking for `ConstellationArea::operator()(std::string str)` which is not defined. You must initialize another object and assign it to the variable, eg ``` area = ConstellationArea(tokens[0]) ``` This will create another object and then assign the value to it through `ConstellationArea& ConstellationArea::operator=(const ConstellationArea& other)` which is the [copy assignment operator](http://en.cppreference.com/w/cpp/language/copy_assignment) and it is provided by default.
Reassign the value? ``` area = ConstellationArea(tokens[0]); ```
17,862,804
If i have a SQL statement like below ``` SELECT * FROM myTable WHERE CID = :vCID AND DataType = :vDataType ``` And usually i use TQuery to get some data like below ``` aQuery.ParamByName('vCID').Value := '0025'; aQuery.ParamByName('vDataType').AsInteger := 1; ``` But how can i ignore the "CID" key to get a SQL like ``` SELECT * FROM myTable WHERE DataType = :vDataType ``` I've try the below synctax, but failed ``` aQuery.ParamByName('vCID').Value := '%'; aQuery.ParamByName('vDataType').AsInteger := 1; ``` Please help me out, thank you.
2013/07/25
[ "https://Stackoverflow.com/questions/17862804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/617179/" ]
The best option is to simply use separate queries: ``` aQueryBoth.SQL.Text := 'SELECT * FROM myTable WHERE CID = :vCID AND DataType = :vDataType'; ... aQueryBoth.ParamByName('vCID').Value := '0025'; aQueryBoth.ParamByName('vDataType').AsInteger := 1; ``` ``` aQueryDataType.SQL.Text := 'SELECT * FROM myTable WHERE DataType = :vDataType'; ... aQueryDataType.ParamByName('vDataType').AsInteger := 1; ```
Change your Query to ``` SELECT * FROM myTable WHERE CID = ISNULL(:vCID,CID) AND DataType = ISNULL(:vDataType,DataType) ``` or ``` SELECT * FROM myTable WHERE COALESCE(CID,'') = COALESCE(:vCID,CID,'') AND COALESCE(DataType,0) = COALESCE(:vDataType,DataType,0) ``` The second one would handle the case of NULL values in the table too. The Parameter you don't want to use can be set to `Unassigned` ``` aQuery.ParamByName('vCID').Value := Unassigned; // << aQuery.ParamByName('vDataType').AsInteger := 1; ``` Since :vCid is NULL it will be evaluated as `CID = CID`
19,375,748
"I have 3 buttons on click of the button using java script the div will appear each div have different button to save some data in asp.net page but it refresh whole page i would like to refresh particular div only and save data to my db" Button Code ``` <asp:Button ID="btnConse" runat="server" CssClass="Button" AlternateText="1" Text="Consequence" OnClientClick="ToggleDiv('Consequence');return false;" /> <asp:Button ID="btnTask" runat="server" CssClass="Button" AlternateText="1" Text="Task" OnClientClick="ToggleDiv('Task');return false;" /> <asp:Button ID="Button4" runat="server" CssClass="Button" AlternateText="1" Text="Incident" OnClientClick="ToggleDiv('Incident');return false;" /> ``` Java script ``` <script type="text/javascript"> function ToggleDiv(Flag) { if (Flag == "Consequence") { document.getElementById('divConsequence').style.display = 'block'; document.getElementById('divTask').style.display = 'none'; document.getElementById('divIncident').style.display = 'none'; } else { if (Flag == "Task") { document.getElementById('divConsequence').style.display = 'none'; document.getElementById('divTask').style.display = 'block'; document.getElementById('divIncident').style.display = 'none'; } else { if (Flag == "Incident") { document.getElementById('divConsequence').style.display = 'none'; document.getElementById('divTask').style.display = 'none'; document.getElementById('divIncident').style.display = 'block'; } } } } </script> ``` Div ``` <div id="divConsequence" style="display: none;"> <div class="TabTextHoriCenter"> <asp:Label ID="Label28" runat="server" Text="div Consequence"></asp:Label> <asp:Button ID="btnSaveCon" runat="server" CssClass="Button" AlternateText="1" Text="Consequence" OnClick="btnSaveCon_Click" /> </div> </div> <div id="divTask" style="display: none;"> <div class="TabTextHoriCenter"> <asp:Label ID="Label33" runat="server" Text="div Task"></asp:Label> <asp:Button ID="btnSaveTask" runat="server" CssClass="Button" AlternateText="1" Text="Task" OnClick="btnSaveTask_Click" /> </div> </div> <div id="divIncident" style="display: none;"> <div class="TabTextHoriCenter"> <asp:Label ID="Label34" runat="server" Text="div incident"></asp:Label> <asp:Button ID="btnSaveInc" runat="server" CssClass="Button" AlternateText="1" Text="Incident" OnClick="btnSaveInc_Click" /> </div> </div> ``` in this div there are button which performs server operation How can I refresh only this div not the whole page? .cs code ``` protected void btnAddFiles_Click(object sender, EventArgs e) { if (fuFile.HasFile) { FileUpload Custom = new FileUpload(); Custom = fuFile; if (Session["FileUpload"] != null) { FileUpload[] fuu = (FileUpload[])Session["FileUpload"]; int cnt = 0; for (int k = 0; k < fuu.Length; k++) { if (fuu[k] != null) { cnt++; } else { break; } } fuu[cnt] = Custom; Session["FileUpload"] = fuu; } else { FileUpload[] fuu = new FileUpload[100]; fuu[0] = Custom; Session["FileUpload"] = fuu; } if (flag == 1) { FilesAttached.Value = ""; flag = 0; } FileInfo Finfo = new FileInfo(fuFile.PostedFile.FileName); string Ext = Finfo.Extension.ToLower(); string f = fuFile.FileName.ToLower(); string fname = Session["CompanyID"].ToString() + Session["MyRiskArea"].ToString(); Session["time"] = String.Format(Global.yyyy_mmm_ddhh_mm_ss_tt.ToString(), DateTime.Now); int i = Convert.ToInt32(Ext.Length); String NewString = f.Remove(f.Length - i, i) + Session["time"].ToString(); string str = NewString + Ext; fuFile.SaveAs(Server.MapPath(Global.AttachedFiles + "/" + str)); ht.Add(Session["time"].ToString(), f); ht1.Add(Session["time"].ToString(), System.IO.Path.GetFullPath(fuFile.FileContent.ToString())); dlIncidents.DataSource = ht; dlIncidents.DataBind(); fuFile.Focus(); dlIncidents.Visible = true; //BindGrid(); } } ```
2013/10/15
[ "https://Stackoverflow.com/questions/19375748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881511/" ]
You aren't allocating memory for `global_variable`, so `fgets` tries to write at a random position in memory, leading to the OS detect memory violation and stopping the process by sending SIGSEGV that causes segmentation fault. Change the your main to something like this: ``` int main () { pthread_t t_m, t1, t2, t3; global_variable = malloc(sizeof(char)*999); //const char *m1 = "Thread 1", *m2 = "Thread 1", *m3 = "Thread 3"; ...more code... printf("Global Variable: %s", global_variable); free(global_variable); ``` Read [`malloc()`](http://linux.die.net/man/3/malloc) and [`free()`](http://linux.die.net/man/3/malloc)
Note declaration: ``` char* global_variable; ``` is not an array but a pointer, and you are trying to read as: ``` fgets(global_variable, 999, stdin); ``` without allocating memory ==> Undefined behaviour, causes of segmentation fault at runtime. To rectify it, either allocate memory for it as @dutt suggesting in his [answer](https://stackoverflow.com/a/19375940/1673391), or `global_variable` should be an array as `char global_variable[1000];`
64,726,380
I am trying to figure out what is wrong with my nested loop without receiving the answer to the exercise I'm working on. The initial error is that there is a comparison of signedness. Prompt: Given a vector of integers named vec, find the sum of the product of all pairs of vector elements. Ex: {1,2,3}: (1x2)+(1x3)+(2x3) = 11. This needs to be stored in a variable called result. The function is already set up and I am simply just writing the body. My idea was that I was trying to grab the first element in the vector with the first for loop, and then used the second for loop to multiply the first element with the rest of the elements in the vector. I thought that the j = i+1 would allow me to avoid the value used in the first for loop and access the rest of the elements. ``` int result = 0; int pair = 0; for(int i = 0; i<=vec.size(); ++i){ int num1 = vec.at(i); for(int j = i+1; j <= vec.size(); ++j){ int num2 = vec.at(j); pair = num1 * num2; result = result + pair; } } ```
2020/11/07
[ "https://Stackoverflow.com/questions/64726380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14594819/" ]
Need to bind it on constructor, when ever function binding is passed as props a new function will be created by which the props will signify a change triggering the render again ``` import TimeGrid from './TimeGrid'; class ScheduleView extends Component { constructor(props) { super(props); this.state = { schedule: [], // initially empty }; this.handleGridChange = this.handleGridChange.bind(this); ) handleGridChange(newSchedule) { this.setState({ schedule: newSchedule, }); } render() { return ( <TimeGrid schedule={this.state.schedule} handleGridChange={this.handleGridChange} /> ); } } ```
Use this instead of your *`handleGridChange`* function ``` <TimeGrid schedule={this.state.schedule} handleGridChange={(newSchedule) => this.setState({schedule: newSchedule})} /> ``` it'll work for sure.
4,475,704
I am wondering if the following code can be written in a somewhat nicer way. Basically, I want to calculate `z = f(x, y)` for a `(x, y)` meshgrid. ``` a = linspace(0, xr, 100) b = linspace(0, yr, 100) for i in xrange(100): for j in xrange(100): z[i][j] = f(a[i],b[j]) ```
2010/12/17
[ "https://Stackoverflow.com/questions/4475704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534298/" ]
you could do something like ``` z = [[f(item_a, item_b) for item_b in b] for item_a in a] ```
If you set it all at once, you can use a list comprehension; ``` [[f(a[i], b[j]) for j in range(100)] for i in range(100)] ``` If you need to use a `z` that's already there, however, you can't do that and your code is about the neatest you'll get. *Addition:* I don't know with what this `lingrid` does, but if it produces a 100-element list, use aaronasterling's list comprehension; no point in creating an extra iterator if you don't need to.
22,613,293
The ANTLR4 book references a multi-mode example <https://github.com/stfairy/learn-antlr4/blob/master/tpantlr2-code/lexmagic/ModeTagsLexer.g4> ``` lexer grammar ModeTagsLexer; // Default mode rules (the SEA) OPEN : '<' -> mode(ISLAND) ; // switch to ISLAND mode TEXT : ~'<'+ ; // clump all text together mode ISLAND; CLOSE : '>' -> mode(DEFAULT_MODE) ; // back to SEA mode SLASH : '/' ; ID : [a-zA-Z]+ ; // match/send ID in tag to parser ``` <https://github.com/stfairy/learn-antlr4/blob/master/tpantlr2-code/lexmagic/ModeTagsParser.g4> ``` parser grammar ModeTagsParser; options { tokenVocab=ModeTagsLexer; } // use tokens from ModeTagsLexer.g4 file: (tag | TEXT)* ; tag : '<' ID '>' | '<' '/' ID '>' ; ``` I'm trying to build on this example, but using the `«` and `»` characters for delimiters. If I simply substitute I'm getting error 126 `cannot create implicit token for string literal in non-combined grammar: '«'` In fact, this seems to occur as soon as I have the `«` character in the parser `tag` rule. ``` tag : '«' ID '>'; ``` with ``` OPEN : '«' -> pushMode(ISLAND); TEXT : ~'«'+; ``` Is there some antlr foo I'm missing? This is using `antlr4-maven-plugin` `4.2`. The wiki mentions something along these lines, but the way I read it that's contradicting the example on github and anecdotal experience when using `<`. See "Redundant String Literals" at <https://theantlrguy.atlassian.net/wiki/display/ANTLR4/Lexer+Rules>
2014/03/24
[ "https://Stackoverflow.com/questions/22613293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134894/" ]
One of the following is happening: 1. You forgot to update the `OPEN` rule in **ModeTagsLexer.g4** to use the following form: ``` OPEN : '«' -> mode(ISLAND) ; ``` 2. You found a bug in ANTLR 4, which should be reported to the [issue tracker](https://github.com/antlr/antlr4/issues).
Have you specified the file encoding that ANTLR should use when reading the grammar? It should be okay with European characters less than 255 but...
23
When I am grating a block of parmesan cheese and the block becomes particularly small, I often fear that I will slip/the item will be completely grated and I will cut/grate my fingers. I've used rubber gloves as well but I'm concerned they are not thick enough. What is the best way to protect against this? Are there graters with built-in functions to prevent this? Or would a particular kind of gloves help?
2014/12/09
[ "https://lifehacks.stackexchange.com/questions/23", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/23/" ]
There are a variety of devices to solve this problem, my first thought would be thimbles if you don't want to buy one, but I would encourage just getting such a device, there's both rotary and flat-board ones I've seen. The rotary ones are thus: ![enter image description here](https://i.stack.imgur.com/a5kud.jpg)
How about using bottle caps to cover the ends of the fingers? Or reverse the cap so it sinks into the potato (in my case) and use the protruding part as a handle?
51,768,027
Given an input array of `1`s and `0`s of arbitrary length, such as: ``` [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0] ``` How can I (most efficiently) calculate a new array detailing if chunks of size `n` `0`s which can fit into the input? Examples -------- Where output now means * 1 == 'Yes a zero chunk that size could go here' * 0 == 'Couldn't fit a chunk that size there' --- * Chunk size = 1 (`[0]`): `[1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1]` * Chunk size = 2 (`[0,0]`): `[0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1]` * Chunk size = 3 (`[0,0,0]`): `[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0]` * Chunk size = 4 (`[0,0,0,0]`): `[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]` I'm using ES6, so any language features are fine. EDIT: The output shouldn't just be a 'yes'/'no' a chunk of size 'n' can fit in this array. More specifically, it needs to be an array of the same length, where a '1' / 'true' array value represents either: * Yes, a chunk of size 'n' could start and fit here, ***or*** * Yes, this slot could contain a chunk of size 'n' that started before it On that second point, this would mean for chunk size 3: `input = [1, 0, 0, 0, 0, 1];` `output = [0, 1, 1, 1, 1, 0];` Edit 2: This is the function I came up with but it seems very inefficient: ``` const calculateOutput = (input, chunkSize) => { const output = input.map((value, index) => { let chunkFitsHere = false; const start = (index - (chunkSize) >= 0) ? index - (chunkSize) : 0; const possibleValues = input.slice(start, index + chunkSize); possibleValues.forEach((pValue, pIndex) => { let consecutives = 0; for (let i = 0; i < possibleValues.length - 1; i += 1) { if (consecutives === chunkSize) { break; } if (possibleValues[i+1] === 0) { consecutives += 1; } else { consecutives = 0; } } if (consecutives === chunkSize) { chunkFitsHere = true; } }); return chunkFitsHere ? 1 : 0; }); return output; }; ```
2018/08/09
[ "https://Stackoverflow.com/questions/51768027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180964/" ]
You could count the connected free places by reversing the array and take an flag for the last return value for mapping. > > Array before final mapping and after, depending on `n` > > > > ``` > 1 0 4 3 2 1 0 0 2 1 0 0 0 3 2 1 0 2 1 array with counter > 1 0 4 4 4 4 0 0 2 2 0 0 0 3 3 3 0 2 2 array same counter > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ------------------ > 1 0 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 n = 1 > 0 0 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 n = 2 > 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 n = 3 > 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 n = 4 > > ``` > > ```js function chunk(array, n) { return array .slice() .reverse() .map((c => v => v ? c = 0 : ++c)(0)) .reverse() .map((l => v => l = v && (l || v))(0)) .map(v => +(v >= n)); } var array = [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0]; console.log(chunk(array, 1).join(' ')); console.log(chunk(array, 2).join(' ')); console.log(chunk(array, 3).join(' ')); console.log(chunk(array, 4).join(' ')); ``` If you like only one mapping at the end, remove the last two `map` and use ``` .map((l => v => l = +(v && (v >= n || l)))(0)); ``` for final mapping.
You could use `some` method and then if the current element is `0` you can slice part of the array from current index and check if its all zeros. ```js const data = [0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0] function check(arr, n) { let chunk = Array(n).fill(0).join(''); return arr.some((e, i) => e === 0 && arr.slice(i, i + n).join('') == chunk) } console.log(check(data, 3)) console.log(check(data, 4)) console.log(check(data, 5)) ```
35,032,889
I am working on a wordpress plugin. I want to get the url of my website and get the page name out of that like `www.example.com/pagename` in this case I want `pagename`. so for that I used native PHP function `$_SERVER['REQUEST_URI']` to get URL of my website. I stored it in `$url` variable as shown below. ``` $url= $_SERVER['REQUEST_URI']; ``` I get this when I echo `url` var ``` /ifar/wellington/ $name= "wellington"; /* I want it like this */ ``` How can I get `wellington` out from this string and store it in `$name`.
2016/01/27
[ "https://Stackoverflow.com/questions/35032889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4688722/" ]
Actually you should use a router, like <https://github.com/auraphp/Aura.Router> or any other. But simple and quick answer for you will be ``` $parts = explode('/', trim($url, '/')); $name = $parts[1]; ``` if you want to get the 2nd uri segment.
``` $url= $_SERVER['REQUEST_URI']; $name = explode("/",$url); echo $name[1]; ``` In $name you got the separate strings in array. You can get the name by doing echo like above if your name is going to come first in your url after your domain name.
16,622
What is the relationship of the option value and the pay off to an option? What happens if the option value > pay off? or if it is equal to the pay off? I read that in a put option , the option value is a solution to $$\sup\_\tau E[\max\left\{K-S,0\right \}]$$, where $K$ is the exercise price. Does this imply that the possible option values are just 0 or K-S. How important is the option value?
2017/05/03
[ "https://economics.stackexchange.com/questions/16622", "https://economics.stackexchange.com", "https://economics.stackexchange.com/users/13132/" ]
The put option allows you to decide to sell at the exercise price $K$ rather than the market price $S$. So if you exercise the put option, in effect it is worth $K-S$ at that point as you could have sold at the market price. You will only do that if it is positive. Hence the $\max\left\{K-S,0\right \}$ expression. If you could only exercise at a particular future point in time, the option would now be worth the expected future benefit $\mathbb{E}[\max\left\{K-S,0\right \}]$ But with a so-called American put option you can exercise at any time up to a limit, making the value the highest of the future expectations, leading to an option value now of $$\sup\_\tau \mathbb{E}[\max\left\{K-S,0\right \}]$$ Typically the option value now is higher than the payoff if exercised now of $K-S$. This difference is called the time value of the option and reflects the benefit from the future payoff being asymmetrical since it cannot be worse than $0$
By option value, I suppose you mean the price of the options (i.e. The option premium) The premium you pay for an option, say $10, consists of two parts - Intrinsic value and Time value. Intrinsic value is simply as you described, the pay off of the option. For a call option, it is the market price - strike price and strike price - market price for a put option. If you have a positive intrinsic value, it means that the option is "in-the-money" aka you are making money now **(K < S)**. The other two results is that the option is "at-the-money", where the strike price is exactly the market price, and "out-of-the-money", where if you exercised the option now you would be making a loss **(S < K)**. This is intended for call options. The opposite holds true for put options. Note that when you are ITM, intrinsic value is positive. The other two scenarios, your intrinsic value is simply 0 and cannot be negative. The time value of the option is therefore, in this case, $10 - Intrinsic value. The reason there is a time value is because an investor would pay a premium based on the probability that the option can result in a ITM outcome before expiry. To calculate the premium of an option, you can use the Black-Scholes model which takes into account Market price, Exercise price, interest rate, term to maturity, volatility as well as probability distribution curve of the underlying asset. In reality, the importance of the value of options only comes into play when the market price is near the exercise price and that is where most of the volume of options trading is. When you are way in the money, it is highly unlikely that the market will turn that much resulting in a loss. In a way, your returns from the option are guaranteed and therefore requires no attention. Similarly, there is low importance when your options are way out of the money. It is highly unlikely that the market will turn by expiry such that you suddenly become in the money and take positive returns from the option. Thereby lies an area when you are around and at the money where trading heavily takes place, and the importance of the option value comes into play. Financial institutions usually set risk limit values which their traders must not exceed. They usually calculate such risks based on the sensitivity of the value to changes in parameters, "Delta, Gamma, Vega, Theta and Rho". One example is Delta which measures the sensitivity of the option price relative to changes in the price of the underlying asset.
42,780,975
Visual Studio Code's default status bar color is blue, and I find it quite distracting. I used [this extension](https://marketplace.visualstudio.com/items?itemName=bentx.vscode-custom-theme) to change the color, but it has stopped working after the *1.10.2* update.
2017/03/14
[ "https://Stackoverflow.com/questions/42780975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7683987/" ]
You can change the colour of the statusbar by editing the user settings by adding these lines of code in it: ```json "workbench.colorCustomizations": { "statusBar.background" : "#1A1A1A", "statusBar.noFolderBackground" : "#212121", "statusBar.debuggingBackground": "#263238" } ```
1. I am going to save 30 minutes of time to noobs like me - it has to be edited in the *settings.json* file. The easiest way to access it is menu command *File* → *Preferences* → *Settings*, search for "Color", choose an option "Workbench: Color Customizations" → "Edit in settings.json". 2. This uses the [solution proposed by Gama11](https://stackoverflow.com/questions/42780975/visual-studio-code-status-bar-color/43446100#43446100), but ***note***: the final form of the code in the *settings.json* file should be like this - note the *double* curly braces around "workbench.colorCustomizations": ```json { // fontSize just for testing purposes, commented out. //"editor.fontSize" : 12 // StatusBar color: "workbench.colorCustomizations": { "statusBar.background" : "#303030", "statusBar.noFolderBackground" : "#222225", "statusBar.debuggingBackground": "#511f1f" } } ``` After you copy/pasted code above, press `Ctrl` + `S` to save the changes to 'settings.json'. The solution has been adapted from *[Status Bar colors](https://code.visualstudio.com/api/references/theme-color#status-bar-colors)*.
13,894,878
i have a list of user reviews that a user can choose to approve or delete. I have the reviews.php file which lists the pending reviews, a approve\_review.php file and a delete\_review.php file. Once the user approves the review i need the mysql column 'approve' to be changed from '0' to '1'. Same applies for the delete but instead of updating 'approve' it will update 'delete'. Everything i've tried isn't working. please can someone tell me where i'm going wrong. Thanks. reviews.php: ``` <?php $pending_set = get_pending_reviews(); while ($reviews = mysql_fetch_array($pending_set)) { ?> <div class="prof-content-pend-reviews" id="reviews"> <div class="pend-review-content"> <?php echo "{$reviews['content']}"; ?> </div> <a href="includes/approve_review.php"><div class="approve"></div></a> <a href="includes/delete_review.php"><div class="delete"></div></a> </div> <? } ?> ``` approve\_review.php: ``` <?php require_once("session.php"); require_once("functions.php"); require('_config/connection.php'); approve_review ($_GET['review'], $_SESSION['user']); header('Location: http://localhost/ptb1/reviews.php'); ?> ``` Function: ``` function approve_review($review_id, $user) { global $connection; global $_SESSION; $query = "UPDATE ptb_reviews SET approved='1' WHERE id=$review_id AND to_user_id=$user"; mysql_query($query, $connection); } ```
2012/12/15
[ "https://Stackoverflow.com/questions/13894878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1904892/" ]
I had the same issue and what I did was replace all the ints with longs in the parameters. Old Calls: ``` [DllImport("odbc32.dll")] internal static extern int SQLDataSources(int EnvHandle, int Direction, StringBuilder ServerName, int ServerNameBufferLenIn, ref int ServerNameBufferLenOut, StringBuilder Driver, int DriverBufferLenIn, ref int DriverBufferLenOut); [DllImport("odbc32.dll")] internal static extern int SQLAllocEnv(ref int EnvHandle); ``` New Calls: ``` [DllImport("odbc32.dll")] internal static extern int SQLDataSources(long EnvHandle, long Direction, StringBuilder ServerName, long ServerNameBufferLenIn, ref long ServerNameBufferLenOut, StringBuilder Driver, long DriverBufferLenIn, ref long DriverBufferLenOut); [DllImport("odbc32.dll")] internal static extern int SQLAllocEnv(ref long EnvHandle); ``` 32-Bit DSNs Won't Appear in the 64-Bit calls. This is the method I am using (Running Windows 8 x64): ``` [DllImport("odbc32.dll")] internal static extern int SQLDataSources(long EnvHandle, long Direction, StringBuilder ServerName, long ServerNameBufferLenIn, ref long ServerNameBufferLenOut, StringBuilder Driver, long DriverBufferLenIn, ref long DriverBufferLenOut); [DllImport("odbc32.dll")] internal static extern int SQLAllocEnv(ref long EnvHandle); //[DllImport("odbc32.dll")] //internal static extern int SQLDataSources(int EnvHandle, int Direction, StringBuilder ServerName, int ServerNameBufferLenIn, // ref int ServerNameBufferLenOut, StringBuilder Driver, int DriverBufferLenIn, ref int DriverBufferLenOut); //[DllImport("odbc32.dll")] //internal static extern int SQLAllocEnv(ref int EnvHandle); public static List<ODBC_System_DSN_Entry> ListODBCsources() { List<ODBC_System_DSN_Entry> entries = new List<ODBC_System_DSN_Entry>(); long envHandle = 0; const long SQL_FETCH_NEXT = 1; const long SQL_FETCH_FIRST_SYSTEM = 32; if (SQLAllocEnv(ref envHandle) != -1) { long ret; StringBuilder serverName = new StringBuilder(1024); StringBuilder driverName = new StringBuilder(1024); long snLen = 0; long driverLen = 0; ret = SQLDataSources(envHandle, SQL_FETCH_FIRST_SYSTEM, serverName, serverName.Capacity, ref snLen, driverName, driverName.Capacity, ref driverLen); while (ret == 0) { //System.Windows.Forms.MessageBox.Show(serverName + System.Environment.NewLine + driverName); entries.Add(new ODBC_System_DSN_Entry(serverName.ToString(), driverName.ToString())); ret = SQLDataSources(envHandle, SQL_FETCH_NEXT, serverName, serverName.Capacity, ref snLen, driverName, driverName.Capacity, ref driverLen); } return entries; } return null; } public struct ODBC_System_DSN_Entry { internal String _server; internal String _driver; internal ODBC_System_DSN_Entry(String server, String driver) { _server = server; _driver = driver; } public String Server { get { return _server; } } public String Driver { get { return _driver; } } } ```
The first thing I'd do it get the parameter types right. Those name length ptr arguments are SQLSMALLINTs not ints. Also ODBC APIs return SQLRETURN types not int. See [SQLDatSources](http://msdn.microsoft.com/en-us/library/windows/desktop/ms711004%28v=vs.85%29.aspx).
3,769,088
I have two classes, `TProvider` and `TEncrypt`. The calling application will talk to the `TProvider` class. The calling application will call `Initialise` first to obtain the handle `mhProvider`. I require access to this handle later when i try to perform encryption, as the `TEncrypt` class donot have access to this handle `mhProvider`. How can i get access to this handle? ``` class TProvider { public: int Initialise(); int Encrypt(); private: HCRYPTPROV mhProvider; TEncrypt* mpEncrypt; }; //------------------------------------ class TEncrypt { public: int Encryption(); private: int GenerateEncryptionKey(); HCRYPTKEY mhKey; }; //------------------------------------ int TEncrypt::Encryption() { vStatus = GenerateEncryptionKey(); // will go on to perform encryption after obtaining the key return(vStatus); } //------------------------------------ int TEncrypt::GenerateEncryptionKey() { BOOL bRet = CryptGenKey(mhProvider, CALG_AES_256, CRYPT_EXPORTABLE, &mhKey); } ```
2010/09/22
[ "https://Stackoverflow.com/questions/3769088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119535/" ]
Either you pass the handle to TEncrypt via a *(constructor/method) parameter*, or you make it available via a *global variable*. I would prefer the former, as global variables make the code harder to understand, maintain and test. Availability may also be indirect, e.g. you pass an object to `TEncrypt::Encryption()` which provides access to the handle via one of its public methods. (of course you can also pass it through a file, DB, ... but let's keep the focus within the program.) ### Update: an example ``` class TEncrypt { public: int Encrypt(HCRYPTPROV& mhProvider); private: int GenerateEncryptionKey(HCRYPTPROV& mhProvider); HCRYPTKEY mhKey; }; //------------------------------------ int TEncrypt::Encrypt(HCRYPTPROV& mhProvider) { vStatus = GenerateEncryptionKey(mhProvider); // will go on to perform encryption after obtaining the key return(vStatus); } //------------------------------------ int TEncrypt::GenerateEncryptionKey(HCRYPTPROV& mhProvider) { BOOL bRet = CryptGenKey(mhProvider, CALG_AES_256, CRYPT_EXPORTABLE, &mhKey); } ``` Note: I renamed `TEncrypt::Encrypt` because it is better to use verbs as method names rather than nouns.
If `mhProvider` is needed by `TEncrypt`, then why is it in the class `TProvider`? Somehow your classes don't look to be properly designed.
27,259,096
I am trying to get a count on the number of times a number (`start_value`) doubles until it reaches a particular value (`end_value`) in the cleanest way possible. Consider the following example: ``` id start_value end_value 1 40 130 2 100 777 3 0.20 2.1 example 1: 40 * 2 = 80 80 * 2 = 160 160 = above value so therefore we had 2 doubles example 2: 100 * 2 = 200 200 * 2 = 400 400 * 2 = 800 800 = above value so we had 3 doubles example 3: 0.20 * 2 = 0.4 0.4 * 2 = 0.8 0.8 * 2 = 1.6 1.6 * 2 = 3.2 3.2 = 4 doubles ```
2014/12/02
[ "https://Stackoverflow.com/questions/27259096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1285948/" ]
Divide the end value by the start value to get the factor between them. For example 130/40 = 3.25. Doubling the value once gives a factor 2, and doubling it twice gives a factor 4, and so on. You can use the logarithm for base 2 to calculate how many times you need to double the value to get a specific factor. log2(3.25) = 1.7004397... Then you round that up to get the whole number of times that you need to double it. The binary logarithm can be calculated as log(n) / log(2): ``` select id, ceil(log(end_value / start_value) / log(2)) as times from TheTable ``` Demo: <http://sqlfiddle.com/#!15/90099/4>
Try below SQL : ``` select id, start_value, end_value, floor(log(end_value / start_value,2)/2) from TempTable ``` Hope this Helps :)
23,798,380
I have a number of links on the page, dynamically generated like so: ``` <a href="#" class="more-info-item" ng-click="showStats(item, $event)"> More information </a> ``` I also have a simple custom template that should show an item's name: ``` <script type="text/ng-template" id="iteminfo.html"> <div class="item-name"> {{item.name}} </div> </script> ``` What I would like to do is: when the link is clicked, to dynamically compile the template, and insert it in the DOM right after the link. I tried using $compile within showStats method to compile the template, but I got an error that $compile wasn't found. How would I go about doing this (and also provide item as part of the scope for the newly generated template)?
2014/05/22
[ "https://Stackoverflow.com/questions/23798380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306296/" ]
Here is a solution using a custom directive which injects the item dynamically using ng-if: [View Solution with Plunker](http://plnkr.co/edit/itt4yIdLeg74BL3YlLwr?p=preview) **html:** ``` <script type="text/ng-template" id="iteminfo.html"> <div class="item-name" ng-if="item.visible"> {{item.name}} </div> </script> <div ng-repeat="item in items" > <a href="#" class="more-info-item" more-info="item" ng-click="item.visible =!item.visible"> More information </a> </div> ``` **script:** ``` angular.module('app', []) .controller('ctrl', function($scope) { $scope.items = [{name:'apples', visible:false},{name:'pears', visible:false},{name:'oranges', visible:false}]; }) .directive('moreInfo', function($compile,$templateCache) { return { restrict: 'A', scope: '=', link: function(scope, element, attr) { var itemInfo = angular.element($templateCache.get('iteminfo.html')); var lfn = $compile(itemInfo); element.parent().append(itemInfo); lfn(scope); } }; }); ```
You can use the built-in **[ngInclude](https://docs.angularjs.org/api/ng/directive/ngInclude)** directive in `AngularJS` Try this out **[Working Demo](http://jsfiddle.net/UGj7t/1/)** **html** ``` <div ng-controller="Ctrl"> <a href="#" class="more-info-item" ng-click="showStats(item, $event)"> More information </a> <ng-include src="template"></ng-include> <!-- iteminfo.html --> <script type="text/ng-template" id="iteminfo.html"> <div class="item-name"> {{item.name}} </div> </script> </div> ``` **script** ``` function Ctrl($scope) { $scope.flag = false; $scope.item = { name: 'Manu' }; $scope.showStats = function (item, event) { $scope.item = item; $scope.template = "iteminfo.html"; } } ```
9,419,875
I like to have a typical "usage:" line in my `cmd.exe` scripts — if a parameter is missing, user is given simple reminder of how the script is to be used. The problem is that I can't safely predict whether potential user would use GUI or CLI. If somebody using GUI double-clicks this script in Explorer window, they won't have chance to read anything, unless I `pause` the window. If they use CLI, `pause` will bother them. So I'm looking for a way to detect it. ``` @echo off if _%1_==__ ( echo usage: %nx0: filename rem now pause or not to pause? ) ``` Is there a nice solution on this?
2012/02/23
[ "https://Stackoverflow.com/questions/9419875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835945/" ]
Start your batch checking for %WINDIR% in %cmdcmdline% like this: ``` echo "%cmdcmdline%" | findstr /ic:"%windir%" >nul && ( echo Interactive run of: %0 is not allowed pause exit /B 1 ) ```
Similar approach... ``` setlocal set startedFromExplorer= echo %cmdcmdline% | find /i "cmd.exe /c """"%~0""" >nul if not errorlevel 1 set startedFromExplorer=1 ... if defined startedFromExplorer pause goto :EOF ```
11,559,592
I embed three Google Fonts from <http://www.google.com/webfonts> (Dosis, Open Sans, Lato) And they all work fine except IE9 where it returns: ``` CSS3111: @font-face encountered unknown error. 2HG_tEPiQ4Z6795cGfdivPY6323mHUZFJMgTvxaG2iE.eot CSS3111: @font-face encountered unknown error. KlmP_Vc2zOZBldw8AfXD5g.eot CSS3111: @font-face encountered unknown error. zLhfkPOm_5ykmdm-wXaiuw.eot ``` And breaks entire website occasionally. What can be done to resolve this?
2012/07/19
[ "https://Stackoverflow.com/questions/11559592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1074346/" ]
Commenting out the 2nd source declaration for the EOT font worked for me. Make sure you the 1st declaration right above "src: url("../fonts/webfonts/Helvetica Neue.eot");" Tested on Chrome, Firefox,Sarafi, IE9-10-11. ``` @font-face { font-family: 'Helvetica Neue'; font-style: normal; font-weight: 400; src: url("../fonts/webfonts/Helvetica Neue.eot"); src: local("Helvetica Neue"), local("Helvetica Neue"), /*url("../fonts/webfonts/Helvetica Neue.eot?#iefix") format("embedded-opentype"),*/ url("../fonts/webfonts/Helvetica Neue.woff2") format("woff2"), url("../fonts/webfonts/Helvetica Neue.woff") format("woff"), url("../fonts/webfonts/Helvetica Neue.ttf") format("truetype"), url("../fonts/webfonts/Helvetica Neue.svg") format("svg"); } ```
I had the same issue in IE11, I fixed the issue by converting my font file from `.woff2` to `.woff`. In general, make sure the browser supports the font file format.
12,948,072
I have a issue with radio button array. I have 1 timer when timer is 0 and select 1 radio button then that value get in jquery. ``` <li> <span class="option">Option1 : Value1 </span> <input type="radio" name="cmbans[][1]" id="cmbans[][1]" value="Value1" /> </li> <li> <span class="option">Option2 : Value2 </span> <input type="radio" name="cmbans[][2]" id="cmbans[][2]" value="Value2" /> </li> <li> <span class="option">Option1 : Value1 </span> <input type="radio" name="cmbans[][3]" id="cmbans[][3]" value="Value3" /> </li> ``` This radio button name or id get in jquery but problem is this is array so how can i get this. Pls help me. Thanks in advance
2012/10/18
[ "https://Stackoverflow.com/questions/12948072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699283/" ]
I didn't get ypur problem correctly. I'm not sure if this one helps you.. Change your html like this.. ``` <li> <span class="option">Option1 : Value1 </span> <input type="radio" name="cmbans[]" id="cmbans1" value="Value1" /> </li> <li> <span class="option">Option2 : Value2 </span> <input type="radio" name="cmbans[]" id="cmbans2" value="Value2" /> </li> <li> <span class="option">Option1 : Value1 </span> <input type="radio" name="cmbans[]" id="cmbans3" value="Value3" /> </li> ``` Now create jquery to get the value like this.. ``` if(timer == 0){ var value = $('#id of radio').val(); } ```
To select element whose ids' have special characters you have to escape these special characters. In your case `[` and `]`, also your choice in id naming is quite stramge ``` $("#cmbans\\[\\]\\[1\\]").val() ```
5,697,453
The following method attempts to calculate the number of days in a year of an NSHebrew calendar object, given a hebrew year. For some reason, I'm getting inconsistent results across devices. The test case was the date of May 25, 1996. One device was returning one day longer (the correct value) than another device, which was one day short. ``` - (NSInteger) lengthOfYearForYear:(NSInteger)year{ // // Then get the first day of the current hebrew year // NSCalendar *hebrewCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSHebrewCalendar]; NSDateComponents *roshHashanaComponents = [[[NSDateComponents alloc] init ]autorelease]; [roshHashanaComponents setDay:1]; [roshHashanaComponents setMonth:1]; [roshHashanaComponents setYear:year]; [roshHashanaComponents setHour:12]; [roshHashanaComponents setMinute:0]; [roshHashanaComponents setSecond:0]; NSDate *roshHashanaDate = [hebrewCalendar dateFromComponents:roshHashanaComponents]; // // Then convert that to gregorian // NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *gregorianDayComponentsForRoshHashana = [gregorianCalendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:roshHashanaDate]; //Determine the day of the week of the first day of the current hebrew year NSDate *oneTishreiAsGregorian = [gregorianCalendar dateFromComponents:gregorianDayComponentsForRoshHashana]; // // Then get the first day of the next hebrew year // NSDateComponents *roshHashanaOfNextYearComponents = [[NSDateComponents alloc] init ]; NSInteger tempYear = year+1; [roshHashanaOfNextYearComponents setDay:1]; [roshHashanaOfNextYearComponents setMonth:1]; [roshHashanaOfNextYearComponents setYear:tempYear]; [roshHashanaOfNextYearComponents setHour:12]; [roshHashanaOfNextYearComponents setMinute:0]; [roshHashanaOfNextYearComponents setSecond:0]; NSDate *roshHashanaOfNextYearAsDate = [hebrewCalendar dateFromComponents:roshHashanaOfNextYearComponents]; [roshHashanaOfNextYearComponents release]; [hebrewCalendar release]; // // Then convert that to gregorian // NSDateComponents *gregorianDayComponentsForRoshHashanaOfNextYear = [gregorianCalendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:roshHashanaOfNextYearAsDate]; //Determine the first day of the week of the next hebrew year NSDate *oneTishreiOfNextYearAsGregorian = [gregorianCalendar dateFromComponents:gregorianDayComponentsForRoshHashanaOfNextYear]; // Length of this year in days NSTimeInterval totalDaysInTheYear = [oneTishreiOfNextYearAsGregorian timeIntervalSinceReferenceDate] - [oneTishreiAsGregorian timeIntervalSinceReferenceDate]; // // We round here because of slight offsets in the Gregorian calendar. // totalDaysInTheYear = round(totalDaysInTheYear/86400); if(totalDaysInTheYear == 353 || totalDaysInTheYear == 383){ totalDaysInTheYear = 0; }else if(totalDaysInTheYear == 354 || totalDaysInTheYear == 384){ totalDaysInTheYear = 1; }else if(totalDaysInTheYear == 355 || totalDaysInTheYear == 385){ totalDaysInTheYear = 2; } return totalDaysInTheYear; } ``` I *think* that it could be because I'm not using `NSHourCalendarUnit` and smaller, but I'm not sure. Would that do it? Is there anything else that's blatantly incorrect?
2011/04/18
[ "https://Stackoverflow.com/questions/5697453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224988/" ]
An object initilizer statement like `var x = new Foo { Property1 = 5};` will be implemented as something like this: ``` Foo temp = new Foo(); temp.Property1 = 5; x = temp; ``` As you can see, the properties in the initiallizer are set after the object is constructed, however the variable isn't set to the fully-initialized object until *all* the properties are set, so if an exception **is** thrown, the constructed object is lost even if the exception is caught (the variable will remain `null` or whatever value it had before).
It is fully constructed first, then initialized. You will however never get a reference to such an object if an exception is thrown, the compiler makes sure that your reference can only ever refer to a properly initialized object. It uses a temporary to guarantee this. So for example, this code: ``` var obj = new Model { FirstName = reader[0].ToString(), LastName = reader[1].ToString(), Age = Convert.ToInt32(reader[2].ToString()) }; ``` Is rewritten by the compiler to: ``` var temp = new Model(); temp.FirstName = reader[0].ToString(); temp.LastName = reader[1].ToString(); temp.Age = Convert.ToInt32(reader[2].ToString()) var obj = temp; ```
336,901
I need a verb meaning "walking slowly into water" that fits this example: > > She shivered a bit - as the lake water was cold - but then continued to \_\_\_\_ into the deep. > > >
2016/07/13
[ "https://english.stackexchange.com/questions/336901", "https://english.stackexchange.com", "https://english.stackexchange.com/users/166244/" ]
You can use the word "sink": > > We watched the Titanic "sink" into the cold water. > > > The more you struggle, the more you will "sink" in quicksand. > > > As our feet "sank" into the mud, the alligators got much closer. > > > It describes slow or sluggish speed.
I like the word "falter". There is not a lot of context, but what's provided paints a picture of a woman who doesn't want to be there (is she being forced? self-harm? is the context more benign and innocent?). Whatever the context, she is shivering, either in fear reaction or reaction to the cold water, and in a similar position, I would not want to move forward. If I did, I might be having second thoughts about doing so, creating a hesitancy. "...continued to falter into the deep." It has the added benefit of drawing analogous 'similarism' to words like farther, falling, father, etc.
11,845,287
I'm looking for an efficient way to store a huge number of booleans (up to 2.5\*10e11) in PHP's memory. My first idea was to create an array of integers and store one boolean per bit in each integer: ``` // number of booleans to store $n = 2.5 * pow(10, 11); // bits per integer $bitsPerInt = PHP_INT_SIZE * 8; // init storage $storage = array(); for ($i=0; $i<ceil($n/$bitsPerInt); $i++) { $storage[$i] = 0; } // bits in each integer can be accessed using PHP's bitwise operators ``` However, the overhead with this solution is still way too big: Storing 10^8 booleans (bits) in a 32-bit environment (PHP\_INT\_SIZE = 4 bytes) needs an array of 3125000 integers, consuming ~ 254 MB of memory, whereas the rare data of 10^8 booleans would only need ~ 12 MB. So which is the best way to store a huge number of booleans in PHP (5)?
2012/08/07
[ "https://Stackoverflow.com/questions/11845287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/846987/" ]
Perhaps the SplStack or the SplFixedArray classes from the [SPL](http://php.net/manual/es/book.spl.php) fit your needs better.
If using one bit per value uses too much memory then you will need to rethink your design - everything in memory is just bits at the end of the day, and you can't squeeze more than one boolean value into a single bit (by definition).
14,352,487
I was reading this question [Awk code to select multiple patterns](https://stackoverflow.com/questions/14336710/awk-code-to-select-multiple-patterns) The user has this as input ``` ------------------------------------------------------------------------ r4544 | n479826 | 2012-08-28 07:12:33 -0400 (Tue, 28 Aug 2012) | 1 line Changed paths: M /branches/8.6.0/conf/src/main/config/RTSConfig.xml CET-402: some text comment ------------------------------------------------------------------------ r4550 | n479826 | 2012-09-04 05:51:29 -0400 (Tue, 04 Sep 2012) | 1 line Changed paths: M /branches/8.6.0/conf/src/main/config/RTSConfig.xml M /branches/8.6.0/conf/src/main/config/base.cfg M /branches/8.6.0/conf/src/main/config/prod.cfg M /branches/8.6.0/conf/src/main/config/qa.cfg M /branches/8.6.0/conf/src/main/config/uat.cfg CET-438: some text comment ``` and he wants this as output ``` r4544 | n479826 | 2012-08-28 07:12:33 | /branches/8.6.0/conf/src/main/config/RTSConfig.xml r4550 | n479826 | 2012-09-04 05:51:29 | /branches/8.6.0/conf/src/main/config/RTSConfig.xml r4550 | n479826 | 2012-09-04 05:51:29 | /branches/8.6.0/conf/src/main/config/base.cfg r4550 | n479826 | 2012-09-04 05:51:29 | /branches/8.6.0/conf/src/main/config/prod.cfg r4550 | n479826 | 2012-09-04 05:51:29 | /branches/8.6.0/conf/src/main/config/qa.cfg r4550 | n479826 | 2012-09-04 05:51:29 | /branches/8.6.0/conf/src/main/config/uat.cfg ``` The correct answer is this ``` awk -F"|" '/^r/{a=$1;b=$2;c=substr($3,0,20)}/^ M/{gsub(/ M /," ");print a"|"b"|"c"|"$0}' your_file ``` I didn't understood that fully. Now i got this part `/^r/{a=$1;b=$2;c=substr($3,0,20)}/^` but i didn't get the second part `M/{gsub(/ M /," ");print a"|"b"|"c"|"$0}` My problems are 1. What is `M` means in the beginning 2.Now awk will read the file line by line so it means at the second line i.e Chngaed paths the value of `a =0` because there is no field separator `|` on that line 2. Now when the awk comes to third line then again `a,b,c =0` and `$0 = /bracnhes` but how is the result still showing the old value of a,b,c I am getting confused when awk is used on multi lines
2013/01/16
[ "https://Stackoverflow.com/questions/14352487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1982150/" ]
I was lazy enough to explain the answer :) But lemme put my lazyness aside for some time now: ``` /^r/{a=$1;b=$2;c=substr($3,0,20)} ``` The above block of code will execute only when the line starts with a letter r. inside the block says store the first field in a ,second field in b and third field from input is : ``` 2012-08-28 07:12:33 -0400 (Tue, 28 Aug 2012) ``` but i need only the date with timestamp and the rest is obsolete for me. it is always 20 characters. so i took a substring from the third field and stored it in c. my main interest was the line which starts with /^ M/ which i have to display with the information present in the previous line which start with r and for sure there is a line which starts with r before our desired line which has all the information i have to prepend the lines which start with M. so every time a line starts with M will be prepended with the values stored in a b and c. ``` M/{gsub(/ M /," ");print a"|"b"|"c"|"$0} ``` gsub part will remove the part of " M " with a space from the current line. print part just prepends the value of a b and c to the current line with | as teh separator. This what the logic is! I will be back into my lazy mode now :)
The reason is that values of a, b and c are not replaced before the M is encountered. so it is still appended to the print statement.
762,147
my attempt $$\lim\_{x\to \infty}\frac{\frac{f(x)}{g(x)}}{\frac{f'(x)}{g'(x)}}\text{ yields }\frac{0}{0}$$ then use l'hopital on this $$\lim\_{x\to \infty}\frac{\frac{f(x)}{g(x)}}{\frac{f'(x)}{g'(x)}} =\lim\_{x\to \infty} \frac{\frac{f'}{g}-\frac{fg'}{g^2}}{\frac{f''}{g'}-\frac{f'g''}{g'^2}} $$ $$\lim\_{x\to \infty}\frac{\frac{f(x)}{g(x)}}{\frac{f'(x)}{g'(x)}} =\lim\_{x\to \infty} \frac{\frac{f'}{f}\frac{f}{g}-\frac{f}{g}\frac{g'}{g}}{\frac{f''}{f'}\frac{f'}{g'}-\frac{f'}{g'}\frac{g''}{g'}} $$ $$\lim\_{x\to \infty}\frac{\frac{f}{g}}{\frac{f'}{g'}} =\lim\_{x\to \infty} \frac{\frac{f}{g} \left( \frac{f'}{g'}-\frac{f}{g}\right)}{\frac{f'}{g'} \left( \frac{f''}{f'}-\frac{g''}{g'}\right)} $$ assuming such limits exists, and equal to $L$, leads to $$\lim\_{x\to \infty}\frac{\frac{f}{g}}{\frac{f'}{g'}} =\lim\_{x\to \infty} \frac{\frac{f}{g} }{\frac{f'}{g'} }\cdot \lim \frac{ \left( \frac{f'}{g'}-\frac{f}{g}\right)}{ \left( \frac{f''}{f'}-\frac{g''}{g'}\right)} $$ $$L =L\cdot \lim\_{x\to \infty} \frac{ \left( \frac{f'}{g'}-\frac{f}{g}\right)}{ \left( \frac{f''}{f'}-\frac{g''}{g'}\right)} $$ I am stuck here.. I would really like to prove that $L$ is not zero and not $\infty$ the proof is obvious for polynomials functions f, and g, and I can not find any counter examples.. any help would be much appreciated.. we can assume the initial condition comes from appropriately using l'hopital
2014/04/20
[ "https://math.stackexchange.com/questions/762147", "https://math.stackexchange.com", "https://math.stackexchange.com/users/61346/" ]
Let $f(x)=e^{-x^2}$ and $g(x)=e^{-x}$.
This seems like it would require some type of lemma which described the behavior of the products and quotients of $\ f:f'::f':f''$. You can factor $\ f'/g'$ out of the expression you stopped at, but are then stuck with a difference quotient with unlike terms. Without a rigorous lemma which would allow you replace limits of the divisor and dividend with known quantities, it seems unlikely you would be able to simplify further. I'll post more if I come up with something further. Interesting post and concept, however. One differing thought is that it might be necessary to first prove that indeterminate form is never zero, but I think that is a definition and not provable because indeterminate form has logical elements that correspond to defined numbers and ones that are always undefined (i.e., $\ n/0 $). Regarding some of the answers ... Let statements can disprove the hypothesis, but the question remains as to "why" they do so. In the above let statements, the reason the hypothesis can be disproved is because you began with the supposition that indeterminate form can be determined not to be zero.
622,514
This is not my area of expertise, so forgive me if I am getting this completely wrong. Some datacentres are now offering IPv6 addresses and potentially 100s per VM. What would the benefit of this be? Surely you only ever need one address and many ports? What benefit would be gained from having 100s of IPv6 addresses point to the same ethernet interface? thanks
2014/08/19
[ "https://serverfault.com/questions/622514", "https://serverfault.com", "https://serverfault.com/users/238379/" ]
> > What would the benefit of this be? > > > One IP per Website or other such web service immediately springs to mind. Then you don't need to worry about SNI, Virtual Hosts, or any of that. Also, darknet honeypots. > > Surely you only ever need one address and many ports? > > > Most protocols can't specify a different port without the user manually specifying it (a very few services can, usually using using SRV records - I can think of about 3 applications that actually use SRV records off the top of my head). > > What benefit would be gained from having 100s of IPv6 addresses point to the same ethernet interface? > > > You already asked that. > > How many IPv6 addresses can one network card have assigned to it? > > > At least tens of thousands, though if you need more than that you're probably doing something wrong.
You can bind services to particular addresses. For instance, suppose you have machine with global routable address `2001:db8:cafe:babe:20c:29ff:fe01:2345` and you run a DNS- and a web server on that machine. Then, you could add the addresses, say, `2001:db8:cafe:babe::53` for DNS and `2001:db8:cafe:babe::80` for HTTP (and HTTPS) (some purists calculate the hex values for 53 and 80 and use them as interface identifier...). This makes for simple firewall rules: Allow only UDP/53 to `2001:db8:cafe:babe::53` and allow only TCP/80 and TCP/443 to `2001:db8:cafe:babe::80` and so on. For redundancy you might add ULAs, say `fc73:607:a09f:babe:20c:29ff:fe01:2345`. And so on. Another use case is what Chris S mentioned. Bear in mind that for each unicast address on an interface the host must join the according link-local solicited node multicast group. So you may use addresses liberally but you should not exaggerate.
65,940
Aside from obviously the the 60D and 6D being APS-C and Full Frame respectively, What are the main features or new controls that must be learnt about when using the canon 6D to truly master the cameras capabilities, that are not available on a canon 60D?
2015/07/31
[ "https://photo.stackexchange.com/questions/65940", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/41707/" ]
I believe that the "obvious" change here should not be underestimated. After my recent switch from APS-C (Canon) to full frame (Nikon) even with the brand change and the different user interface my biggest challenge are implications of DOF and the fact that because of that the focusing needs to be much more exact.
In Canon 6D you can set up AF micro adjustments for lenses you have. That may improve sharpness a bit. There is also ISO 50 mode that is turned of by default.
7,246
We are told, 'The just (upright) shall live by faith.' So I have a question for the Christians here. How do you understand faith? This does not have to be strictly biblical (since the scripture does not interpret itself, except where it really explicitly does so) but can also use anecdotal, philosophical or logical proofs/reasons for your explanation. A good definition an agnostic gave me once was, '*A strong trust in someone or something*'. Consider the following two sided propositions: **Does faith refer to a blind acceptance?** * We are often told, no, and consider the case of Gideon, but -- * Job is told he does not understand -- he is expected to accept the goodness of God without an explanation he can grasp **Is faith rational?** * In some cases, we are told yes, consider the phrase, 'a reason to believe'... but -- * Abraham is asked to do something wrong on orders from God; that he really will go through with it is met with 'Now I know that you are faithful.' **Does faith itself save a person?** * John 3:16 suggests this, as do some of Jesus' words, but -- * We are repeatedly told, 'Those who endure until the end shall be saved.' **Is faith a work?** * In some traditions, faith is contrasted against works, but -- * James the Just tells us 'faith without works is dead' and in another place equates Abrahams faith and works ('see how he was justified by works...') and indeed many passages where we have the word 'faith', it is really 'faithing', i.e. trusting, meaning something active: a work. **Is doubt a sin, or at least, the lack of faith?** * Jesus warns against doubt as does James the Just, but -- * The Apostle Thomas is in our tradition lauded for his doubt ('the precious doubt of Thomas' it is called) and we are also confronted with a contradiction where the man in the Gospels says, 'I believe, help my unbelief' - suggesting doubt and faith can coexist. **Is faith a source of knowledge?** * Paul suggests so 'evidence of things not seen' * But we have numerous examples where faith itself is only a substitute for knowledge (for example, Abraham's case.) **What is the 'faith of Christ' (pisteis Christou)?** * Some suggest it is Christ's faith, i.e. his *personal* faith, but * The verbiage is vague, and may be interpreted as 'faith in Christ', i.e. believing in him. **We use faith generically, but is this even correct?** * Is having faith in Christ the same as having faith that space aliens exist? * or does our definition of 'faith' implicitly include the **object** of that faith? **Is it possible to overemphasize faith, as opposed to questioning?** * On the one hand, we are told we must enter the Kingdom as little children: that's radical acceptance * We are also told that false Christs will come with false signs and to test all of the spirits. That seems like pretty radical skepticism there. You may either answer personally or for your tradition, or for another person's interpretation. But most of all, I'm hoping to find a consensus on some if not all of these points. It does not have to be either/or, it can be both/and, but if so, *why?*
2012/04/20
[ "https://christianity.stackexchange.com/questions/7246", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/-1/" ]
Faith is the conviction and acceptance of what God has revealed to you. Faith persists even when challenged or confronted with reasons to not accept what God has revealed to you. The object of Christian faith is always God. Christian faith is not blind or baseless, rather it derives it's strength and endurance from it's source: God. Since faith is based on God's revelation, it outweighs any other form of evidence that one may base a conclusion on. It may coexist with doubt when doubt is caused by some evidence contrary to what God has revealed, but faith will always win out.
"Faith is the key to open the door inside of us, that opens to God." It is the bridge between the physical and spiritual worlds. > > Do you not know that your body is a temple of the Holy Spirit, who is > in you, whom you have received from God? You are not your own; > -Corinthians 6:19 > > >
44,778,090
I'm a novice with GNU parallel and I'm only semi-knowledgeable about bash in general so I would really appreciate some advice. I want to read line by line through an input file containing a file path in the first column and the path to a second file in the second column, and for each line use the columns as input in a command. However, I need to replace part of the file name in column one to make my command work. The file would look like this, two file paths separated by tabs: ``` path_to_file/filename1_combined_R1_001.bam \t path_to_file/filename1.fna path_to_file/filename2_combined_R1_001.bam \t path_to_file/filename2.fna ``` What I would need to be able to do is remove the string "\_R1\_001.bam" from column one and replace it with my own string (e.g. \_R1\_fastq) to invoke a script called `removeM`. FYI, I'm not sure if I'm using `--colsep` correctly.The command is as follows: ``` parallel -j10 --colsep '\t' input_file.tsv removeM -1 {1}_R1.fastq -2 {1}_R2.fastq -i {2} -f CoralRemoved_{1}_R1.fastq -r CoralRemoved_{}_R2.fastq` ``` As far as I can tell I could use basename removal (something like {1.} ) but I can't figure out how to remove more than just the extension (.bam). Thank you in advance.
2017/06/27
[ "https://Stackoverflow.com/questions/44778090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8219909/" ]
I ended up figuring this out for myself. I used --colsep to split the files into fields and then a regex to replace the string. The 1 before the equals signs say to print the first field while the regex within the equal signs do the string replacement. `parallel -j10 --colsep '\t'-a $2 removeM -1 bamToFastq_{=1s/_R1_001.bam//=}_R1.fastq.gz -2 bamToFastq_{=1s/_R1_001.bam//=}_R2.fastq.gz -i {2} -f CoralRemoved_bamToFastq_{1}_R1.fastq -r CoralRemoved_bamToFastq_{1}_R2.fastq`
This does not answer the full question, so treat it as a comment. Version 20170322 introduced dynamic replacement strings, which might be useful here. A dynamic replacement string is a `--rpl` definition that takes an argument. The argument is grabbed with () in the replacement string and used in the code to run as $$1 (and $$2, $$3 ... if there are more ()-groups). Here are a few examples that each correspond to a Bash parameter expansion: ``` # Bash ${a:-myval} --rpl '{:-([^}]+?)} $_ ||= $$1', # Bash ${a:2} --rpl '{:(\d+?)} substr($_,0,$$1) = ""', # Bash ${a:2:3} --rpl '{:(\d+?):(\d+?)} $_ = substr($_,$$1,$$2);', # Bash ${a#bc} --rpl '{#([^#][^}]*?)} s/^$$1//;', # Bash ${a%def} --rpl '{%([^}]+?)} s/$$1$//;', # Bash ${a/def/ghi} ${a/def/} --rpl '{/([^}]+?)/([^}]*?)} s/$$1/$$2/;', # Bash ${a^a} --rpl '{^([^}]+?)} s/^($$1)/uc($1)/e;', # Bash ${a^^a} --rpl '{^^([^}]+?)} s/($$1)/uc($1)/eg;', # Bash ${a,A} --rpl '{,([^}]+?)} s/^($$1)/lc($1)/e;', # Bash ${a,,A} --rpl '{,,([^}]+?)} s/($$1)/lc($1)/eg;', ``` These are, by the way, enabled, if you use `--plus`. So to remove a string (or more accurately: a regexp) from the end you can use: ``` $ parallel --plus echo {%_R1_001.bam} ::: MyOrganism_R1_001.bam MyOrganism ``` Or to replace a string: ``` $ parallel --plus echo {/_R1_001.bam/_R1.fastq.gz} ::: MyOrganism_R1_001.bam MyOrganism_R1.fastq.gz ``` Or you could make your own where you expressed how many .'s or \_'s you wanted to remove: ``` $ parallel --rpl '{_(\d+)} s/([_.][^_.]*){$$1}$//' \ echo {_1} {_2} {_3} ::: filename2_combined_R1_001.bam filename2_combined_R1_001 filename2_combined_R1 filename2_combined ``` You could then have this `--rpl` definition in your `~/.parallel/config`.
73,369,181
``` func writeToChan(wg *sync.WaitGroup, ch chan int, stop int) { defer wg.Done() for i := 0; i < stop; i++ { ch <- i } } func readToChan(wg *sync.WaitGroup, ch chan int) { defer wg.Done() for n := range ch { fmt.Println(n) } } func main() { ch := make(chan int, 3) wg := new(sync.WaitGroup) wg.Add(2) go writeToChan(wg, ch, 5) go readToChan(wg, ch) wg.Wait() } ``` ``` 0 1 2 3 4 fatal error: all goroutines are asleep - deadlock! ``` I assume that the `readToChan` always reads continuously, and the `writeToChan` write to the channel and waits while the channel is read. I don't know why the output showed deadlock while I added two 'wait' to the WaitGroup.
2022/08/16
[ "https://Stackoverflow.com/questions/73369181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19733327/" ]
You need to close channel at the sender side. By using ```golang for n := range ch { fmt.Println(n) } ``` The loop will only stop when `ch` is closed correct example: ```golang package main import ( "fmt" "sync" ) func writeToChan(wg *sync.WaitGroup, ch chan int, stop int) { defer wg.Done() for i := 0; i < stop; i++ { ch <- i } close(ch) } func readToChan(wg *sync.WaitGroup, ch chan int) { defer wg.Done() for n := range ch { fmt.Println(n) } } func main() { ch := make(chan int, 3) wg := new(sync.WaitGroup) wg.Add(2) go writeToChan(wg, ch, 5) go readToChan(wg, ch) wg.Wait() } ```
If close is not called on buffered channel, reader doesn't know when to stop reading. Check this example with for and select calls(to handle multi channels). <https://go.dev/play/p/Lx5g9o4RsqW> ``` package main import ( "fmt" "sync" "time") func writeToChan(wg *sync.WaitGroup, ch chan int, stop int, quit chan<- bool) { defer func() { wg.Done() close(ch) fmt.Println("write wg done") }() for i := 0; i < stop; i++ { ch <- i fmt.Println("write:", i) } fmt.Println("write done") fmt.Println("sleeping for 5 sec") time.Sleep(5 * time.Second) quit <- true close(quit) } func readToChan(wg *sync.WaitGroup, ch chan int, quit chan bool) { defer func() { wg.Done() fmt.Println("read wg done") }() //using rang over //for n := range ch { // fmt.Println(n) //} //using Select if you have multiple channels. for { //fmt.Println("waiting for multiple channels") select { case n := <-ch: fmt.Println("read:", n) // if ok == false { // fmt.Println("read done") // //return // } case val := <-quit: fmt.Println("received quit :", val) return // default: // fmt.Println("default") } } } func main() { ch := make(chan int, 5) ch2 := make(chan bool) wg := new(sync.WaitGroup) wg.Add(2) go writeToChan(wg, ch, 3, ch2) go readToChan(wg, ch, ch2) wg.Wait() } ``` Output: ``` write: 0 write: 1 write: 2 write done sleeping for 5 sec read: 0 read: 1 read: 2 write wg done received quit : true read wg done Program exited. ```
27,793,848
In our one of production database, we have 4 column table and there are no PK,UK constraints on it. only one notnull constraint on one column. The inserts are slow on this table and when I checked the indexes , there is one index which is built on all columns. It is a normal table and not IOT. I really don't see a need of all column index, but wondering why the developers has created it? Appreciate your thoughts?
2015/01/06
[ "https://Stackoverflow.com/questions/27793848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3825288/" ]
One case where it could be useful is, Say for example, you are trying to check the existence of records in this table and for that you have to have joins on all four columns. So in such a case if you have written a correlated query like below, ``` SELECT <something> FROM table_1 t1 WHERE EXISTS (SELECT 1 FROM table_t2 t2 where t1.c1=t2.c1 and t1.c2=t2.c2 and t1.c3=t2.c3 and t1.c4=t2.c4) ``` Apart from above case, it looks an error to me from developer's side.
Indexes are good to better query optimization but causes slow updates/inserts because the indexes needs to be updated at each modification. If these tables first use is querying and inserts happens only in a specific periods like a batch at the beginning or the end of the day only, then you can remove the indexes before updating tables and then restore them. In addition, all the queries all these tables need to be analysed to see which indexes are useful and which are not? Anyway, You need to ask developers before removing these indexes.
8,131,692
I've been looking for a solution with Bitbucket and XCode. As everybody knows, XCode 4.2 comes with git support. I've created a bitbucket account and I wanted to push my changes to my repository, I've followed this tutorial <https://confluence.atlassian.com/display/BITBUCKET/Use+the+SSH+protocol+with+Bitbucket> However this is the problem I'm facing. When I'm in the Organizer - Repositories Section at XCode, I go to my remotes folder and create a repository. ssh://git@bitbucket.org/username/myrepo.git However when I'm asked for Name and password, the ones I provide as username and password fails. I've also tried with git as a user but no luck. UPDATE: I've created a ~/.ssh/config file where I've added a specific configuration for bitbucket. ``` Host bitbucket.org HostName bitbucket.org IdentityFile ~/.ssh/bitbucket User username ``` I've tested it with ssh -T git@bitbucket.org and It works, it gets authenticated. However, when I test this with XCode I got the following error. "Authentication failed because the name or password was incorrect." I know I'm missing something here. UPDATE 2: I've managed to solve the issue but only from command line, not from XCode. I'll post my solution later but feel free if you have a way to do it from XCode Thanks
2011/11/15
[ "https://Stackoverflow.com/questions/8131692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031846/" ]
**iOS 9.2, Xcode 7.2, ARC enabled** It seems that every time I start a new Xcode project, I have to crawl back to this post and others like it to put together a solution to get my \*.git repository set up for the new project. My goal with this answer is to update and compile a full solution. Thanks to all original contributors, especially "trolley". For a very thorough description, please refer to this link: <http://www.appcoda.com/git-source-control-in-xcode/> **1. Create your new Xcode project as usual, but make sure that you enable source control, see below:** If you didn't do this, then go here to see how to do it once the project is already created: <https://stackoverflow.com/a/17790306/4018041> [![Enable source control when creating your project.](https://i.stack.imgur.com/q2RMp.png)](https://i.stack.imgur.com/q2RMp.png) **2. From the top tool bar select Source Control->"current branch"->Configure "your project name", see below:** [![Configure the source control](https://i.stack.imgur.com/F2mV9.png)](https://i.stack.imgur.com/F2mV9.png) **3. Choose Remotes from the configure menu tab, hit the "+" sign and select "Add Remote", see below:** [![Add remote source](https://i.stack.imgur.com/dQt52.png)](https://i.stack.imgur.com/dQt52.png) **4. You will be prompted to enter the repository name and enter the address for the repository, see below:** Here you would use the instructions "trolley" provided here: <https://stackoverflow.com/a/9271409/4018041> ``` https://bitbucket.org/username/myrepo.git ``` In the above example, "myrepo" is the name of the repository at bitbucket.org; but locally you can assign any name you want, the default name being "origin" as you see in the picture below. [![Enter a repository name and address](https://i.stack.imgur.com/9jEsR.png)](https://i.stack.imgur.com/9jEsR.png) **5. Enter the username and password that you use to access your bitbucket.org account, see below:** Your user name is most likely the e-mail you used to register. [![Credentials for the repository](https://i.stack.imgur.com/yP3D6.png)](https://i.stack.imgur.com/yP3D6.png) **6. After pressing OK and if the credentials were accepted, then you should get a green check mark message. That is it!** After this you are able to Source Control->Push your local \*.git to your bitbucket.org repository, which is named locally as "origin" (default). [![Push local *.git repository to origin](https://i.stack.imgur.com/Rq5N4.png)](https://i.stack.imgur.com/Rq5N4.png) A similar text with a green check mark will appear upon successful push up to the bitbucket.org repository. **Note: Make sure you commit an initial change for the project in order for your local \*.git to get properly created.** Hope this helps someone. Cheers!
You have to add your generated SSH key to your account. I use GitHub, but BitBucket is basically a clone of it so the same procedures apply: ``` cat ~/.ssh/id_rsa.pub | pbcopy ``` Now try re-connecting.
38,235,645
This works, I know. ``` int8_t intArray7[][2] = {-2, -1, 0, 1, 2, 3, 4, 5, 6, 7}; int8_t intArray8[][2] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3}; int8_t intArray9[][2] = {100, 101, 102, 103}; int8_t (*arrayOf2DArrays[])[2] = {intArray7, intArray8, intArray9}; ``` Now, what if the 2D arrays are not all the same width? How do I make that work? Ex: this does NOT work, since intArray11 is width 3: ``` int8_t intArray10[][2] = {-2, -1, 0, 1, 2, 3, 4, 5, 6, 7}; int8_t intArray11[][3] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1}; int8_t intArray12[][2] = {100, 101, 102, 103}; int8_t (*arrayOf2DArrays2[])[] = {intArray10, intArray11, intArray12}; ``` What must one do to make an array of arrays of different element sizes? I plan on keeping track of each of the array sizes using separate variables.
2016/07/06
[ "https://Stackoverflow.com/questions/38235645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4561887/" ]
I believe the most compatible method is to use a `struct` (or `class`) to describe the array: ``` struct Array_Attributes { int8_t * array_memory; unsigned int maximum_rows; unsigned int maximum_columns; }; ``` You can treat the `array_memory` as a multidimensional array by converting from 2d to 1d indices: ``` unsigned index = row * maximum_columns + column; ``` You could also make an array out of linked lists. This would allow dimensions of different sizes. ``` +-------+ +----------+ +----------+ | row 0 | --> | column 0 | --> | column 1 | ... +-------+ +----------+ +----------+ | | V +-------+ +----------+ +----------+ | row 1 | --> | column 0 | --> | column 1 | ... +-------+ +----------+ +----------+ ```
Alright, I'd like to answer my own question too. There are many good ideas here, but let me post this simple and low-memory-cost solution. For devices of minimal memory (ex: an ATTiny AVR microcontroller with 512 bytes of RAM and a few kB program flash memory), I think this may be the best solution. I've tested it; it works. Use an array of pointers to int8\_t's--ie: an array of pointers to 1D arrays, as follows: ``` int8_t intArray10[][2] = {-2, -1, 0, 1, 2, 3, 4, 5, 6, 7}; int8_t intArray11[][3] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1}; int8_t intArray12[][2] = {100, 101, 102, 103}; //get some array specs we need about the arrays byte arrayLengths[] = {sizeof(intArray10)/sizeof(int8_t), sizeof(intArray11)/sizeof(int8_t), sizeof(intArray12)/sizeof(int8_t)}; //redundant division since int8_t is 1 byte, but I want to leave it for verboseness and extension to other types byte arrayCols[] = {2, 3, 2}; //make pointers to int8_t's and point each pointer to the first element of each 2D array, as though each 2D array was a 1D array //-this works because the arrays use contiguous memory int8_t *intArray10_p = &(intArray10[0][0]); int8_t *intArray11_p = &(intArray11[0][0]); int8_t *intArray12_p = &(intArray12[0][0]); //make an array of those pointers to 1D arrays int8_t *intArrayOfnDimArray[] = {intArray10_p, intArray11_p, intArray12_p}; //print the 3 arrays via pointers to (contiguous) 1D arrays: //-Note: this concept and technique should work with ANY contiguous array of ANY number of dimensions for (byte i=0; i<sizeof(intArrayOfnDimArray)/sizeof(intArrayOfnDimArray[0]); i++) //for each 2D array { for (byte j=0; j<arrayLengths[i]; j++) //for all elements of each 2D array { Serial.print(intArrayOfnDimArray[i][j]); Serial.print("/"); //now read out the 2D array values (which are contiguous in memory) one at a time; STANDARD ARRAY ACCESS TECHNIQUE Serial.print(*(intArrayOfnDimArray[i] + j)); Serial.print("/"); //ARRAY/POINTER TECHNIQUE (extra teaching moment) Serial.print((*(intArrayOfnDimArray + i))[j]); Serial.print("/"); //POINTER/ARRAY TECHNIQUE Serial.print(*(*(intArrayOfnDimArray + i) + j)); //POINTER/POINTER TECHNIQUE //add a comma after every element except the last one on each row, to present it in 2D array form static byte colCount = 0; //initialize as being on "Column 1" (0-indexed) if (colCount != arrayCols[i]-1) //if not on the last column number Serial.print(", "); else //colCount==arrayCols[i]-1 //if we *are* on the last column number Serial.println(); colCount++; if (colCount==arrayCols[i]) colCount = 0; //reset } Serial.println(F("-----")); //spacer } ``` Output: ``` -2/-2/-2/-2, -1/-1/-1/-1 0/0/0/0, 1/1/1/1 2/2/2/2, 3/3/3/3 4/4/4/4, 5/5/5/5 6/6/6/6, 7/7/7/7 ----- 10/10/10/10, 9/9/9/9, 8/8/8/8 7/7/7/7, 6/6/6/6, 5/5/5/5 4/4/4/4, 3/3/3/3, 2/2/2/2 1/1/1/1, 0/0/0/0, -1/-1/-1/-1 ----- 100/100/100/100, 101/101/101/101 102/102/102/102, 103/103/103/103 ----- ``` Note: as Thomas Matthews teaches in his answer, to access a specific 2D array, row, and column, use the following: ``` byte index = row * maximum_columns + column; ``` which in my above example would be: ``` byte rowColIndex = desiredRow * arrayCols[desired2DArrayIndex] + desiredColumn; int8_t val = intArrayOfnDimArray[desired2DArrayIndex][rowColIndex]; ``` Note: `byte` is equivalent to `uint8_t`.
21,690,763
I'm currently learning about coupling and dependencies in Java. I've been reading [this tutorial](http://tutorials.jenkov.com/ood/understanding-dependencies.html) and understand that if class1 contains an instance of class2 and if you call a method like `exampleMethod(c2)`, this counts as dependency between class1 and class2. However, I am unsure about the examples below. Can anyone give me some clarification? Assuming that we are inside class1 (which contains class2 `c2`): 1. If class1 calls a method defined in class2 (`c2.aMethod()` for example), does this count as a dependency/coupling between class1 and class2? 2. Does calling `c2.someSetterMethod(argument)` count as dependency/coupling between class1 and class2? 3. Does calling `c2.repaint()` within class1 count as a dependency?
2014/02/11
[ "https://Stackoverflow.com/questions/21690763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120842/" ]
The fact that class1 contains a reference to an instance of class2 suffices to say that class1 *depends* on class2. In all of your 3 examples you need a reference to class2 in order to call its methods. This only increases the need for dependency in your class1 but not the dependency itself. Please read <http://depfind.sourceforge.net/Manual.html#Dependencies> as mentioned in my answer to your previous question: <https://stackoverflow.com/a/21689495/1659599>.
1. Yes. 2. Yes. 3. Yes. One way to reduce coupling is to use interfaces. This way, class 1 only knows about the interface, and is not coupled with class 2 specifically. And in fact, any class that implements the interface could be used instead of class 2 and class 1 would still be satisfied.
50,408
This is my original image in a layer... on top of a pattern bg ![enter image description here](https://i.stack.imgur.com/2lo0K.png) as you can see, it has a white background. I would love for it to be transparent. When I change its blending mode to "Multiply" it becomes transparent as you can see in the image below ![enter image description here](https://i.stack.imgur.com/qsoui.png) This transparency is nearly perfect. I cannot reach even 10% of the quality of this white background stripping by any mean, magic eraser, color replacing etc. nothing works like this blending mode. How can I use the same "technique" to create a saved transparent PNG of my image? without any forced background? This is really my goal here. I'd like to strip it of its white background in the best way possible without working on every pixel for weeks... how do I apply the same "blending" technique that stripped the image of its white background in order to **save it** transparent?
2015/03/31
[ "https://graphicdesign.stackexchange.com/questions/50408", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/9841/" ]
There's no solid way to get the same appearance as the multiply blend mode. But **you can get exceptionally close** with very little effort. Just `Command/Ctrl`-click the thumbnail for the Blue Channel in the **Channel Panel**. (should then see marching ants) Highlight the layer in the **Layer Panel** and add a new mask. Invert the mask Use **Levels** or **Curves** to boost the contrast of the mask. ![enter image description here](https://i.stack.imgur.com/sbVou.gif) I find **Channels** are quite often one of the best and fastest way to create a mask, especially if the area being removed is consistent (like a white background).
In addition to Scott's answer, you could use the Blending Options for the layer. Just lowering blend if option: ![enter image description here](https://i.stack.imgur.com/qrFkT.png) Gave me a pretty good result: ![enter image description here](https://i.stack.imgur.com/qciWy.png)
169,011
If Yavin Prime was fired upon, the scattered debris would have destroyed Yavin 4 as well. **Why did they wait to make a direct shot?**
2017/09/06
[ "https://scifi.stackexchange.com/questions/169011", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/89189/" ]
This was addressed in an "[Ask the Jedi Council](https://web.archive.org/web/20030212050533/http://www.starwars.com/community/askjc/steve/askjc20010405.html)" feature on the StarWars.com website. According to LucasFilm's (former) Head of Fan Relations/Director of Content Management [Steve Sansweet](http://www.starwars.com/news/contributor/ssansweet), **the Death Star was simply not powerful enough to destroy a gas giant.** > > **Q. In Star Wars, why does the Death Star go around the planet Yavin to blow up the fourth moon when it can simply blow up Yavin first (as > it did Alderaan) and then the fourth moon without wasting any time?** > > > **A.** *The Death Star's superlaser is very powerful, but it's not all powerful. Relatively speaking, a terrestrial world of rock and metal > like Alderaan is easier to blow up than an immense gas giant like > Yavin. **The Death Star simply couldn't blow up Yavin**, and had to circle > the gas giant in order to get to the much smaller moon Yavin 4.* > > > [Starwars.com - Ask the Jedi Council](https://web.archive.org/web/20030212050533/http://www.starwars.com/community/askjc/steve/askjc20010405.html) > > >
The Empire was particularly proud of the Death Star and they were power-blinded. They want to see rebels die quickly in one shot. Destroying Yavin would have taken time to destroy Yavin 4. Plus, the Death Star was near to Yavin and destroying this planet would have caused debris fly to Death Star and damage it. The Death Star didn't have defense shield then. Therefore, it wasn't wise to destroy Yavin. However, this is just speculation. Plus, if they have destroyed Yavin, you couldn't see the planning of attack and the final battle around Death Star and the movie would have been 30 minutes shorter, wouldn't it? ;-)
8,898,298
Is there a way in wordpress that I can create custom page templates for a mobile version, I mean something like when it detects that is a mobile to load `mobile_header.php` or is there a better way, I can't do this only from css I also need to use some custom page templates. Thanks!
2012/01/17
[ "https://Stackoverflow.com/questions/8898298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58839/" ]
What you could do is create a new theme which is a mobile template specifically. You can then put this code into your functions.php file and it will use the mobile template instead. ``` add_filter('option_template', 'mobileTheme'); add_filter('template', 'mobileTheme'); add_filter('option_template', 'mobileTheme'); add_filter('option_stylesheet', 'mobileTheme'); function mobileTheme($theme) { global $mobile; if($mobile) $theme = 'mobile_theme'; return $theme; } ``` You'd have to work out if it is a mobile phone useragent or not though.
How about WPTouch? It is a WP plugin.
25,475,230
So far I have this: ``` ls /usr/bin | grep "^[\.]" ``` The cmd still gets files with a "." in there. I have looked at [[:punct:]] but still returns the same thing.
2014/08/24
[ "https://Stackoverflow.com/questions/25475230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973363/" ]
You can change your regex to exclude files starting with ".": ``` ls -a /usr/bin | grep "^[^.]" ``` This regex selects only files which do not have "." at the start. By the way only `ls -a` shows files that starts with ".". How did you manage to get them without "-a" ?
I think you are referring to the current working directory and parent dirctory and not a command with "a dot" in it. Try this as you probably have ls aliased: /bin/ls /usr/bin
28,051,743
I am using **browserify** so I can use npm modules in my front end code, and **gulp** to do my build tasks. This works fine: ``` var browserify = require('gulp-browserify'); gulp.task('js', ['clean'], function() { gulp .src('./public/js/src/index.js') .pipe(browserify({ insertGlobals : true, debug : ! gulp.env.production })) .pipe(gulp.dest('./public/js/dist')) }); ``` However if there's a syntax error in my JS, I'd like to be notified of the error via an OS X notification. I've seen this [similar question](https://stackoverflow.com/questions/23161387/catching-browserify-parse-error-standalone-option) and modified my code to add an `.on('error'...)` after the `.browserify()`: ``` // Browserify/bundle the JS. gulp .src('./public/js/src/index.js') .pipe(browserify({ insertGlobals : true, debug : ! gulp.env.production }).on('error', function(err){ notify.onError({ message: "Error: <%= error.message %>", title: "Failed running browserify" } this.emit('end'); }) .pipe(gulp.dest('./public/js/dist')) ``` However this doesn't notify when my JS is broken. Adding a console.log() inside `on('error',...)` doesn't log either. I suspect because that question doesn't involve using gulp piping. **How can I get notified of errors during when piping to gulp browserify?**
2015/01/20
[ "https://Stackoverflow.com/questions/28051743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123671/" ]
Use **gulp-notify**. Note also you should use the [browserify](https://github.com/substack/node-browserify) module instead of the deprecated [gulp-browerify](https://github.com/deepak1556/gulp-browserify) module. ``` var browserify = require('browserify'), brfs = require('brfs'), watchify = require('watchify'), notify = require("gulp-notify"); var bundler = watchify(browserify({ basedir: "./public/js/src" })); // Browserify our code gulp.task('js', ['clean'], function() { // Browserify/bundle the JS. return bundler.bundle() // log errors if they happen .on('error', function(err) { return notify().write(err); }) .pipe(source('index.js')) .pipe(gulp.dest('public/js/dist')); }); ``` [Here](https://github.com/gulpjs/gulp/blob/master/docs/recipes/browserify-uglify-sourcemap.md) example how to use `browserify` util in `gulp` task. [Here](https://github.com/greypants/gulp-starter/blob/master/gulp/tasks/browserify.js) another example how to use `browserify` and show notification, when js has syntax errors.
In my gulpfile, I just listen for uncaught exceptions and notify using [node-notifier](https://npmjs.org/package/node-notifier): ``` var Notifier = require('node-notifier'); notifier = new Notifier(); process.on('uncaughtException', function(err) { notifier.notify({title: 'error', message: 'gulp process has crashed'}); setTimeout(function() { console.error(err); process.exit(1); }, 1000); }); ``` I found that a `setTimeout` delay was necessary for the notification to show up before exiting the process.
10,015,708
I'm new to exceptions and am trying to figure out when is appropriate to use them. In the following php code I would like to change `echo` (no need to tell the user) to simply log the message. Should I just replace `echo` with `log->notice(...)` (for example) or should I be using an exception (which I plan to log anyway). ``` if (file_exists($file)) { echo 'File already exists and will be overwritten.'; } ``` Also, If I should be using an exception, then how would I use one properly in this scenario?
2012/04/04
[ "https://Stackoverflow.com/questions/10015708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1024808/" ]
You could try calling `accordion()` again after setting the html in your ajax success handler. This should re-apply the styles: ``` $("#accordion").accordion(); ```
There might be several causes for this. Here is one possible cause: If you use JavaScript for styling(adding CSS class etc.) your accordion menu, and that usually run on page load. Then call the styling function again after setting the loaded content in your success callback.
11,635,059
I have been working on an app for a number of months now and a strange bug has appeared in the last week or two. After extended use of the application (20-30 minutes), many of our custom labels (based on UILabel) cease to render correctly (some will just appear blank). Interestingly, bringing up the keyboard in this situation shows the following: ![enter image description here](https://i.stack.imgur.com/AuLgX.jpg) I've tried a number of tweaks over the last couple of weeks to various parts of the codebase with no avail and I was hoping that someone here might have stumbled across a similar problem before and/or might have some ideas of where to look for a solution. We are using lots of CoreGraphics calls within our custom labels to render some pretty complicated annotated strings and have a fair amount of traffic going back and forth to a server in the background on another thread. With regards to memory, we are using ARC and while we're keeping about 5-10Mb of raw data in memory at any one time - I can't imagine that anything else is chewing up loads of memory. Any advice on where to look would be greatly appreciated.
2012/07/24
[ "https://Stackoverflow.com/questions/11635059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445153/" ]
After first time the inner loop is finished, the inner iterator over file2 reached the end so the solution is to point inner iterator of file2 to file's beginning each time, for example: ``` while f < 50: for line in file1: file2.seek(0, 0) for name in file2: if name == line: print 'match!' ```
Depending on the size of the files, you can use the `readlines()` function to read the lines of each file into a list. Then, iterate over these lists. This will ensure that you do not have problems with the current position of the file position.
27,298,426
i'm stuck at this very basic form, that i could not accomplish, which i want to build a search form with an text input, and two select controls, with a route that accept 3 parameters, the problem that when the i submit the form, it map the parameters with the question mark, not the Laravel way, Markup ------ ``` {{ Form::open(['route' => 'search', 'method' => 'GET'])}} <input type="text" name="term"/> <select name="category" id=""> <option value="auto">Auto</option> <option value="moto">Moto</option> </select> {{ Form::submit('Send') }} {{ Form::close() }} ``` Route ----- ``` Route::get('/search/{category}/{term}', ['as' => 'search', 'uses' => 'SearchController@search']); ``` When i submit the form it redirect me to ``` search/%7Bcategory%7D/%7Bterm%7D?term=asdasd&category=auto ``` How can i pass these paramters to my route with the Laravel way, and without Javascript ! :D
2014/12/04
[ "https://Stackoverflow.com/questions/27298426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2100974/" ]
The simplest way is just to accept the incoming request, and pull out the variables you want in the Controller: ``` Route::get('search', ['as' => 'search', 'uses' => 'SearchController@search']); ``` and then in `SearchController@search`: ``` class SearchController extends BaseController { public function search() { $category = Input::get('category', 'default category'); $term = Input::get('term', false); // do things with them... } } ``` Usefully, you can [set defaults in `Input::get()`](http://laravel.com/docs/4.2/requests#basic-input) in case nothing is passed to your Controller's action. [As joe\_archer says](https://stackoverflow.com/a/27298740/658210), it's not necessary to put these terms into the URL, and it might be better as a POST (in which case you should update your call to `Form::open()` and also your search route in routes.php - `Input::get()` remains the same)
I was struggling with this too and finally got it to work. routes.php ``` Route::get('people', 'PeopleController@index'); Route::get('people/{lastName}', 'PeopleController@show'); Route::get('people/{lastName}/{firstName}', 'PeopleController@show'); Route::post('people', 'PeopleController@processForm'); ``` PeopleController.php ``` namespace App\Http\Controllers ; use DB ; use Illuminate\Http\Request ; use App\Http\Requests ; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Redirect; public function processForm() { $lastName = Input::get('lastName') ; $firstName = Input::get('firstName') ; return Redirect::to('people/'.$lastName.'/'.$firstName) ; } public function show($lastName,$firstName) { $qry = 'SELECT * FROM tableFoo WHERE LastName LIKE "'.$lastName.'" AND GivenNames LIKE "'.$firstName.'%" ' ; $ppl = DB::select($qry); return view('people.show', ['ppl' => $ppl] ) ; } ``` people/show.blade.php ``` <form method="post" action="/people"> <input type="text" name="firstName" placeholder="First name"> <input type="text" name="lastName" placeholder="Last name"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <input type="submit" value="Search"> </form> ``` Notes: I needed to pass two input fields into the URI. I'm not using Eloquent yet, if you are, adjust the database logic accordingly. And I'm not done securing the user entered data, so chill. Pay attention to the "\_token" hidden form field and all the "use" includes, they are needed. PS: Here's another syntax that seems to work, and does not need the ``` use Illuminate\Support\Facades\Input; ``` . ``` public function processForm(Request $request) { $lastName = addslashes($request->lastName) ; $firstName = addslashes($request->firstName) ; //add more logic to validate and secure user entered data before turning it loose in a query return Redirect::to('people/'.$lastName.'/'.$firstName) ; } ```
14,076,179
In C I use `"1st line 1\n2nd line"` for a newline, but what about VB? I know `"1st line" & VbCrLf & "2nd line"` but its too verbose, what is the escape char for a newline in VB? I want to print ``` 1st line 2nd line ``` I tried using `\n` but it always outputs this no matter how many times I run the compiler ``` 1st line\n2nd line ``` Any ideas?
2012/12/28
[ "https://Stackoverflow.com/questions/14076179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You should use `Environment.NewLine`. That evaluates to CR+LF on Windows, and LF on Unix systems. There are no escape sequences for CR or LF characters in VB. And that's why `"\n"` is treated literally. So, `Environment.NewLine` is your guy.
If you're looking for an inline escape to accomplish something like including line breaks in a String.Format you can include a pipe or something similar and then replace it at the end of your string. > > String.Format("Batch: {0} | ProductNumber: {1} | Formula: {2}", dr.Item("BatchNumber"), dr.Item("PartNum"), dr.Item("Formula")).Replace("|", Environment.NewLine) > > >
9,010,693
I'm going nuts trying to figure out why I'm having such a difficult time getting WordPress to only show posts newer than 30-days and I could really use a second set of eyes. I'm using the following code but nothing is showing up on my site. ``` <?php // Create a new filtering function that will add our where clause to the query function filter_where( $where = '' ) { // posts in the last 30 days $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; return $where; } add_filter( 'posts_where', 'filter_where' ); $the_query = new WP_Query( $query_string ); remove_filter( 'posts_where', 'filter_where' ); ?> <?php if ($the_query->have_posts()) : ?> <?php while ($the_query->have_posts()) : $the_query->the_post(); ?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> <h2 class="title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="meta"> <span class="date"> <strong><?php the_time('d'); ?></strong> <strong><?php the_time('M'); ?></strong> </span> </div> <div class="entry"> <?php if ( function_exists( 'get_the_image' ) ) { get_the_image( array( 'custom_key' => array( 'post_thumbnail' ), 'default_size' => 'full', 'image_class' => 'alignleft', 'width' => '170', 'height' => '155' ) ); } ?> <?php the_content('Read More'); ?> </div> </div> <?php endwhile; ?> <div class="navigation"> <?php include('includes/wp-pagenavi.php'); if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?> </div> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center">Sorry, but you are looking for something that isn't here.</p> <?php get_search_form(); ?> <?php endif; ?> ```
2012/01/25
[ "https://Stackoverflow.com/questions/9010693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965879/" ]
The way you're doing looks fine. Try putting `posts_per_page => -1` as the argument. The following works for me: ``` function filter_where( $where = '' ) { $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; return $where; } add_filter( 'posts_where', 'filter_where' ); $args = array( 'posts_per_page' => -1, ); $the_query = new WP_Query($args); remove_filter( 'posts_where', 'filter_where' ); while ($the_query->have_posts()) { $the_query->the_post(); // do stuff } ``` Hope it helps.
I know this is super old but, you can do this with WP\_Query now. ``` $args = array( 'post_type' => 'post', // or whatever post type you want 'posts_per_page' => -1, // get all posts that apply, i.e. no limit 'date_query' => array( array( 'after' => '-30 days', 'column' => 'post_date', ), ), ); ```
94,755
> > 笑顔が無邪気でかわいい子 > > > Hi. Does this clause here mean a child with an innocent and cute smile or a cute child with an innocent smile? Thank you
2022/05/29
[ "https://japanese.stackexchange.com/questions/94755", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/48269/" ]
This is ambiguous and can be taken both ways. I personally feel "a child with an innocent and cute smile" is slightly more likely because you can say 笑顔が無邪気**な**かわいい子 to unambiguously mean "a cute child with an innocent smile".
無邪気 can be an adjective or noun. Particle で in position after a noun indicates an uncontrollable reason. In this case, this sentence means "a child is cute because of an innocent smile" and you can replace "で" with "から".
31,270
Do day trips (e.g. gone from home from 9am to 4 pm) qualify for the traveling exemption from the sukkah?
2013/09/23
[ "https://judaism.stackexchange.com/questions/31270", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/955/" ]
[YU Torah online](http://www.yutorah.org/lectures/lecture.cfm/723700/Flug,_Rabbi_Josh#) has a good summary. The subject is disputed by the Vilna Gaon and Rabbeinu Tam. The first allows only up till sunset; the second up to when the stars appear. > > Mishna Berurah 233:14, limits the leniency to recite Mincha until > tzeit hakochavim. He cites the opinion of P'ri Megadim, Eshel Avraham > 233:7, who rules that one cannot actually recite Mincha until tzeit > hakochavim, but rather until Rabbeinu Tam's shekiat hachama which is a > few minutes before tzeit hakochavim. [R. Ovadia Yosef, Yechaveh Da'at > 5:22, cites numerous Acharonim who disagree with P'ri Megadim and > maintain that according to Rabbeinu Tam, one may recite Mincha until > tzeit hakochavim.] Mishna Berurah then notes that even those who > normally follow the opinion of Rabbeinu Tam should nevertheless show > deference to the opinion of the Vilna Gaon and recite Mincha before > astronomical sunset. > > > Nevertheless, Mishna Berurah, Sha'ar HaTziun 233:21, rules that even > according to the Vilna Gaon, there is room for leniency in a pressing > situation. R. Ovadia Yosef, op. cit., notes that although the Vilna > Gaon himself does not allow one to recite Mincha after shekiat > hachama, one can argue that within the opinion that shekiat hachama > occurs at astronomical sunset (i.e. the Vilna Gaon's opinion) one can > still maintain that latest time for Mincha is at tzeit hakochavim. > According to R. Ovadia Yosef, the question of whether evening (for the > purpose of Mncha) begins at shekiat hachama or tzeit hakochavim is not > necessarily connected to the question of whether one follows Rabbeinu > Tam or the Vilna Gaon. > > >
In the mishna in Berachos 26a, the tana'im dispute until when one can daven mincha. R' Yehuda says until plag hamincha (the second half of the time of mincha ketana, which goes from 9 1/2 hours of the day till twelve), the Chachamim say until the evening. The gemara (26b-27a) proves that 'until plag hamincha' cannot mean until the end of plag hamincha (twelve hours), as then there would be no dispute between R' Yehuda and the Chachamim (as they also hold that one has until the evening, ie the end of twelve hours of the day). Thus it is clear that according to the most leninent opinion (the Chachamim), the time after which one cannot daven mincha is also the time that the hours of the day end. It is well known that the Magen Avraham and the Gra argue about this, the M"A holds that the day goes from Alos HaShachar until Tzeis HaKochavim, whereas the Gra (and the Levush) holds that it is from sunrise till sunset (in truth this is debated by the rishonim as well). It should also be pointed out that the view of the M"A is based on the position of Rabeinu Tam, that halachic sunset is 54 minutes after the viewed sunset (the Levush argues that even according to Rabeinu Tam the day goes from viewed sunrise to viewed sunset, but without Rabeinu Tam the view of the M"A cannot start). The Levush also points out that those who held that the day goes from alos hashachar till tzeis mistakenly believed that at the equinox, day and night would each be twelve hours according to this. Thus reality proves that in fact day starts at viewed sunrise and ends at viewed sunset. All those who allow davening mincha after shekia take the view of Rabbeinu Tam into account. Thus for most of us, who do not take Rabbeinu Tam into account even at the end of Shabbos, there is no justification for davening mincha after the viewed sunset. See Responsa Bemareh HaBazak, part 8 (<http://eretzhemdah.org/Data/UploadedFiles/SitePages_File/123-sFileEn.pdf>), siman 1.
921,276
This question looks pretty easy and hard at the same time. Here's how it goes: **Let A and B be symmmetric nxn matrices. Show that A + B is also symmetric.** To me this sounds like a pretty obvious fact, well, if its not obvious I still have a good idea of why this is true, but I'm new to university level maths and I don't really know how I would go about writing a formal proof for this. Any help would be much appreciated. =D
2014/09/06
[ "https://math.stackexchange.com/questions/921276", "https://math.stackexchange.com", "https://math.stackexchange.com/users/173101/" ]
This is how I would write a proof of this statement: Let $A=(a\_{ij})\_{i,j=1}^n$,$B=(b\_{ij})\_{i,j=1}^n$ be symmetric matrices, then it holds that $a\_{ij}=a\_{ji}$ and correspondingly for $B$. Then consider the sum $C=A+B$, then $c\_{ij}=a\_{ij}+b\_{ij}$, and $c\_{ji}=a\_{ji}+b\_{ji}$. Then since $A$, $B$ are both symmetric $a\_{ji}+b\_{ji}=a\_{ij}+b\_{ij}$ and thus $c\_{ji}=c\_{ij}$ and therefore $C$ must be symmetric.
I found this here: <http://mymathforum.com/linear-algebra/8319-if-b-symmetric-show-b-also-symmetric.html> a) Since (A+B)^T = A^T + B^T, A = A^T and B = B^T, and you have that (A+B)^T = (A+B) That is, A + B is symmetric. I thought of doing it by writing down the matrices out in full but I thought that would be messy. This looks like a good answer. Thanks for replies tho!!
6,696,063
If I `SELECT` IDs then `UPDATE` using those IDs, then the `UPDATE` query is faster than if I would `UPDATE` using the conditions in the `SELECT`. To illustrate: ``` SELECT id FROM table WHERE a IS NULL LIMIT 10; -- 0.00 sec UPDATE table SET field = value WHERE id IN (...); -- 0.01 sec ``` The above is about 100 times faster than an `UPDATE` with the same conditions: ``` UPDATE table SET field = value WHERE a IS NULL LIMIT 10; -- 0.91 sec ``` Why? Note: the `a` column *is* indexed.
2011/07/14
[ "https://Stackoverflow.com/questions/6696063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/732284/" ]
The two queries are not identical. You only know that the IDs are unique in the table. UPDATE ... LIMIT 10 will update at most 10 records. UPDATE ... WHERE id IN (SELECT ... LIMIT 10) may update more than 10 records if there are duplicate ids.
The comment by Michael J.V is the best description. This answer assumes `a` is a column that is not indexed and 'id' is. The WHERE clause in the first UPDATE command is working off the primary key of the table, `id` The WHERE clause in the second UPDATE command is working off a non-indexed column. This makes the finding of the columns to be updated significantly slower. Never underestimate the power of indexes. A table will perform better if the indexes are used correctly than a table a tenth the size with no indexing.