INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
insert an array element in an std::map I don't understand why this code works: std::map<int,char> map2; map2.insert (std::pair<int,char>(3,'a')); But this doesn't: std::map<int,double[2]> map1; map1.insert (std::pair<int,double[2]>(100,{0,0}));
The answer you are loooking for is here: Using array as map value: can't see the error Where the last answer explains it as arrays are not assignable or copy constructible, therefore cannot be mapped to. As an alternative, you can use pointer arrays or vectors.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c++, stdmap" }
Tagged bucket not showing in AWS billing report I'm trying to determine my AWS costs per bucket. My bucket has a tag, as see on the bucket properties: !Bucket Properties However, in the Cost Explorer, I am unable to see any tags. !Cost Explorer Am I doing this right? Where can I find info on how much that bucket is costing me? I should also note that other services I'm using are tagged, and those don't appear in the Cost Explorer either. I am an admin on the account, so it shouldn't be an issue of permissions.
This is the page it should have linked you to. You have to specify tags under preferences. <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "amazon web services, amazon s3" }
Using PHP in a JavaScript Function in HTML So I declared a variable empty in external JavaScript file which I am sourcing in my main HTML page and because I want to load that variable from PHP I am doing this but it doesn't seem to work. <script src="./assets/js/script.js"></script> <script type="text/javascript">var APIKey = <?php echo $API; ?></script> script.js is the one having empty global variable like this: var APIKey = ""; I have already declared $API in PHP and I know it's working because I tried echoing it as text and it works but for some reason it doesn't in script. Please help. Thanks!
So it took a bit time to figure out but the mistake was pretty simple. All I had to do was **REMOVE** this from script.js var APIKey = ""; The problem was that I was defining it 2 times and I don't think that's supported for some reason but that worked for me so if anyone else has the same issue, it'll work for you as well. Have a good day and keep on coding.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, php, html" }
Cannot read property 'firstname' of undefined in view engine node js I am trying to display json data on a website using view engine (ejs) but I am facing following error `Cannot read property 'firstname' of undefined` this is my program **node.js** io.readEmp().then(function(data){ res.render('Dashboard',{data:data}); }).catch(function(err){console.log(err.message);}); **index.ejs** <ul class="list-group list-group-flush"> <% for(var key in data){%> <li class="list-group-item"><%= data.key.firstname %></li><%}%> </ul> **jsonfile** { "id01":{"firstname":"abc","lastname":"xy"}, "id02":{"firstname":"pqr","lastname":"xy"} } **error** Cannot read property 'firstname' of undefined
If you have data as an object like you display then 'key' will be the item key and you need to use the key access notation for an object thusly: <ul class="list-group list-group-flush"> <% for(var key in data){%> <li class="list-group-item"><%= data[key].firstname %></li><%}%> </ul> 'key' for the first item will be "id01", so this is equivalent (on the first pass) for saying `data.id01.firstname`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js, json, ejs, viewengine" }
Too many views in Xcode; alternative? I'm an Xcode noob. I have created a view-based project, whose model is this. As you can see from it, I'd have to create lots and lots of view, which is very inconvenient. Is there another way to do that? Thank you.
A solution would be to make a dynamic view. You just create a few view controllers and through a storyboard segue you pass the value and you change the UITableView data accordingly. Here is a good tutorial about storyboard segues: < Basically, when you select a row in you tableview you can pass a value to the pushed view controller so you can change the new content:
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xcode, view" }
How can I terminate user input without using zero? Basically I'm trying to make an method that would return an array so that I can use this list later down the line, only problem is I cant find a way to terminate user input other than using 0. I've tried to take in user input using a string then parsing it into an int but that only results in an error when a non-number character is used. public static double[] input() { double[] arr = new double[100]; //int count = 1; for(int i = 0; i < arr.length; i++) { System.out.print("Insert a number or Zero to stop: "); double input = scan.nextDouble(); arr[i] = input; if(input == 0) { break; } count++; } return arr; }
I think that instead of the condition `for(int i = 0; i < arr.length; i++)` you could simply ask the user how many digits he/she wishes to enter and then pass that value to the for loop to execute lie `for(int i = 0; i < length; i++)` where length is the user desired size of array. If you do not want to ask the user then do this accept the numbers as single characters instead of a string then before parsing it into int just check if the entered character is an escape sequence(\n or \r) `arr[index]='\n' or'\r'` then you can terminate the input process. Note: this process is only for integer input if the user enters a character it accepts it just make sure that the entered character is a number. I suggest you put the print statement out of the for loop as it will be repeated as long as the for loop runs, it is not nice to have those instructions displayed again and again.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, arrays" }
How to protect firebase Cloud Function HTTP endpoint to allow only Firebase authenticated users? With the new firebase cloud function I've decided to move some of my HTTP endpoint to firebase. Everything works great... But i have the following issue. I have two endpoints build by HTTP Triggers (Cloud Functions) 1. An API endpoint to create users and returns the custom Token generated by Firebase Admin SDK. 2. An API endpoint to fetch certain user details. While the first endpoint is fine, but for my second end point i would want to protect it for authenticated users only. meaning someone who has the token i generated earlier. How do i go about solving this? I know we can get the Header parameters in the cloud function using request.get('x-myheader') but is there a way to protect the endpoint just like protecting the real time data base?
There is an official code sample for what you're trying to do. What it illustrates is how to set up your HTTPS function to require an Authorization header with the token that the client received during authentication. The function uses the firebase-admin library to verify the token. Also, you can use "callable functions" to make a lot of this boilerplate easier, if your app is able to use Firebase client libraries.
stackexchange-stackoverflow
{ "answer_score": 206, "question_score": 213, "tags": "firebase, firebase realtime database, firebase authentication, firebase security, google cloud functions" }
SUM of multiple VLOOKUP It seems like a simple problem, but I do not manage to solve it. I have the following tables: ### Values | Key | Value | |-----|-------| | A | 1 | | B | 2 | | C | 3 | ### Results | Foo | Bar | |-----|-----| | A | B | | C | B | | A | A | | B | C | | ... | ... | What I am looking for is a final row in the `Results` table that looks for the `key` in the `Values` table, takes its `value` and sums all the `keys` in a column (i.e. `FOO` and `BAR`). The final result would be: | Foo | Bar | |-----|-----| | A | B | | C | B | | A | A | | B | C | |-----|-----| | 7 | 8 | I have been trying with different VLOOKUP, INDEX and MATCH functions, but still I am not able. Any ideas?
I asume you want a solution **without** extra columns. Then you are into Array formulas (a.k.a CSE or ControlShiftEnter functions). Combination of `{=SUM(VLOOKUP(...))}` doesn't work, but combination of `{=SUM(SUMIF(...))}` does: in A12 enter `=SUM(SUMIF($A$1:$A$3;A7:A10;$B$1:$B$3))` and save with `Ctrl`+`Shift`+`Enter`. You then can copy this to B12. !enter image description here Problem is you will need to change the Array function every time you add values to the list A7:B10 (or you initially make the range sufficiently large) ... this would speak more for extra =VLOOKUP() columns as suggested by CustomX.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "excel, excel formula, key, vlookup" }
How would I prepend 127.0.0.1 as a nameserver all the time I do web development and I would like to have dnsmasq running and handing my local dns requests. However I work in a lot of different networking scenarios and I need to DHCP updating my networking information multiple times a day. I already have dnsmasq running and I can have my laptop always use it by setting the DNS name server. It's not too bad, this way, I can use the location management (in the network preference pane) and just switch location between 'Automatic' and 'Automatic (dnsmasq)' when I need to, however what I really want it something linux has. In linux I can configure my dhcp client to prepend a name server to whatever I get from dhcp. On ubuntu I do this by editing `/etc/dhcp3/dhclient.conf` and setting. prepend domain-name-servers 127.0.0.1; Is there an equivalent in OS X (10.8 Mountian Lion). Thanks
As you already know, OS X will overwrite any changes you make to `/etc/resolv.conf` so you can't really specify your own nameserver in there. Luckily, there is a way to add your own resolver entries in a way that will persist whatever network connection you use whilst still using DHCP assigned name servers for most normal lookups. Create the directory `/etc/resolver` and create a text file within it that simply has a standard name server directive like `nameserver 127.0.0.1`. Make sure this text file is named the same as the domain or TLD you wish to use dnsmasq for. In my case, all my development sites end with the .dev TLD so my config file is named `/etc/resolver/dev`. And that's it! From now on, when ever you connect to a network using DHCP, your name servers will be automatically assigned and used as normal but any requests for your specified TLD (*.dev in my example) will be routed to dnsmasq.
stackexchange-apple
{ "answer_score": 1, "question_score": 4, "tags": "snow leopard, network, dns" }
How to customize the top-left text label on the background windows of Inno Setup By default, Inno Setup use the `AppName` as text source for the top-left text label displayed in the fullscreen background when we use `WindowVisible`. I would like also to print the `Publisher` and the `Version`. I found many help topics to put an image as background but nothing to change the displayed text. Is there a way to do it, without modifying the `[Setup] AppName` parameter? #define MyAppName "MyAppName" #define MyAppVer "4.1" [Setup] AppName={#MyAppName} AppVersion={#MyAppVer} AppVerName={#MyAppName} {#MyAppVer} WindowVisible=True ![Screenshot of Innosetup with WindowVisible](
It does not seem to be possible. There's no "label" control for the application name text. The name is drawn on the window directly. Maybe you can obscure the built-in label behind some panel and put your own label on top of it. * * * Though, why are you even using `WindowVisible`? It's pretty old-school and against Microsoft UI guidelines. You better abandon that.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "inno setup" }
Is there a way to have python start a the match statement when a string is found so that loop doesn't start from the beginning? File includes: Honda color white trim black Chevy color blue trim chrome Hyundai color red trim black Let's say I have hypothetical data from above. I'm trying to create a loop so that when Hyundai is found I get color red. The problem I'm having is when Hyundai is found the loop starts again from the beginning and I get white. for line in data: if Hyundai in line: for line in data: if 'color' in line: color = get_color(line) print (color) Hope this makes sense.
Put it in a function and return: def getCarColor(car, data): car_found = False for line in data: if car in line: car_found = True if 'color' in line and car_found: return get_color(line) return None print(getCarColor("Hyundai", data))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x" }
How to determine (in MaxScript) which line's spline is the "outer one"? I would like to list the vertices of line, grouped by spline to file. I know I can output data to file with `format % ... to: file`, but I have to do one more thing. My line looks like this (the outer spline is selected/red and the hole is white): ![enter image description here]( I want to output the **outer spline first** (the order is important to me), and then list all the holes (as vertices' lists). **How to determine (in MaxScript) which line's spline is the "outer one"?**
A simple (but probably not the most effective) way would be to do a length comparrison between the two (since the inner will probably always be shortest). You use the following method: getSegLengths <splineShape> <spline_index> [cum:<boolean>] / [byVertex:<boolean>] [numArcSteps:<integer>] You could do something like: if ((getSegLengths $YourSpline 2 cum:true) > (getSegLengths $YourSpline 1 cum:true) then (setFirstSpline $YourSpline 2) You will of course need to iterate over alle the sub splines of the splineshape, to identify the longest. Alternatively, you can calculate some vounding box around them, in case your inner spline is curled up, and thus are longer than the outer.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "maxscript" }
"Reveal in Finder" functionality for Windows Explorer? How to preselect a file or directory in the Windows Explorer? What command line switches do I need? How to find out what command line switches the Explorer supports (`explorer /?` does not show something)?
explorer /path/to/dir opens an explorer window in that directory, or if it's a file, opens it with the default application. There are some explorer commandline options. **edit:** explorer /select,/path/to/something will open explorer window in _/path/to_ with _something_ selected
stackexchange-superuser
{ "answer_score": 5, "question_score": 2, "tags": "windows explorer" }
Replace a second field output with sed or awk I have a below content in a file where i need to search the pattern "application:" , where "application:" should be there but the next field to it should be changed to "RMAN" , I am trying to do with sed but unable to get it in one go.. any help appreciated $ cat myjobs update_job: P_rman_INC1_HCMS2 job_type: CMD group: DBA application: RMAN update_job: P_rman_INC1_HCMPRTL job_type: CMD group: DBA application: Mybox
Assuming the example input you gave: sed -e 's/application:.*/application: RMAN/g' filename
stackexchange-unix
{ "answer_score": 0, "question_score": 0, "tags": "shell script" }
Start>Run doesn't launch desired exe despite PATH On Windows 10 I use the old (WinXP) pbrush.exe instead of the new "ribbon UI" version (never mind why; that is not the question). I had to obtain the old exe from an XP image and keep it in a separate folder, since if I replace the primary version then it periodically gets reverted by Windows File Protection. I want the command "pbrush" to launch my XP version and not the Win10 version. So I tried adding the extra folder to my PATH system variable. That works from a command prompt, but for some reason it doesn't work from the Start>Run box (the one that appears when you press WinKey+R); that Run box still launches the Win10 pbrush. Why is that, and how can I fix it?
You can directly put a shortcut (`.lnk` file) to your executable under: `%APPDATA%\Microsoft\Windows\Start Menu`. That should be enough, however, it may be that it cannot overwrite default names, so you would have to change "Paintbrush" to something else like "PaintbrushXP".
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "windows 10, path, start menu" }
wordpress queries in mytheme/update.php In my wordpress theme, I created a file called update.php. I can access this URL by < Here is the code inside update.php global $wpdb; // do some more stuff here $wpdb->update( 'twitter_followers', array('count' => $followers), array('id' => '1') ); echo 'done'; When I go to this page I get this error. PHP Fatal error: Call to a member function update() on a non-object in /var/www/vhosts/mydomain.com/subdomains/mytheme/httpdocs/wp-content/themes/mytheme/update.php on line 34 Any ideas on how I can fix this? Also note, I did created twitter_followers table in my database.
The issue is that you don't have $wpdb yet, since your update.php is not part of wordpress. When you go to update.php wordpress is never loaded, so you get the non-object error. Try adding this line to the top of your update.php file, obviously changing the path: require_once("/path/to/wordpress/wp-load.php"); the path will probably look something like this in a normal installation: require_once("../../../../wp-load.php");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, mysql, database, wordpress" }
Ignore the last object in array in PHP I have this little code here : $arrayName = array('0','1','2'); foreach ($arrayName as $key) { echo $key . ','; } So now the Output is this : > > 0,1,2, If i want to have this what should i do ? : > > 0,1,2 I mean not inserting "," for last object in an array . thanks .
You can either use join or implode echo join(',', $arrayName); OR echo implode(',', $arrayName);
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "php" }
install python pymssql package without pip / proxy I have a python script that leverages pymssql and currently this is running on my DEV Server. I need to deploy this to PRO however and I do not want to setup a proxy on my linux server. it has Python 2.7 installed but no pip. Can i somehow take the pymssql package from the current working dev env and tar it up, move it across to the PRO server.
Download a wheel for your platform, rename it to `*.zip`, extract the zip, transfer to the server files `_mssql.so` and `pymssql.so`, move these files to `site-packages` directory in Python.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, pip, tar, offline, pymssql" }
How to combine two tables/view objects into one in JDeveloper? I have the following tables/view objects: **StudentRequest** **StudentApprovedRequests** I want to add a new **StudentRequestHistory** View object that simply combines both of these tables by displaying both of their content in one. This table is simply for visual/front end purposes, its does not exist in the database. What I want is this: StudentRequest View Object StudentApprovedRequests View Object StudentRequestHistory View Object Really hope someone can help. Thank you!
Define a VO based on a SQL query that uses the Union: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "oracle, oracle adf, jdeveloper" }
PyYAML variables in multiline I'm trying to get a multi-line comment to use variables in PyYAML but not sure if this is even possible. So, in `YAML`, you can assign a variable like: current_host: &hostname myhost But it doesn't seem to expand in the following: test: | Hello, this is my string which is running on *hostname Is this at all possible or am I going to have to use Python to parse it?
The anchors (`&some_id`) and references (`*some_id`) mechanism is essentially meant to provide the possibility to share complete nodes between parts of the tree representation that is a YAML text. This is e.g. necessary in order to have one and the same complex item (sequence/list resp. mapping/dict) that occurs in a list two times load as one and same item (instead of two copies with the same values). So yes, you need to do the parsing in Python. You could start with the mechanism I provided in this answer and change the test if node.value and node.value.startswith(self.d['escape']) to find the escape character in any place in the scalar and take appropriate action.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, yaml, pyyaml" }
How do error bars change for variables squared? Let's say I have some variable $\mu$ with an uncertainty estimate: $$\mu = 2 \pm .5$$ Let's say I have another variable $\nu = \mu^2$. Is the uncertainty estimate in $\nu$ equal to the the uncertainty in $\mu$ squared, such that $$\nu = 4 \pm .25$$ This does not seem to be right to me. What would be the appropriate way of getting the uncertainty in $\nu$?
Uncertainty can be written for a quantity : $$ X=Y \pm u(Y) $$ Then taking the square you have $$ (Y\pm u(Y))^2=Y^2\pm 2Yu(Y)+u(Y)^2$$ Or a the first order for maybe more sense $$ (Y\pm u(Y))^2=Y^2\pm 2Yu(Y)$$ It is ok for you ?
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "statistics, error propagation" }
didReceiveAuthenticationChallenge not getting called I am using iOS sdk5.0. I am hitting a link using NSURLConnection and creating a request. But my control is not going into didReceiveAuthenticationChallenge method. Is didReceiveAuthenticationChallenge not called in iOS5.0?
According to Docs of `NSURLConnectionDelegate` connection:canAuthenticateAgainstProtectionSpace: connection:didReciveAuthenticationChallenge: connection:didCancelAuthenticationChallenge: are deprecated and new code should adopt connection:willSendRequestForAuthenticationChallenge The older delegates will still be called for compatibility, but incur more latency in dealing with the authentication challenge.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 7, "tags": "ios5" }
Objective-C: How to check a number is between two values Going a little nuts here with a super noob issue. How do a check if and int is between two values i.e. want to see if x<100 && x>50 I have tried: if(x<100 && x>50){ .. } but not having any joy??
Unless your compiler is broken there is nothing wrong with that code. There is probably something wrong with `x` As Sascha stated in the comments make sure that `x` is not an `NSNumber`. The reason for this is if `x` is an `NSNumber` then the value stored in it is a pointer which value would likely be much higher than 100 (0x4FBC60 for example) and you would want to compare against the `-(int)intValue`. Other things to consider are comparing against the right data. While implicit number conversions work well you may want to use the same literal comparison as your data type. unsigned long long x = 51ull; if(x > 50ull && x < 100ull) { }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "objective c" }
Concat dataframes by matching a value in a column to a list in another column I have 2 data frames with the following format: df1 ID age [111, 222, 333] 15 [444] 9 [555, 666, 777, 888] 8 df2 ID school 222 A 777 B I need to concat them by matching the IDs to get the following result df1_ID age df2_ID school [111, 222, 333] 15 222 A [555, 666, 777, 888] 8 777 B df1_ID could be a list of up to 10 IDs and I can't think of a way to concat the data frames efficiently. How would you approach this? Thanks.
If want working with data efficiently, is necessary change format, because working with `list`s in pandas is obviously slow. from itertools import chain df11 = pd.DataFrame({ 'ID' : list(chain.from_iterable(df1['ID'].tolist())), 'age' : df1['age'].values.repeat(df1['ID'].str.len()) }) print (df11) ID age 0 111 15 1 222 15 2 333 15 3 444 9 4 555 8 5 666 8 6 777 8 7 888 8 df12 = df11.merge(df2, on='ID', how='left') print (df12) ID age school 0 111 15 NaN 1 222 15 A 2 333 15 NaN 3 444 9 NaN 4 555 8 NaN 5 666 8 NaN 6 777 8 B 7 888 8 NaN
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python, pandas" }
Single domain for multiple ELB Is it possible for a single domain name to be associated with multiple AWS ELB on different domains? Eg. I want `example.com` to point to my first ELB, and `api.example.com` to point to my second ELB (which is from a different AWS account). I tried creating an `A record` for `example.com` with the first ELB as alias target, and another `A record` for `api.example.com` with the second ELB as alias target, but only `example.com` is working. For both of the ELB, I use the same domain name for the AWS cert manager to register for SSL cert, not sure if that affects anything.
The problem was that I forgot to allow all incoming traffic on the security group of the ELB...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "amazon web services, dns, amazon elb, amazon route53, elastic load balancer" }
How should I prove $\lim_{x \to \infty} \frac{1}{x^3} = 0$ Use the definition of the limit to prove the following limit. $$\lim_{x \to \infty} \frac{1}{x^3} = 0$$ This is my attempt at solving this question Suppose $\epsilon > 0$, choose $M = \frac{1}{^3\sqrt{\epsilon}}$ Suppose $x>M$ $$\frac{1}{x}<\frac{1}{M}\ \text{(taking the reciprocal)}$$ $$\frac{1}{x^3}<\frac{1}{M^3}\ \text{(cubing both sides)}$$ Assuming $x > 0$ as the limit is as $x$ approaches $\infty$: $$\left|\frac{1}{x^3}\right|<\frac{1}{M^3}$$ $$\implies \left|\frac{1}{x^3} - 0\right|<\epsilon$$ I am unsure whether this is the right way to do so. I thought of this method after watching videos and reading up on limit proofs. I am self-learning all these topics purely for interest. Any corrections to my working will be greatly appreciated! Thank you.
Well done, your logic works because giving a formula for $M$ based on $\epsilon$ which satisfies the proposition guarantees that such an $M$ exists for any $\epsilon,$ given that the formula is defined over the given domain. (which it is in this case) This is a proof strategy called _proof by construction_ and it's great for whenever you need to prove a given object exists. (as opposed to _proof by contradiction,_ which is more useful for proving something is true for all objects of a certain type) A few things worth noting, first off that cubing both sides of the inequality is justified because $f(x) = x^3$ is strictly increasing, which can be justified a number of ways but commonly by simply showing that $f'(x) = 3x^2$ is always positive. Second, the $x > 0$ can alternatively be justified with $M = \frac{1}{^3\sqrt{\epsilon}} > 0$ when $\epsilon > 0,$ so $x > M$ and $M > 0$ implies $x > 0.$
stackexchange-math
{ "answer_score": 3, "question_score": 10, "tags": "real analysis, limits, epsilon delta" }
Windows 7 on Mac Book Pro along with OS X (Dual Boot)? I'm thinking to buy Mac Book Pro with i5 or i7 Intel CPU. The question is would I be able to install Windows 7 parallel to OS X? Any instructions on that so I can estimate the success?
Yes you can, you use an application called Boot Camp and the official Apple manual for it is here.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "windows 7, macos" }
what happens when two stateful beans extends a single remote interface which Stateless bean instance assigned to EJB object to serve the client, when two Stateless beans implements single remote interface and with same name Ex: @Stateless(name="KING") public class One implements RemoteInterface{ } @Stateless(name="KING") public class Two implements RemoteInterface{ }
I suppose you will likely to get `CreateException` or `NameAlreadyBoundException`, not sure though. Try it out, why not?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, ejb 3.0" }
Getting the smaller model for a SMT formula Let say that I have some formulas that can be sat but I want to get the smaller (or larger) possible value so sat that formula. Is there a way to tell the SMT solver to give that kind of small solution? Example: a+1>10 In that example I want the SMT solver to give me the solution 10 instead of 100. Cheers NOTE: I have just seen a similar question answered by one of the z3 authors saying, three years ago, that they were implementing that functionality in z3. Do you know if it is already implemented?
It can be done using `maximize` and `minimize` More info (declare-const x Int) (assert (> (+ x 1) 10)) (minimize x) (check-sat) (get-model)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "z3, smt" }
RESTful API in CouchDB: How to structure your documents? Since CouchDB is implementing a RESTful API, doesn't that mean I wanna put all documents of the same type in their own database? eg. POST GET PUT DELETE POST GET PUT DELETE Rather than putting them all in one big database ( Doesn't a 100% RESTful approach mean that the former is more correct?
The primary reason to use multiple databases is to split the data up because of volume, notably creating new views, compaction, etc. There's no reason logically to split them up. The simple truth is that the DB doesn't care. Nor do the URLs. Nor do REST. You can easily create a logically similar URL structure within couch using views, or if you find that offensive you can use the built in URL Rewriting functionality with Couch. REST cares about architecture. REST cares that you use unique URLs. REST cares that you provides links to other resources via their URLs using hypermedia. REST cares that you use ubiquitous media types. Pretty URLs are way down on the list of things REST cares about. If you want to do REST, focus on architecture and media-types. URLs pretty much handle themselves.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 4, "tags": "rest, couchdb" }
if..while.. if .. loop strange issue Simple, yet i cannot figure out whats wrong. Scenario: I have a page called stationary. And item pen has been reviewed(clicked). Bottom sample code is a search feature, to list the related items. Code: $id = $_GET['id']; /* Code to display item*/ $query = "SELECT * FROM table1 WHERE table1_category = 'red'"; $result = mysqli_query($dbc,$query); if(mysqli_num_rows($result) < 2){ echo "No other red pen available."; }else{ while($data = mysqli_fetch_assoc($result)){ if($data['item_id'] == '$id'){ echo ""; }else{ echo $data['item_name']."<br>"; } } } My error: ID from the table is displaying incorrect while debugging. There seems to be a problem with inner if statement. or is there!? Fixed/Solved: if($data['item_id'] == $id){ ........ }else{}
if($data[item_id] == '$id'){ There's no definition of `item_id`. If it's a variable, those usually begin with a `$`. This is probably resulting in errors in your PHP logs (which you should really check). Perhaps you meant for it to be a string? if($data['item_id'] == '$id'){ Also, will that value ever equal the _literal string_ `'$id'`? Or did you mean to use the _variable_ `$id`? if($data['item_id'] == $id){
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysqli" }
Clarification about place for a question I posted this question on Programming Puzzles & Code-Golf and suddenly got a downvote and a comment, that my question is misplaced there. The downvote was removed after I wrote back, that the question is indeed on topic, but because I wasn't shure I opened a meta question. Many people told me there, that my question is suited better on SO, but since it is related to Code-Golf, I disagree to this. (Please also see quite similar on-topic questions during the commitment phase) Finally, they kept my question, but marked it as CW. As the people on Codegolf told me, that the linked question rather belongs to Stack-Overflow, what is the opinion of the people at Stack-Overflow about this issue.
I'm inclined to agree with them; while there is a code-golf aspect to it, at root it's more a question about algorithms. The meta-question is, what's the key aspect of the problem? I would say it's less "how do I make this code smaller" than "how do I make this code _smarter_ ".
stackexchange-meta
{ "answer_score": 3, "question_score": 2, "tags": "discussion, code golf, scope" }
With UIView Block animation do Flashing effect I want a flashing animation, Alpha value through UIView the code below, why disappear when the animation display has a direct emerged? Animation is not smooth. [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionRepeat animations:^{ if (aView.alpha == 0) { [aView setAlpha:0.5]; }else if (middle.alpha == 0.5){ [middle setAlpha:0]; } } completion:^(BOOL finished) { }];
When doing a repeating animation, you can often produce a more graceful animation if you use `UIViewAnimationOptionAutoreverse` when using `UIViewAnimationOptionRepeat`. By adding the autoreverse option, that prevents the jarring UI that results otherwise, where it gracefully animates from the starting state to the end state, but then jumps back to the starting state before repeating the process. By using `UIViewAnimationOptionAutoreverse`, it gracefully animates back to the start state before repeating the animation.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "ios, objective c, uianimation" }
Does append() need to be on the body tag to add to dom tree? I just need this to be cleared up, if I use append(), does it need to be on $("body") in order to add an element to the dom tree for access or can it be on any element? Just to clarify, I know you can do append on any element but I want to make sure what I need to append to for it to be in the DOM for later access, thank you for your time
It can be called on any element.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, dom" }
Apply constraint to equation, Wolfram Alpha. I think it's being able to handle gracefully this one: a * -2 + b * 5 = -9 Yields me several interpretations, one of them I like: a = 5n + 2, b = 2n - 1, n ∊ ℤ Now because `a` and `b` are Stack Exchange downvotes and upvotes on questions; and if I fed a `0` to the solution it handed me, it would yield `a = 2, b = -1` where `b` fails to be in ℕ; I tried to apply an additional constraint to it: a * -2 + b * 5 = -9 such that a > -1 and b > -1 But I'm unable to find such interpretation in the answers it's proposing me. How to / What am I doing wrong?
I think a * -2 + b * 5 = -9, a > -1, b > -1 did what I wanted. At first I thought it was interpreting a tuple, but I finally found a = 5n + 2, b = 2n - 1, n ∊ ℤ, n ≥ 1 as the last interpretation.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "wolfram alpha" }
Cut just one character out of a javascript string I want to remove what is inside the last bracket of a string. This is the ids string: rule_Group[0][5] This is my Javascript code var str = 'rule_Group[0][5]'; var a = str.lastIndexOf("[") + 1; var b = str.lastIndexOf("]") - 1; var res = str.substr(a,b) document.write(res) I want to keep the 5 in the brackets. No matter what JS doesn't allow me to cut out just one character. I have even manually tried to do this with no luck. Any advice?
use `substring` instead of `substr`. var str = 'rule_Group[0][5]'; var a = str.lastIndexOf("[") + 1; var b = str.lastIndexOf("]"); var res = str.substring(a,b) document.write(res)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript" }
How to get bitcoin address of any private key? calling `bitcoin-cli dumpwallet` returns wallet private keys and addresses. **Example** L34D2hAS9KBJQzJkHtmNt1bdSJ18cQUvfSnJEqPKH2oUj6sBxvXt 2017-11-23T05:11:13Z reserve=1 # addr=1D2mnuj9qeRAzmw8mjLDciyvqzQiiYZCfE hdkeypath=m/0'/0'/1030' Importing this private key to wallet using `importprivkey` command returns `null` on success. How to get bitcoin address related to this private key? or is there's any way get this private key details like balance or addresses?
the private key is a Private Key WIF Compressed, 52 characters base58, and can be used to convert into (compressed or uncompressed) public keys. These pub keys are usually hex codes, and can be converted into bitcoin addresses: 1D2mnuj9qeRAzmw8mjLDciyvqzQiiYZCfE and 1KWvNZB4Gf2Kars88aGR2cedUb81Q6gZKC. There is no easy way I am aware of to do this in bitcoin client. Looking at the line you provided, the bitcoin address is behind the comment sign (#), and is part of a HD key, which complicates things even more, if I had to explain it. To understand the whole idea behind keys, you may want to read bitcoin.org or the book af Andreas "Mastering Bitcoin" (online available). Looking then at e.g. blockchain.info, you can provide the addresses or the keys, and see that there is no value. Hint: **never ever (!)** use this key again to transfer values. It has been disclosed, and people are only waiting to snipe the values from this address! - me too :-)
stackexchange-bitcoin
{ "answer_score": 2, "question_score": 2, "tags": "bitcoin core, address generation" }
SQL query to finds rows containing a value in a column that also appears in another column? Given a team table represented as below. ` id | name | owner_id | members ------|------------------------------------- 1 | Tigers |99 | 501,502,503 2 | Bears |100 | 100,600,601,602 3 | Swans |101 | 700,701,702 ... ` A team has a name, an owner (a foreign key to a user's table), and members (a list of id's related to users in a user's table). The point here is that while owners are implicitly team members, their id does not appear in the members column. In the above example, row #2 is an error (id 100 appears in members column). **Question** How can I query the table for rows which have owner_ids that also appear in members column?
Use `FIND_IN_SET`. select * from tbl where find_in_set(owner_id,members)>0
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "mysql, sql" }
Java package error I am currently working on a Java project using openDIS- however, in one of my Java class files, I have started off with the line `package openDIS`, the same as in the other Java class file that I'm using, but in this one for some reason, I get a compiler error that says The type javax.persistence.GenerationType cannot be resolved. It is indirectly referenced from required .class files Any ideas why this is, or how I can resolve it? The one quick fix it offers is to 'configure build path- clicking this opens a dialog box which shows that I have the 'open-dis_4.08.jar' and 'JRE System Library [JavaSE -1.7]' libraries added to my project... I can't think of any others that I would need...?
The `javax.persistence` package is part of the Enterprise JavaBeans (EJB) persistence API. You'll need to use the Java EE SDK instead of Java SE.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, simulation" }
Glob pattern include all js exclude certain endings I'd like to use glob with mocha. Sadly mocha does not support exclude and it does not pass glob options either, so I have to solve this in a single pattern without the usage of the glob ignore option. < The other solution would be to use mocha.opts, but that is not karma compatible, I am not sure why. I could define a karma compatible opts file for karma and a node compatible opts file for node, but this will break immediately after the issue is fixed, so I am looking for another solution. < I need to match `test/**/*.spec.js` and exclude `test/**/*.karma.spec.js` from the results. Is this possible with a single glob pattern?
What we are talking here is the `AND("*.spec.js", NOT("*.karma.spec.js"))` expressed with logical operators. I checked the glob documentation, it does not support the `AND` logical operator. Lucky for us we can transform this operator to `OR` with negation: `NOT(OR(NOT("*.spec.js"), "*.karma.spec.js"))`. I tried out the `test/**/!((!(*.spec.js)|*.karma.spec.js))`, but it does not work. It tries to require a module with the `test/features` path, which is a path of a directory and not a js file, so no wonder it does not manage it. I don't know what kind of bug is that, but it is apparently not working. Another possible solution to forget this `AND` operator, and use only negation with `NOT("*.karma").spec.js`. I tried this out with `test/**/!(*.karma).spec.js`, which was working properly.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "node.js, pattern matching, mocha.js, glob, node glob" }
How to pull image file from db2/AS400 file systems and insert into MS SQL Server I am newbie to DB2/AS400. working on an ETL project. basically, we need to "select" image files (*.bmp) stored on a AS400 server file system/share (not sure if this is the correct term but to differentiate it from a Database file/table). I have other processes in a MS SSIS package already pulling data from this AS400 server database/tables (using MS DB2 Provider + SQL) successfully. But I do not know how to interact with AS400 file system from a Windows system. I can use the UI tool (iSerials Navigator i.e.) browse to those files. I'd appreciate any pointer/help. Thanks.
In IBM i terminology, we would probably say that files on a shared directory in the IFS [Integrated File System]. The software that delivers files over the network from the IFS is called NetServer. You should be able to read the files from a Windows application the same way you would read any other file over the network. * * * If you are seeking speed by delivering them from SQL Server, you would probably get faster delivery times by storing them in a BLOB column in a DB2 table, rather than SQL Server. DB2 is generally faster than SQL Server, and faster than the IFS. Of course all this depends on what you are doing and trying to accomplish, among other factors.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "filesystems, ibm midrange" }
Does using FULLTEXT in MySQL require for me to use a different syntax in PHP to retrieve the results? Here's my code: $terminosBuscados = 'Vender la porteria' $x = $conectarDB->prepare(" SELECT DISTINCT titulo, FROM_UNIXTIME(fecha, '%d-%m-%Y') AS fecha, cuerpo, tipoContenido, autor FROM searchIndex WHERE match(titulo) AGAINST (' ? ' IN BOOLEAN MODE) ORDER BY contenidoID DESC "); $x->bindParam(1, $terminosBuscados); $x->execute(); $y = $x->fetchAll(PDO::FETCH_ASSOC); This is showing no results at all (`$y` returns `null`), when trying the query itself in phpMyAdmin does work and show results. I've just added a FULLTEXT index into the table and adapted my working code to use that index.
For mysql ' ? ' is a string, and will not be used as palce holfer. If you need the spaces use `CONCAT(' ',?,' ')` $x = $conectarDB->prepare(" SELECT DISTINCT titulo, FROM_UNIXTIME(fecha, '%d-%m-%Y') AS fecha, cuerpo, tipoContenido, autor FROM searchIndex WHERE match(titulo) AGAINST (CONCAT(' ',?,' ') IN BOOLEAN MODE) ORDER BY contenidoID DESC "); $x->bindParam(1, $terminosBuscados); $x->execute(); $y = $x->fetchAll(PDO::FETCH_ASSOC);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, mysql, full text search, prepared statement, fulltext index" }
Zeoslib: How to tell when query execution is complete? I am using ZeosLib within Delphi to call a MySQL stored procedure through the TZQuery object. Immediately after MySQL finishes execution of the stored procedure I need to initiate my next block of code. I added a `SELECT 1;` statement at the end of my MySQL stored procedure. What is the best way to find out that the results have been returned?
Zeos lib does not play nice with stored procedures that return a result set. It actively disables the returned resultset. There is a workaround for that, you can activivate the resultset by altering the ZEOS source code. However when you do that, you get lots of errors like `MySQL has gone away`. At unpredictable times, which is probably why they disabled this option in the first place. In the end the workaround I went for is to put any resultset that I need in a (temporary) table and query that after the stored procedure finishes. This solved the errors and works well for me.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "mysql, sql, delphi, mysql connector, zeos" }
AppleWatch : On button tap from the the AppleWach Open URL on iPhone device I want to open url from the AppleWatch app button tap to the mobile application. Please any one have any idea regarding to these?
Added this in your AppDelegate.m - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@" }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, apple watch" }
Random range of float in Objective C? for an in I'm doing this: int randomRange(int min, int max) { int range = max - min; if (range == 0) return min; return (arc4random() % range) + min; } but how can I do this with a float?
+(float) randFloatBetween:(float)low and:(float)high { float diff = high - low; return (((float) rand() / RAND_MAX) * diff) + low; }
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 4, "tags": "iphone, random, floating point" }
Difference between Java's Vector.add() and Vector.addElement()? Please explain the difference between the `Vector.add()` method and the `Vector.addElement()` method, along with a sample code snippet
`add()` comes from the `List` interface, which is part of the Java Collections Framework added in Java 1.2. `Vector` predates that and was retrofitted with it. The specific differences are: 1. `addElement()` is `synchronized`. `add()` isn't. In the Java Collections Framework, if you want these methods to be synchronized wrap the collection in `Collections.synchronizedList()`; and 2. `add()` returns a boolean for success. `addElement()` has a `void` return type. The `synchronized` difference technically isn't part of the API. It's an implementation detail. Favour the use of the `List` methods. Like I said, if you want a `synchronized` `List` do: List<String> list = Collections.synchronizedList(new ArrayList<String>()); list.add("hello");
stackexchange-stackoverflow
{ "answer_score": 29, "question_score": 18, "tags": "java, collections" }
MySQL database server v.s. Phpmyadmin Can anyone "PLEASE" answer these two questions : 1- What is the difference between MySQL database server and Phpmyadmin ? 2- can I make a connection from a java software to a phpmyadmin database using JDBC-driver ? and how ? Thank you in advance !!
> 1- What is the difference between MySQL database server and Phpmyadmin ? mySQL is a database server. phpMyAdmin is a client tool to access a mySQL database, written in PHP and used in a browser. > 2- can I make a connection from a java software to a phpmyadmin database using JDBC-driver ? and how ? No, but you should be able to make a connection to a mySQL database. As to how... I don't know but I'm sure there is reference info for this. **Update** : See here: > JDBC Driver for MySQL (Connector/J)
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "java, mysql, jdbc, phpmyadmin" }
Sending rails errors to rspec output I am using Capybara in combination with rspec for integration testing of rails apps. I would like any errors (routing errors, errors in a controller, anything) generated during a test to be printed the same as "puts" statements in rspec's output. Is this possible? Additionally, is this a reasonable idea, or am I just being silly?
Adding the following to my spec_helper.rb file worked: ActionController::Base.class_eval do def rescue_action(exception) raise exception end end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "ruby on rails, logging, rspec, integration testing, capybara" }
Red Hat Enterprise Linux の開発者用サブスクリプションについて RHEL 8.2821OS OSHP… Windows Server DB
() OS (web) ()
stackexchange-ja_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "linux, rhel" }
Divide UITableView into fixed number of cells I created a UIViewController which has a header and contains a UITableView. Now I want to divide the whole height of the UITableView between 6 cells. I tried it with `tableView.frame.size.height` and then set the `tableView.rowHeight = tableViewHeight / 6`. But when I launch the application, there is still some space left on the bottom of the table view. Is there another way?
I would recommend returning the cell height from the `tableView:heightForRowAtIndexPath:` delegate method like so: let numOfRows = 7 ... func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numOfRows } ... func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return tableView.frame.size.height / CGFloat(numOfRows) } With that method, you're given direct access to your `tableView` where you can divide its height by the number of rows you want. Return that value to set the tableView's row height.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "ios, swift, uitableview" }
My data at a certain latitude is disappearing in Mapbox Studio? I'm trying to make a simple map showing 4 villages in Alaska (and Fairbanks for reference) but for some reason the northernmost village is being cut-off it seems. When viewing the data in Mapbox Studio there is a mysterious line that seems to be the culprit? I have no idea what this line is from. See picture below. The coordinates for the disappearing village are -152.65091, 66.56305. Here is the data file in geojson format as a gist villages.geojson gist![data cut off by mysterious line]( And here is the working map Map
The line that is clipping your type is a tile boundary. The clipping can occur in certain cases where data/labeling exists at the edge of a tile boundary. You can "debug" your map and adjust labeling and such to avoid these artifacts using the setting shown below. ![Tile boundaries](
stackexchange-gis
{ "answer_score": 1, "question_score": 0, "tags": "mapbox, grids graticules, mapbox gl, mapbox studio" }
framework is red in Xcode but no error with building The file is displayed in red in Xcode as shown in the image. I'm developing a Flutter app and buid to ios simulator succeeds without any problems. I have no idea what the cause is. Also, when I check the corresponding file with alfred, the path seems to be different ... I tried pod update , but nothing changed. Xcode ver : 12.5.1 use m1 mac.and installed cocoapod by homebrew. ![enter image description here](
This means that your framework is not found... if you right clic on them and select show in finder, it will probably not take you anywhere, as it does not know where they are... you can just re-include them in your project, by dragging and dropping them in your project directory and that should auto-correct so that they don't show in red... You may also want to check 'Framework Search Paths' under the build settings of your project/target... to make sure it can find them, the paths to the location of your frameworks should all be included here (it's easier if yo have all your frameworks in one folder) But to make them not show up as red, just drag and drop them from wherever they are again into your project, and then delete the red one and you should be good...
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ios, xcode, flutter, cocoapods" }
Platform diving - diver standing position I am following the Olympic diving. I am always wondering why or how divers choose to jump from different positions on the platform (i.e not from the center)
There is no rule governing where a diver should stand before diving. They can choose any place or position they like. According to the linked Wikipedia article on **diving platform**: > Diving platforms for FINA sanctioned meets must be at least 6 metres (20 ft) long and 2 metres (6.6 ft) wide. The width is necessary because there is also a synchronized platform diving competition.
stackexchange-sports
{ "answer_score": 3, "question_score": 2, "tags": "technique, olympics, diving" }
Where can I find LDraw examples? Where can I find LDraw files to download? I would like to have a collection of simple Lego examples and want to create step-by-step instructions for my youngsters.
The models included in AIOI as mentionned by HaydenStudios is also available as **separate download** There is also a huge collection of LDraw models of official sets available on **Eurobricks forum**
stackexchange-bricks
{ "answer_score": 5, "question_score": 3, "tags": "instructions, ldraw" }
Why is my union's size bigger than I expected? When I print the size of a union like this: union u { char c[5]; int i; } un; using this: int _tmain(int argc, _TCHAR* argv[]) { printf("size of union = %d ",sizeof(un)); return 0; } I get an answer of 8 using Visual C++, but I expected 5. Why? Well, for the same example, i did something like this: int i1 = 0x98761234; un.i = i1; printf("\n un.c[0] = %x ",un.c[0]); printf("\n un.c[1] = %x ",un.c[1]); printf("\n un.c[2]= %x ",un.c[2]); printf("\n un.c[3] = %x ",un.c[3]); printf("\n un.c[4] = %x ",un.c[4]); printf("size of union = %d ",sizeof(un)); i got results like un.c[0] = 34; un.c[1] = 12; un.c[2] = 76; un.c[3] = ffffff98; why are there 6fs at un.c[3]
The `sizeof` operator produces the size of a variable or type, _including_ any padding necessary to separate elements in an array of that type such that everything is still correctly aligned. Since your union has an `int` member, it needs to be 4-byte aligned, so its "natural" size gets rounded upwards to the next multiple of 4 bytes. * * * The `ffffff98` is because you're compiling with signed `char`. Using `%x` with an argument that is not `unsigned int` causes undefined behaviour; what you're seeing is sometimes called _sign-extension_. The result of your aliasing is `0x98` reinterpreted as `char`, which is `-104`. This retains its value on being promoted to `int` (this is called the _default argument promotions_ ), and the int `-104` when aliased as `unsigned int` becomes `0xffffff98`.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 8, "tags": "c++, unions" }
C++ compilation error: "cast from 'WCHAR*' to 'WORD' loses precision" MyGUI library. There's a line in its sources: mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)); _mHandle_ is `size_t` _LoadCursor_ returns `HCURSOR`. Error: D:\Dev\MyGUI_3.2.0_RC1\Common\Input\Win32\ResourceW32Pointer.cpp:48: error: cast from 'WCHAR*' to 'WORD' loses precision Here's the full source: www.pastebin.com/gzqLBFh9 MinGW compiler. There was error `cast from 'CHAR*' to 'WORD' loses precision` and **selbie** gave an advice to add macro here: [Create window with WNDCLASSEX? [Cpp]]( . Thanks to him - it disappeared.
The problem is actually at `MAKEINTRESOURCE(IDC_ARROW)` and isn't related to the type of `mHandle`. [Aside: I agree that `mHandle` should not be `size_t` but I think that is not your current problem.] Since `IDC_ARROW` is defined to be `MAKEINTRESOURCE(32512)`, the code should in fact read LoadCursor(NULL, IDC_ARROW) rather than LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)) The latter code fails because IDC_ARROW is `LPTSTR` but `MAKEINTRESOURCE()` expects `WORD`. That explains the error message you see. In fact `IDC_ARROW` is already a resource type and needs no further processing. Likewise, all the other calls to `LoadCursor()` are in error.
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 5, "tags": "c++, winapi, mingw" }
MessageBox not resolving to MessageBoxW? Scenario 1 I created an empty vc++ project added a c file to it and the #include. Now in my main() function if I hover my mouse over the MessageBox func., it resolves to MessageBoxA. Scenario 2 I create a win32 windows project now here MessageBox resolves to MessageBoxW??? I checked the Project properties->c/c++->preprocessor property there I found **WIN32** defined so I did that in my previous project but still the same result. What should I do.Yeah of course I can use the latter type of project but think of me as one stubborn rookie who wants to learn the tid-bits. thanks.
The default "Character Set" property for a new empty project is "Multi-Byte", which means that the preprocessor will not define the `UNICODE` preprocessor symbol and so `MessageBox` will be replaced by `MessageBoxA`. For a Win32 project, the default "Character Set" property is "Unicode", which means the preprocessor _will_ define `UNICODE` and thus `MessageBox` will be replaced by `MessageBoxW`. See the MSDN article Working with Strings for an introduction.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "winapi, api" }
Placing point symbol on center of polygon in ArcMap? I'd like to symbolize polygons with a point at the centroid. Does anyone have suggestions how to accomplish this without creating a new shapefile? I'm using ArcGIS 10.0.
You can use the symbology option 'multiple attributes' and set the size min/max for the symbol to the same, and it will create a dot in the middle of each polygon. also, you could probably do the same with maplex labeling to place a '.' label at the centroid of each shape
stackexchange-gis
{ "answer_score": 9, "question_score": 3, "tags": "arcgis 10.0, arcgis desktop, arcmap, polygon, symbology" }
CSS Div boxes not going underneath eachother i am using this CSS code for a few div boxes on my homepage: #homepagebox { width:80%; margin:0 auto 0 auto; } #homepagebox .column { float: left; width: 25%; } #homepagebox .column div { margin: 15px; min-height: 300px; max-height:300px; color:#ffffff; background: #666666; border-radius:10px; } I need them to start displaying underneath each other when the screen gets too small but then obviously if the screen is big enough then to all display next to each other. at the moment if the screen is too small the boxes just get smaller Here is a fiddle: <
#homepagebox .column { float: left; min-width: 25%; } If you set your width in percentages, it will never hit the point of needing to wrap content to the next line. Setting it as min-width makes sure that they never shrink below that point and will therefore wrap. [edit] update fiddle to have a fixed width but still wrap when needed. #homepagebox .column { float: left; width: 25%; min-width: 200px; } <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html, css" }
R data.table grepl column on another column in i Can I subset for when a string in column A is in column B? Example: x <- data.table(a=letters, y=paste0(letters,"x")) x[grepl(a, y)] x[like(y, a)] Both return only a one row data.table of the first row and the following warning: Warning message: In grepl(pattern, vector) : argument 'pattern' has length > 1 and only the first element will be used I would expect this to return all rows.
The following code applies `grepl` to each row with the `a` and `y` as a pair of that row. Basically, the first argument of grepl cannot be a vector with length larger than 1, so looping or lapply based approach is needed. x[mapply(grepl, a, y), ] # a y # 1: a ax # 2: b bx # 3: c cx # 4: d dx # 5: e ex # 6: f fx # 7: g gx # 8: h hx # 9: i ix # 10: j jx # 11: k kx # 12: l lx # 13: m mx # 14: n nx # 15: o ox # 16: p px # 17: q qx # 18: r rx # 19: s sx # 20: t tx # 21: u ux # 22: v vx # 23: w wx # 24: x xx # 25: y yx # 26: z zx # a y
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "r, data.table" }
Is it haram to build a system which will be used at the end for haram purposes? I am a programmer and I have been thinking about something for a **very** long time. At the moment I am working for a company who has a beer website. I, the developer, have built the entire system of this alcoholic website but I am really afraid the money I earned with it is haram-money and that it was a sin to build a system for this website. Is it haram to build a system which will be used at the end for haram purposes? By the way, I had nothing to do with the content (pictures, texts etc..) and the site is _not_ selling it
> God’s curse falls on ten groups of people who deal with alcohol. The one who distills it, the one for whom it has been distilled, the one who drinks it, the one who transports it, the one to who it has been brought, the one whom serves it, the one who sells it, **the one who utilizes money from it** , the one who buys it and the one who buys it for someone else." - Sunan Ibn-I-Majah Volume 3, Book of Intoxicants, Chapter 30 Hadith No. 3380. It would seem that the answer depends on whether you profit from the sale of alcohol.
stackexchange-islam
{ "answer_score": 4, "question_score": 4, "tags": "halal haram" }
Mathematica plot, exclude endpoints? Why does the following give me errors about dividing by 0? ParametricPlot[{1/Sin[t], t}, {t, 0, 3 Pi}, Exclusions -> Sin[t] == 0] Power::infy: Infinite expression 1/0 encountered. It does successfully exclude the points at Pi and 2 Pi, but not the points at 0 and 3 Pi. If I exclude the endpoints by changing the interval... ParametricPlot[{1/Sin[t], t}, {t, 0.001, 2.999 Pi}, Exclusions -> Sin[t] == 0] I get no errors. How do you exclude the endpoints of a plot? thanks, Rob
In this particular case, you can reformulate the plot with `Csc[t]` instead of `1/Sin[t]` and things seem to work: ParametricPlot[{Csc[t], t}, {t, 0, 3 Pi}, Exclusions -> {Sin[t] == 0}] !Mathematica graphics I suspect the behavior with `1/Sin[t]` is simply a bug and will report it as such. As a more-general workaround, you can wrap your original expression with `Quiet` to surpress the error messages: Quiet[ParametricPlot[{1/Sin[t], t}, {t, 0, 3 Pi}, Exclusions -> Sin[t] == 0], Power::infy]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "plot, wolfram mathematica" }
Is there any benefit to putting application variables in Application.rb vs an initializers/file.rb There's a lot of suggestions on where to store your application wide variables, including a few gems that do it for you. For Rails 4 the most simple way I've found to do this is to add a variable to 'config' in either Application.rb or an initializers/file.rb like such #/config/application.rb config.new_variable = 5 or #/config/initializers/application_variables.rb Rails.application.config.new_variable = 5 I'm wondering if there's any difference in these two, maybe load times, or if the one in application gets called everytime the application is refreshed, etc...
This definitely depends on the intended usage. I would use `/config/application.rb` to only configure the actual Rails application. Not to store miscellaneous variables used in my own code. Thats just a global in disguise. For API keys and other secret bits and bobs the answer is using environmental variables combined with initializers: # /config/initializers/boozehound_client # a fictional API client Boozehound.configure( api_key: ENV['BOOZEHOUND_API_KEY'], secret: ENV['BOOZEHOUND_API_SECRET'] ) Otherwise if you need to use a variable across controllers you could place it your `ApplicationController`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ruby on rails, configuration" }
How should one know the vote-count of a user when he asked a question? How would one know the vote-count of a user has when he/she asked a particular question or answered a particular question? Right now it just shows the current status of the user for a past question, which is normal though. But in case I would want to know the status of the user when he asked a question or answer, how would I find that?
## If you mean the vote count on the question/answer: Questions have a timeline, where you can follow this information. Changing into allows you to follow the timeline of your question. So, replace `questions` by `posts` and the end by `timeline`. Go try it for a more busy question, it takes a bit of practice to be able to read it properly... ## If you mean the user's reputation: You can see this under the `reputation` tab on the profile of a user. However, it doesn't show totals; so you'd have to count how his reputation has changed over time. Although, the network profile `reputation` tab shows a nice graph where you can get a better idea if the question has been asked long ago and it becomes unfeasible to use the user's profile.
stackexchange-meta
{ "answer_score": 3, "question_score": 2, "tags": "discussion, vote count" }
How to avoid the vim omnicomplete menu closing when entering the parameter list? I’m actively using it for `Python` and `C++` development and it’s kind of frustrating that the menu always closes on me when I enter the function parentheses, because that’s normally when I need most of the help (types and order of parameters).
Vim's _omni completion_ does not work exactly like _Intellisense_ in IDEs; it helps completing an identifier or function name, but has no notion of function arguments and their types. That means: It can help you with typing `frobnize`, may even show the function prototype `frobnize(Foo, Bar)`, but cannot help you with completing the function arguments. For that, the completion function would need to consider the full underlying syntax and the previous context, which most don't. The only aid that some completions offer is that the function prototype is shown in the preview window (with `:set completeopt+=preview`, which is the default). The preview window stays open after the completion, so you still have the last function prototype visible. However, not all completions provide this information.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "vim, parameters, omnicomplete" }
Susy 2: How to remove "last" from nth-child on different breakpoint? I'm using Susy 2 and I have this code: @include breakpoint($tab) { .l-region--sections { > .block { @include span(6 of 12); &:nth-child(2n) { @include last; } } } } @include breakpoint($desk) { .l-region--sections { > .block { @include span(4 of 16); &:last-child { @include last; } } } } The problem is that at desktop width, the ":nth-child(2n)" takes effect and I would like to remove it completely in favor of ":last-child". How can I remove ":nth-child(2n)" styles for desktop?
It appears the answer is here: < , basically: @include breakpoint($tab) { .l-region--sections { > .block { @include span(6 of 12); &:nth-child(2n) { @include last; } } } } @include breakpoint($desk) { .l-region--sections { > .block { @include span(4 of 16); &:nth-child(2n) { @include span(4 of 16); // We are declaring span for this container here once more, just to override nth-child styles. } &:last-child { @include last; } } } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sass, susy compass" }
how to get values monthly from mysql table I have a table `lead` and there is a field called `added_on (datatype timestamp)`, I want to to fetch only the leads which are interested in a particular product and the reports should come monthly. `interested_in` is a field in the lead table where the interested product's id will be stored as a comma separated values. and `$prod_id` is stored with a product id which has to be checked. the below query works fine just to fetch out the leads which are interested in a particular product. but i want the results to come month by month. select*from lead where find_in_set('$prod_id',interested_in) Please guide me what i have to do to achieve that
TRY `WHERE MONTH(added_on) = $giveMonthNumber` OR `WHERE MONTHNAME(added_on) = $givenMonthName;` Reference : MySQL date time functions
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
programmatically enabling buttons taking several seconds I am creating a swift app with AVFoundation and using an AVAudioPlayerNode. I disable the play button while playing and in the completion portion of the player I enable it, but the button stays transparent for over 10 seconds. The button is useable and my print("complete") shows immediately, so it seems like the view is not updating. Here is my code: player.scheduleBuffer(buffer, completionHandler: { print("complete") self.playButton.enabled = true } ) I have tried the following with no luck: self.view.layoutIfNeeded() player.scheduleBuffer(buffer, completionHandler: { print("complete") self.playButton.enabled = true self.playButton.reloadInputViews() self.view.layoutIfNeeded() } )
The completion handler is not in the main thread. You can move that portion of the code by using this code: self.player.scheduleBuffer(buffer, completionHandler: { print("complete") dispatch_async(dispatch_get_main_queue(),{ self.playButton.enabled = true }) })
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, swift, avfoundation, avaudioplayernode" }
R gsub not removing '?' in data I have a large df that I am trying to clean up, it goes something like this Name1. Name2. Var1. Var2.... name? ... ... ... name? ... ... ... So the Names are encrypted and they do include special characters that I do NOT want to remove. I have been using gsub(), but it does not remove the '?': I just want to remove the single '?' at the end of the names that Excel somehow added on. MyData$Name1 <\- gsub("?", "", MyData$Name1) Nothing seem to have changed and I do not get any error codes. Name1. Name2. Var1. Var2.... name? x a 1 ... name? y b 2 ... Does anyone have any prior experience with something like this?
`?` is a _metacharacter_, and has a special meaning in regular expressions. In order to get a literal question mark, you must escape it. Use: gsub("\\?", "", MyData$Name1)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "r, normalization, gsub, data cleaning" }
Linq with null parameters not working I don't understand why this query is not working, can you please help me? public static IEnumerable<SelectListItem> MyList(int? id, string name="") { var list =db.Entity .Where(p=> (name==null? p.Name !=null : p.Name==name) && (id.hasValue || p.Id==id) .Select(n=>new SelectListItem() { Text=n.Name, Value=n.Id.ToString() }).ToList(); return list; } I want to have the full list when both parameters are null!! but I get an empty list when both parameters are null. The snippet code is from a big method which contain several query like this one.
If I understand you correctly you do not want to perform filtering when the value is `null`. Then you should write: .Where(p=> (name == null || p.Name == name) && (id == null || p.Id == id) And you should change the signature of the function to set the default value for parameter `name` to `null` rather than empty string. public static IEnumerable<SelectListItem> MyList(int? id, string name = null)
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 1, "tags": "c#, asp.net mvc, linq" }
How can I detect if I'm in a subshell? I'm trying to write a function to replace the functionality of the `exit` builtin to prevent myself from exiting the terminal. I have attempted to use the `SHLVL` environment variable but it doesn't seem to change within subshells: $ echo $SHLVL 1 $ ( echo $SHLVL ) 1 $ bash -c 'echo $SHLVL' 2 My function is as follows: exit () { if [[ $SHLVL -eq 1 ]]; then printf '%s\n' "Nice try!" >&2 else command exit fi } * * * This won't allow me to use `exit` within subshells though: $ exit Nice try! $ (exit) Nice try! What is a good method to detect whether or not I am in a subshell?
In bash, you can compare `$BASHPID` to `$$` $ ( if [ "$$" -eq "$BASHPID" ]; then echo not subshell; else echo subshell; fi ) subshell $ if [ "$$" -eq "$BASHPID" ]; then echo not subshell; else echo subshell; fi not subshell If you're not in bash, `$$` should remain the same in a subshell, so you'd need some other way of getting your actual process ID. One way to get your actual pid is `sh -c 'echo $PPID'`. If you just put that in a plain `( … )` it may appear not to work, as your shell has optimized away the fork. Try extra no-op commands `( : ; sh -c 'echo $PPID'; : )` to make it think the subshell is too complicated to optimize away. Credit goes to John1024 on Stack Overflow for that approach.
stackexchange-unix
{ "answer_score": 46, "question_score": 34, "tags": "bash, shell, exit, subshell" }
Gimp Projects default Unix location I am trying to do a series of tutorials to guide others on how to share a full development system to Unix running in VirtualBox. Oddly, the last piece of my tutorial (The Gimp) seems to be the only software that lacks a default Projects directory. Am I missing something? I use Gimp on Windows and Ubuntu, but have never taken much notice until now of this. It seems pretty common for a software of this type to have a default directory to store projects to. Doing so, would allow directories to be shared between host and guest systems like in VirtualBox, but more importantly assist those that like to write scripts not just for themselves, but others too. eg. I can refer to `~/IdeaProjects` in a script in confidence that the directory contains Jetbrains IDEA projects. *This is a Gimp issue as it is both on Windows and Unix Gimp that have no projects directory.
No, it indeed does not have, and will just save to the system sugested (~/Documents, generally) just like OpenOffice, text editors, and a lot of other programs. There are directories for the resources GIMP uses, like plug-ins, textures, brushes and so, which can be set in the prefrences dialog (and are stored in a ~/.gimprc file which can be parsed. But no default folder for user images.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "gimp" }
Why do Nvidia mobile cards not work with Ubuntu I've gone through 8 laptops already. I keep returning them because I can't get Ubuntu working with the latest Nvidia drivers. When I first install Ubuntu it works perfectly. But I need OpenGL 4.3 so I need to install the latest Nvidia driver. Once I do that and reboot Ubuntu crashes. I have also tried this with Linux Mint and same results. My current laptop is an Acer Aspire V 15 Nitro (VN7-571G-769P) with an Nvidia GeForce 840M. I can't believe I can't get linux with OpenGL 4.3 working. I'm getting the following error Xlib: extension "GLX" missing on display ":0"`
You can install drivers to Ubuntu 14.04 this way sudo add-apt-repository ppa:xorg-edgers/ppa sudo apt-get update sudo apt-get install nvidia-346 nvidia-prime sudo add-apt-repository -r ppa:xorg-edgers/ppa In 15.04 just `sudo apt-get install nvidia-346 nvidia-prime`.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 0, "tags": "nvidia, opengl" }
Orbeon - saxon parse() stop working in new version I have problem with function saxon:parse() in my form. I used it in Orbeon 2020.1.2 CE and it worked well. After update to version 2021.1.2 PE (I have prebuild) it stop working. I try same thing on orbeon.com too with same bad result (< Strange is when i try same thing saxon:parse(//xml) in xforms-inspector it work well (I change $ from form to // in inspector). Is some change in using saxon in new version or I hit some bug? Thank you
As of Orbeon Forms 2021.1, you can't use `saxon:parse()` anymore, and should use `xf:parse()`, which is a new XForms 2.0 function (see differences between XForms 1.1 and 2.0). In new code, it is always better to use `xf:parse()`. However, for backward compatibility, it would be good for Orbeon Forms to also support `saxon:parse()`, and this is tracked as issue #5271.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "saxon, orbeon" }
how to check running time and how to force stop program I'm making Online Judge, but I can't check need to be judged file's running time and I can't stop it. If submitted program have infinite loop, my judge system falls to infinite loop too. how should I do?
You should simply run the "to be judged files" in a separate thread and kitt it after a time-limit if it has not terminated successfully before. This way you only need to wait in your time limiting thread and than kill the other one, if it has not finished already.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "algorithm" }
How to use supervisorctl on Ubuntu? I'm trying to install plumi And I did `sudo apt-get install supervisor` but `./bin/supervisord` doesn't work, nor `./bin/supervisorctl status` `sudo service supervisor status` shows that it's running but does not show what services are running so please tell me how supervisor work and how I could check what service are running
Do you have **Supervisor** installed? If no do this first: sudo apt-get install supervisor Once this has completed, the supervisor daemon should already be started, as the prebuilt packages come with an init script that will also ensure the Supervisor is restarted after a system reboot. You can ensure this is the case by running: sudo service supervisor restart Now you can read the link here for more information about installing Plumi. **Edit:** More information can be found here.
stackexchange-askubuntu
{ "answer_score": 7, "question_score": 4, "tags": "python, services" }
How can I do own increment value in mysql I'm struggling to do proper sql script to increment field on specific way. Those two script are without any exception, but nothing happened on the results. Script 1: UPDATE myTable T1, ( SELECT id, (@s:=@s+1) AS seq FROM myTable, (SELECT (@s:=0) AS s ) s WHERE infotext IS NULL ORDER BY grouptext ) T2 SET sequence = seq WHERE T1.id = T2.id Script 2: UPDATE myTable AS target INNER JOIN ( SELECT supfault_id, (@s:=@s+1) AS seq FROM myTable, (SELECT (@s:=0) AS s ) s WHERE infotext IS NULL ORDER BY grouptext ) AS ordered ON ordered.id = target.id SET sequence = seq
Subqueries working well separately, so I wondered why I can't update my sequence value by seq from subquery. I'm not expert, but I felt that need to be used some virtual table for my subquery. Here is solution for inner join case: CREATE TEMPORARY TABLE supportGroupSeqcalculation AS SELECT supfault_id, (@s:=@s+1) AS seq FROM myTable, (SELECT (@s:=0) AS s ) s WHERE infotext IS NULL ORDER BY grouptext; UPDATE myTable AS target INNER JOIN supportGroupSeqcalculation AS ordered ON ordered.supfault_id = target.supfault_id SET sequence = seq; DROP TEMPORARY TABLE supportGroupSeqcalculation; We can get into temporary table specific order and record it as sequence value. It is not necessarily to drop temporary table, it exists only in current session.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mysql, increment" }
Print value of GDB setting How to print the value of GDB setting? For example if I use the command set width 5 Later on I want to know the value of `width`, how to do that? I tried print width print &width set width? but none of these printed the value `5`. Any help will be appreciated.
Use `show width`. For example: (gdb) set width 100 (gdb) show width Number of characters gdb thinks are in a line is 100.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "gdb" }
Utilizing my RAM more efficiently I just upgraded my RAM on my server from 4 GB to 16GB, I have 2x Dual Core 2.4 Ghz processors and would like to utilize that extra RAM if possible to setup some additional caching, or just anything that I can do. I only use this server to serve web sites, nothing special. I'd like the server to be able to handle as much load as possible... what would you recommend? **update** I should say that I'm running Ubuntu in a LAMP environment.
Your use case will determine your mileage from each of the following, though I think they're in order of bang-for-buck: 1) Database: Mysql has lots of different cache parameters, and you can get a lot of extra db performance by getting them just right. The thing is, it's different for every app. One helpful tool here is mysqltuner. 2) Bytecode: Most PHP accelerators (APC, XCache, eAccellerator) cache bytecode in memory, which speeds up your PHP execution by skipping the compilation step. This probably won't use too much RAM, but it's a good step if you're looking to increase performance. Some of these also let you access a shared cache through code. 3) App: You could choose one of the accelerators that offers explicit app cache, and Memcached also does this very well. The problem with this is that you have to write your app to take advantage of it. This can be really nice, but expensive (dev time), so make sure you profile first.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 1, "tags": "ubuntu, web server, memory, cache" }
vue-konva how save layer with image and line like jpg, png have v-group with image and lines on layer,stage like this: <button @click="export"></button> <v-layer ref="layer"> <v-group> <v-image :config="configBackground"></v-image> <v-line v-for="line in lines" :key="line.id" :config="{ stroke: 'red', points: line.points, }" /> </v-group> </v-layer> in my function i try get dataurl from stage to save img: export(e) { //console.log(e.target.getStage()) let dataURL = e.target.toDataURL() console.log(dataURL) // this.download(dataURL, "img.png") }, If i click button, i get **e.target.toDataURL is not a function** How can i get dataURL to save image?
this work for me let stage = vm.$refs.stage.getNode() let dataURL = stage.toDataURL()
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vue.js, save image, konva, vue konva" }
Transistor as a switch for 3A collector current I am using: * ATtiny10 w/ 10Ohm Resistor in series to drive Base of transistor * Transistor is ZTX688B * Vcc is 5V and 3A source * Load is a Raspberry Pi connected to Collector !schematic simulate this circuit - Schematic created using CircuitLab The ATtiny is programmed to turn on the Base for 10 seconds and then turn it off for 5 seconds. When I run the circuit it turns on briefly but only manages to 100-200mA (not enough to fully turn on the Pi. How can I make this work? The transistor is rated to handle 3A and up to 12V. NOTE: I am also open to suggestions of replacing parts. I just need to control the Pis power supply with a MCU.
From your schematic, the current flowing from PB0 to T1's base-emitter junction is \$I_B = (5V - 0.6V) / 10\Omega = 440mA\$, which is extremely high for a MCU-pin's drive capability. Thus PB0 may limit the output _(I'm not sure, but I hope)_. To saturate the transistor, a base current of \$I_{Bs} = \frac{I_C}{ (\beta_{min}/10)}\$ is sufficient _(I cannot prove this, but this comes from my experiences)_. From your circuit, this base current is 3000mA / (400/10) = 75mA, which is still extremely high for MCU's port/pin. The most efficient way is to use an N-Channel MOSFET _(with logic-level gate)_ instead.
stackexchange-electronics
{ "answer_score": 3, "question_score": 0, "tags": "transistors, switches, raspberry pi, attiny" }
Can't get bootstrap button ID from button on a table row I'm using Bootstrap and thought I'd be clever and drop some buttons inside a table. Alas, nothing happens. Button state changes but other than that, no errors, no alerts, no response at all. **My abbreviated table** <table class="table"> <tr> <td>Entry of some sort</td> <td><button type="button" class="btn btn-default btn-xs" id="edit_Button">Edit</button></td> <td><button type="button" class="btn btn-default btn-xs" id="delete_Button">Delete</button></td> </tr> </table> **jQuery for my button** $( document ).ready(function() { $(".table .btn").click(function(e){ e.preventDefault(); var id = $(this).attr('id'); alert(id); }); });
Define function inside `$(document).ready(function ()` Since your buttons created dynamically to the DOM, the click event will not be available for these buttons. In this case, event delegation will help you to attach that event. Try this $(document).ready(function () { $(document).on('click', ".table .btn", function (e) { e.preventDefault(); id = $(this).attr('id') alert(id); }); }); DEMO
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jquery, button, twitter bootstrap 3" }
What's the wrong with this mysql full-text query? (SELECT COUNT( `ad_general`.`id` ) as no FROM (`ad_general`) WHERE MATCH (title, body) AGAINST (' +stack* 'IN BOOLEAN MODE) AND `user` = '1') ) AS count This query gives me this error: > # 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use > > near 'AS count' at line 17 But this one is working as i expected. SELECT COUNT( `ad_general`.`id` ) as count FROM (`ad_general`) WHERE MATCH (title, body) AGAINST (' +stack* 'IN BOOLEAN MODE) AND `user` = '1') What's wrong with the first version ? I need it to work like in first one.
You can't name a query like that. You can fix this by putting `select` in front: select (SELECT COUNT( `ad_general`.`id` ) as no FROM (`ad_general`) WHERE MATCH (title, body) AGAINST (' +stack* 'IN BOOLEAN MODE) AND `user` = '1') ) AS count Or you could just do: SELECT COUNT( `ad_general`.`id` ) as `count` FROM (`ad_general`) WHERE MATCH (title, body) AGAINST (' +stack* 'IN BOOLEAN MODE) AND `user` = '1')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql, subquery, full text search" }
In Julia, how to skip certain numbers in a for loop In the julia for loop, I want to skip the numbers that can be divided by 500. For example, in the loop below, I want to skip i=500, 1000, 1500, 2000, 2500, ..., 10000. How can I do that? n=10000 result = zeros(n) for i = 1:n result[i] = i end
just use `continue`: for i = 1:n iszero(i%500) && continue result[i] = i end
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "julia" }
MONTHNAME in Portuguese MYSQL I´ve got a huge query (In a PHP file) that gives me a monthname from some dates: CASE A.STATUS WHEN 'Cancel' THEN LEFT(MONTHNAME(DT_CANCEL),3) WHEN 'About to cancel' THEN LEFT(MONTHNAME(DATA_REGISTER),3) END AS MONTH_CANCEL, Is there a way to insert my language inline with MONTHANAME? Something like: WHEN 'Cancel' THEN SET LANGUAGE Portuguese LEFT(MONTHNAME(DT_CANCEL),3) I don´t want to write case for eveymonth to transform 'Dec' to 'Dez' and so on, this will take too long.
Unfortunately in MySQL this cannot be done dynamically within a query. From the documentation : > The language used for the month name is controlled by the `lc_time_names` system variable. You need a separate SQL command to change the setting : SET lc_time_names = 'pt_PT'; SELECT MONTHNAME('2018-12-28') AS 'Month'; The value of the `lc_time_names` persists for the lifetime of the MySQL session.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "mysql, sql, string, date" }
Flatten RDD[(String,Map[String,Int])] to RDD[String,String,Int] I am trying to flatten an RDD[(String,Map[String,Int])] to RDD[String,String,Int] and ultimately save it as a dataframe. val rdd=hashedContent.map(f=>(f._1,f._2.flatMap(x=> (x._1, x._2)))) val rdd=hashedContent.map(f=>(f._1,f._2.flatMap(x=>x))) All having type mismatch errors. Any help on how to flatten structures like this one? EDIT: hashedContent -- ("A", Map("acs"->2, "sdv"->2, "sfd"->1)), ("B", Map("ass"->2, "fvv"->2, "ffd"->1)), ("c", Map("dg"->2, "vd"->2, "dgr"->1))
You were close: rdd.flatMap(x => x._2.map(y => (x._1, y._1, y._2))) .toDF() .show() +---+---+---+ | _1| _2| _3| +---+---+---+ | A|acs| 2| | A|sdv| 2| | A|sfd| 1| | B|ass| 2| | B|fvv| 2| | B|ffd| 1| | c| dg| 2| | c| vd| 2| | c|dgr| 1| +---+---+---+ **Data** val data = Seq(("A", Map("acs"->2, "sdv"->2, "sfd"->1)), ("B", Map("ass"->2, "fvv"->2, "ffd"->1)), ("c", Map("dg"->2, "vd"->2, "dgr"->1))) val rdd = sc.parallelize(data)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "scala, apache spark, apache spark sql" }
What does this ground cable connect to? so i was filming for youtube and came across this random ground wire that wasn't bolted to anything, it's on a '99 jeep wrangler TJ, any of y'all know where this goes? ![Random ground wire]( ![Random Ground wire #2](
It should connect to the hood/bonnet. I got this photo from here I guessed it was from the hood and did a google search "jeep wrangler hood earth strap" You can see the bolt hole in your photo. Sometimes bad electrical connections on things like hinges can increase radio noise. The earth strap electrically bypasses the hinge. ![enter image description here](
stackexchange-mechanics
{ "answer_score": 3, "question_score": 2, "tags": "jeep, wrangler, ground, wire" }
SQLite Android . unable to open database file I found a lot of question about this problem, but i can't fix it. I have a sqlite db in assets folder: assets/data/data/{package_name}/databases/mydb.db I can open database and read data before change one table structure. I try to uninstall the app and reinstall again, but i get the same exception. What can i do now? Thanks in advance **EDIT** // The Android's default system path of your application database. private static String DB_PATH = "/data/data/{mypagackename}/databases/"; private static String DB_NAME = "mydb.db"; Open database (Before change table structure, adding some fields, it doesn't work) public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); }
Basically, you can't use database right from the assets, you have to copy it over into internal data storage first and open it from there
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 8, "tags": "android, database, sqlite" }
How to append to a file? I am trying to append some text to the end of a file in Mac OSX having a .conf extension. I am using the following code to do that: open NEW , ">>$self->{natConf}"; print NEW "$hostPort = $vmIP"; where $self->{natConf} = \Library\Preferences\VMware Fusion\vmnet8\nat.conf So basically this is a .conf file. And even though its not returning any error, but it is not appending anything to the end of the file. I checked all the permissions, and read-write privilege has been provided. Is there anything I am missing here.
First of all `use strict` and `use warnings`. This would have thrown errors and warnings for your code. On Mac OS the delimiter in a path is `/` like in other unix-like systems not `\`. To asign a string to a variable use quotation marks. Do not use `open(2)` but `open(3)` (the arrow operator does not work in your usage of open anyway) and it is considered bad practice to use bareword filehandlers. use strict; use warnings; # your code here $self->{natConf} = '/Library/Preferences/VMware Fusion/vmnet8/nat.conf'; # more code here open my $fh, '>>', $self->{natConf} or die "open failed: $!\n"; print $fh "$hostPort = $vmIP"; close $fh; # rest of code here
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "perl, perl module" }
Is there a software capable of creating native mobile apps with JavaScript, HTML and CSS only? There is a ton of software, so diverse and sophisticated that almost capable of making coffee themselves. We have Electron.JS which builds cross platform desktop apps with JavaScript only. But has there been a software around which does the same with creation of mobile native apps with web technologies like JavaScript, HTML, and CSS (apart from React Native which imposes own restrictions and syntax)? I still cannot find one that would be a lightweight compilator, a converter, whose existence is logical and of great demand.
So far the only option I could find is the creation of a hybrid app with the help of Apache Cordova shell, which is free, cross-platform, and is based on HTML5, CSS3 and JavaScript technologies. To get away from attaching necessary modules througth cmd console, we can simply download Visual Studio Community edition of 2017 or higher versions, including under installation a module called 'Develompment with JavaScript". Hybrid apps account for 6% of all apps in public app stores. Another revolutionary way is a newly introduced option by Google allowing to publish Progressive Web Applications (PWA) onto Google Play Store.
stackexchange-softwarerecs
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Network Manager not working when installing ubuntu-desktop on a Ubuntu 18.04 Server installation I have installed a Ubuntu 18.04 Server to be able to install on a RAID, followed by a `ubuntu-desktop` install. The problem is that the Network Manager does not work now, it does not allow me to see or modify any of the network configuration. The network connection is displayed with the name "Wired Unmanaged". Maybe the server distro uses another system to configure the network that is not supported by NetworkManager? How can I move to a standard Desktop configuration of the network?
Are you aware that Ubuntu 18.04 introduced Netplan? If you want to use network manager my understanding is you need to edit the netplan configuration file in `/etc/netplan`. Specifically to enable network manager your `/etc/netplan` would look like this: network: version: 2 renderer: NetworkManager You then need to run netplan generate netplan apply After that, network manager should work as you expect.
stackexchange-askubuntu
{ "answer_score": 13, "question_score": 10, "tags": "networking, server, network manager, desktop environments, 18.04" }
How to get the number of rows in a resultset using medoo I would like to know how to get the number of rows in a resultset for this statement: $data=$db->query("SELECT name FROM users")->fetchAll(); I need something similar to `mysqli_num_rows` but using `medoo`. thanks for your help!
Since the `query()` method returns an array, just use php's count() function to determine the number of records returned (do not set the recursive mode).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "php, mysql, medoo" }
Добавление элемента в массив, который определяется классом Swift Есть определенный класс class Weapon { var name: String var atack: Int var def: Int var image: UIImage init(name:String, atack:Int, def:Int, image:UIImage) { self.name = name self.atack = atack self.def = def self.image = image } } Так же есть массив, который определяется классом выше var weapon: [Weapon] = [] Изначально пустой. Вопрос такой, как добавить новый элемент в массив, при этом иметь возможность сохранить его через userDefaults. С помощью append добавить можно, но тогда не сохраняются данные добавляю так в массив, но тогда при сохранении выдает ошибку let we = (Weapon(name: "ddadadadaad", atack: 24, def: 34)) weapon.append(we)
В вашем нижнем куске кода в инициализаторе отсутствует UIImage... может проблема в этом? При добавлении переменной класса Weapon в массив через append - все ее содержимое должно сохранятся... иначе какой во всем этом добавлении смысл?
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xcode, swift" }
How to differentiate tag popularity in a cloud tag? I never implemented a tag cloud before, so I have some ideas on how to do this. I was thinking of differentiating between them using CSS, and playing around with font sizes. But, how many CSS classes should I create? I can think of the following popularity "info": * normal * has some activity * popular * very popular and use different font sizes for them. But, some websites seem to differentiate between them even more. Is my idea of differentiating tags bad? If I'd want to add more categories, I'd have to add more classes. Are there other ways of doing this that could be more efficient?
You don't have to name them. You can just create classes `popularity1` to `popularityX` where X is the number of differentials you want. You can adjust this number if you like. Just group the results differently and create extra css classes. Alternative solution, although I wouldn't recomment this: You could nest classes with a relative font size, like 110%. For every higher popularity, you nest the elements one layer deeper.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "language agnostic" }
Split a string entered by the user in arguments how can I split a string entered by the User in arguments? assuming that a user type: test1 test2 test3 how can i separate each entered values, in a way that i can access these values separately?
Use getline with stringstream to extract characters from user input and stores them into string until the delimitation you inform. sequentially use a vector to store the extracted characters. something like this: void split(std::vector<std::string> &args, std::string userInput, char delimiter) { std::stringstream ss(userInput); std::string buf; while(getline(ss, buf, delimiter)) { args.push_back(buf); } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++" }
document.write() Only Displaying First Item in IE7, IE8 I have an image that when clicked, opens in a new window displaying the larger image and a print button. The issue I am having is that the new window only displays the first html element in IE7 nad IE8. Switching the order of the syntax proves this. Is document.write() incorrect for this type of situation? <script type="text/javascript"> function openWin() { var myWindow=window.open('','','width=855,height=885,scrollbars=yes,toolbar=yes'); myWindow.document.write("<img src='/sites/default/files/PipelineChart_2012_large.jpg' height='785' width='835' style='float:left;' '/><input type='button' onClick='window.print()' value='PRINT'style='float:left; clear:both;'/>"); } </script>
You have an extra quote before the closing `/>` on your img tag in your document.write call: myWindow.document.write(" <img src='/sites/default/files/PipelineChart_2012_large.jpg' height='785' width='835' style='float:left;' /> <input type='button' onClick='window.print()' value='PRINT'style='float:left; clear:both;'/>");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, internet explorer 8, internet explorer 7" }
Как поменять текст описания сайта на WordPress ![введите сюда описание изображения]( Как поменять описание сайта, который сделан на вордпрессе?
В `header.php` изменить содержимое тега `< meta name="description" content="Содержимое мета-тега">` на нужное вам. Либо в админке: Настройки - Общие - Краткое описание
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wordpress, seo, поисковые системы" }
how to add extensions to vendor manually in yii2 i want to add < in yii2 . i copyed vendor from instagram-php-scraper project to yii2's vendor this is my error : > Class 'InstagramScraper\Instagram' not found project extensions(instagram-php-scraper) is not developed for yii2 . What other changes should I do?
I suppose you have have used composer to install Yii2; Use composer to add the required package: `composer require raiym/instagram-php-scraper` See also : < This way, the classes will be added to composer autoload functionality
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "yii2, yii2 advanced app" }
Parâmetro this fora do esperado dentro de uma função anônima Fiz um código para treinar manipulação de Arrays e JavaScript. Eis parte do código: function Playlist (nome ='Playlist'){ const musicas = []; function addMusicas(...novasMusicas){ novasMusicas.forEach(function(musica){ // aqui o this é o objeto global this.musicas.unshift(musica); }) } return { nome, musicas, addMusicas, } } const playlist01 = new Playlist(); playlist01.addMusicas('Dream on', 'Drive', 'Sex and Candy'); Percebam que quem executa a função dentro do `forEach` é o objeto global. Sem o `this`, o escopo é o do objeto criado por `Playlist()`. Alguém pode me explicar por que isso ocorre?
Isso ocorre pois quando uma função não é uma propriedade de um objeto, ela é invocada com o paramêtro `this` ligada ao objeto global. Existem varias formas de escapar disso, poderia utilizar bind, call, apply, that. Mas pelo fato da pergunta ter a tag ES6, recomendo que use uma arrow function, pois ela conserva o `this` de onde ela foi criada. Veja como ficaria: function Playlist (nome ='Playlist'){ const musicas = []; function addMusicas(...novasMusicas){ novasMusicas.forEach(musica => { // perceba aqui a sintaxe da criação de uma arrow function this.musicas.unshift(musica); }) } return { nome, musicas, addMusicas, } } const playlist01 = new Playlist(); playlist01.addMusicas('Dream on', 'Drive', 'Sex and Candy'); console.log(playlist01.musicas);
stackexchange-pt_stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "javascript, ecmascript 6, scope, contexto" }
How do you get the width and height of a surface view I am developing a game.I have drawn images on a surface view which is residing in a relative layout.I want that my game's look and feel should be the same in all resolutions. So now i want to measure the surfaceview/canva's width and height so that I can launch the images in proper proportion rather than hard coded values. But I am unable to retrieve the height and width so please help me. I tried canvas.getWidth() and all but it returns 0.
You probably need to do something like this: Determining the size of an Android view at runtime
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "android" }