INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
multiple statements after if statement I have an awk line to calculate an average that works fine but when I put it into an if statement, I get a syntax error referring to the part with "END". I want to calculate the average only if certain conditions are fulfilled. Line for calculating average that works: `awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }' input.txt` Line for calculating average after if statement which doesn't work: `awk '{if ( $1 > 5 ) { {sum += $2; n++} END { if (n > 0) print sum / n; }}}' input.txt` I would like to know where the error is, changing the type and number of brackets did not help.
try this awk '$1>5 {sum+=$2; n++} END {if(n) print sum/n}' file
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "awk" }
Python analyze requests I'm interested in building an app that lets developers see http/https requests from their machine real time. Something like firebug, but it catches requests made not only from a browser but also a shell. My question is, is there any python packages that allow me to tap into the module that makes each request ? I'm not very clear as to what this is called but its basically like firebug or wireshark.
Such activities are often referred to as packet sniffing. See Packet sniffing in Python (Windows)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, http" }
FFMPEG video scale & add image background I want to create a video with ffmpeg. There are background image(450pxx800px) and video(unknown sizes). I want scale to video 450x800 and put the image video background. I try this code but when finish job, video create without audio. what must i do? ffmpeg -loop 1 -i C:\Users\drt\Desktop\media\background\bg4.png -vf "movie='C\:\\Users\\drt\\Desktop\\media\\fX4I0jW8_fX4I0jW8.mp4',scale=450:800:force_original_aspect_ratio=1,pad=450:800:0:264:color=black@0,setsar=1[inner];[in][inner] overlay=0:0[out]" -ss 00:00:00.000 -to 00:00:15.000 -y C:\Users\drt\Desktop\media\2q4pyZpSCE7syzJMj.mp4
You need to map the output streams. Also, no need to use the movie filter: that method is from a billion years ago. ffmpeg -y -i C:\Users\drt\Desktop\media\fX4I0jW8_fX4I0jW8.mp4 -i C:\Users\drt\Desktop\media\background\bg4.png -filter_complex "[1:v]scale=450:800:force_original_aspect_ratio=1,pad=450:800:0:264:color=black@0,setsar=1[inner];[0:v][inner]overlay=0:0[video]" -map "[video]" -map 0:a -c:a copy -to 00:00:15.000 C:\Users\drt\Desktop\media\2q4pyZpSCE7syzJMj.mp4
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, ffmpeg, video processing" }
How to solve equality equation through matlab solver? I have a question related to basic mathematics, but with Matlab solving method. Here is the question: y = 5; for x=0.01:100 F = 3*x + y - 2*x^2; end From the above iterative equation I want to find the max [F] value and its relative [x]. Is it possible to solve it through matlab solvers. Could you please help me to solve this problem?
For unconstrained non-linear optimization (according to your last edit) use `fminsearch` to solve your problem. It would be something like this: F = @(x) 3*x + y - 2*x^2; xini = 5; %initial value to the solver [xsolu Fsolu] = fminsearch(@F,xini) To control the options, parameters of solver see `optimset` opts = optimset('MaxFunEvals',10e4, 'MaxIter', 10e4) [xsolu Fsolu] = fminsearch(@F,xini, opts) * * * The solution according to your original formulation would be: x=0.01:100; F = zeros(length(x),1); for ii = 1:length(x) F(i) = 3*x(i) + y - 2*x(i)^2; end xsolu = max(F); Fsolu = F(x == xsolu); Which is quite inefficient approach, to say nothing more.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -4, "tags": "math, matlab, symbolic math" }
Has anyone tried/had trouble with being able to build the Redbeard "Pages" tutorial project? If I download the source and build it works fine, but if I do it myself Xcode won't find the default.inc.json file. If I alter the path to /default-theme/default.inc.json then that particular file is found, but other theme files aren't Clearly, for some reason my set up is causing grief. However, analysing the directory structure of my app and the source comes up with no differences. Has anyone run into the same?
Are you trying to set the 'root' theme file? If so it should be named 'theme.inc.json'. From there you should add in your own theme files and include files. See this for further information about themes and the general structure. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, redbeard ios" }
Outlook reports "no default gateway" on Lan Domain I have a local domain with DC win2003 and an exchange server also added to the domain. When I connect a pc to the domain and put the ip , mask and DNS (the same as DC), outlook dont get directly the users credentials to log him in. I manage to resolve it adding a default gateway to NIC's the ip of the exchange server. This approach is wrong and I have to face it now that I really need a default gateway to an other network. What do I do wrong? With my little experience I believe is the DNS server fault. Thank you for your help in advance.
This is a common issue with Outlook 2007 and later (I suppose you use one of these versions, because Outlook 2003 doesn't have these problems). It requires a default gateway to be set. Try the registry fix or use the "Fix it" from MS, I'd say.
stackexchange-serverfault
{ "answer_score": 2, "question_score": -1, "tags": "windows, domain name system, windows server 2003, exchange 2003" }
Copy a div to a text file needing some help here with jquery. I have a div i want to copy to a text file. This div has a class, and inside this div, there is some other divs and some other elements, but no one with the same .class as the main div. I'm not sure if i am able to use .clone() So what i need is something like this: $('.myClass').misteriousCopyFunction('toTextFile'); //as i said, i'm not sure about this. and my html looks like this ... <div class="myClass"> *lots of stuff* *lots of stuff* *lots of stuff* </div> ... it's just a little piece of the Html code to output to a new file in the current folder. Sorry if i said something stupid =P
You can do this using some new HTML features currently only available in Chrome I believe. Basically you save the contents of the DIV using the FileSystem APi and then create a link that has a `download` attribute pointing to the file.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, file, html, clone" }
Do trees really get a large share of their mass from the carbon in the air? I remember hearing that trees and other plants actually obtain a large amount of their mass from the carbon floating in the air, not the ground beneath them. Does the makeup of air actually contain enough carbon to support this theory, and is a tree's surface area actually large enough to obtain the amount of carbon it needs directly from the air?
The vast majority of a tree's _carbon_ comes from the air, which averages 0.03-0.04% by volume (300-400 ppmv) CO2. This is fixed through photosynthesis and eventually stored as glucose which the plant can then use for its metabolism. Doing some quick math, this means that in order to produce 1 kilogram of carbohydrates (e.g. cellulose) a plant needs to process on the order of 2000-3000 cubic meters of air (and ≈550 g or mL of H2O), which would fill a cube measuring 13-14 meters on a side. Note this is an ideal figure; a plant's fixing efficiency will likely fall as it depletes the air of CO2. Plants do take a great deal from the ground, namely water, fixed nitrogen (for proteins), phosphorous (for nucleic acids), and several ions (sodium, potassium, calcium, among others)
stackexchange-biology
{ "answer_score": 33, "question_score": 37, "tags": "botany, photosynthesis" }
How can I get user if i have auth_token I use `"gem 'devise', '~> 4.2'"` and I need to get current_user with some auth_token, but method `"User.find_by_authentication_token"` is deleted. What method can i use instead or just how can i get current user.I use json api.
Try: User.find_by(authentication_token: "abcd1234") That is not provided by Devise, but Rails (more specifically ActiveRecord). Documentation here. The dynamic `find_by_attribute_name` methods were removed from ActiveRecord.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby, devise, ruby on rails 5" }
Cannot render Handlebars views in nodejs So i have been trying to follow some guides online to debug and fix my situation however it keeps not loading anything. so here i am to ask you guys if there is something wrong with the code: var express = require('express'); var app = express(); var exphbs = require('express-handlebars'); var request = require('request'); var async = require('async'); var apiOptions = { useRedis: false, hostname: '127.0.0.1', port: 6379, cacheTTL: 7200 }; var lolapi = require('lolapi')('4df431ee-5631-4db3-b7d5-771c8aaf02f0', 'oce', apiOptions); app.engine('handlebars', exphbs({defaultLayout: 'main'})); app.set('view engine', 'handlebars'); app.get('/', function(req, res) { res.render('index', { title: 'Welcome to Api' }); });
according to the documentation you need to have the structure . app.js views home.handlebars layouts main.handlebars then set **views/layouts/main.handlebars** <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Example App</title> </head> <body> {{{body}}} </body> </html> and you index.handlebars in **views/index.handlebars** <h1>App Title: {{{title}}}</h1>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js, express, handlebars.js" }
How To Restrict Access To Custom WordPress Template I have a custom template that I built which manages a separate table inside a WordPress database. I have had success restricting access unless logged in on all other pages (including existing custom templates) accept my custom template (page id 9597) using this code: add_action( 'template_redirect', 'add_restrict_access'); function add_restrict_access(){ if( ! is_user_logged_in() && is_page( 9597 ) ) { wp_redirect( '/wp-login.php' ); exit; } } If I change the is_page number to any other page ID, the redirect works. Anyone have any ideas?
SSL cert issue. Page was viewable without SSL, as soon as I added https it started working properly. Weird.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, wordpress, template redirect" }
Uniqueness quantification in propositional logic I'm trying to define the Uniqueness quantification $\exists ! $ in propositional logic. I am aware that it is possible to define it in predicate logic, as the Wikipedia page (and many answers here) shows, but as propositional is weaker, can we define this quantification in propositional? If not, why not?
There are no quantifiers in propositional calculus.
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "logic, propositional calculus, first order logic, quantifiers" }
How can I "cache" a variable in Bash? I have a bash script which is run every 10m by `cron`. The script performs an expensive calculation for some value (say variable x=value). I need to "cache" this value for 2-3 hours. What are possible solutions to this problem? I tried memcached but it doesn't seem to play well with bash.
Write a second script that does the actual calculation and saves the result to a file: # calculate $curval printf '%s' "$curval" > /var/foo/value.txt Schedule it with `cron` to run every 2-3 hours. In the "every 10 minutes" script, simply read the current value from the file: curval=$(< /var/foo/value.txt) A nice refinement is to call the calculation script from the "every 10 minutes" script if the `value.txt` file doesn't exist yet. You could even make it add the `crontab` entry if it's missing.
stackexchange-unix
{ "answer_score": 10, "question_score": 2, "tags": "bash, cron" }
How to know if an anchor accepts withdraws from their stellar.toml? When looking at an anchors stellar.toml files, how do we know that they allow withdraws and also what version of SEP it allows, either SEP 24 or SEP6 or both?
SEP-6 requires a `TRANSFER_SERVER` URL field in the stellar.toml, in SEP-24 it is named `TRANSFER_SERVER_SEP0024`. Both SEPs describe an _/info_ endpoint (SEP-6 here, SEP-24 here), so you can presumably get all details at _
stackexchange-stellar
{ "answer_score": 0, "question_score": 0, "tags": "anchor" }
How to use output from an action as an expression in a if-condition for a Github Action workflow? I am building an workflow where an action provides a condition for a step in the workflow. How can I use this value? The value from the action is blank and therefore evaluates to false and nothing is ever deployed... jobs: build: steps: - id: verify name: verify if artifact is eligable for deployment uses: my.org/my.action.group/[email protected] - name: release candidate run: echo release candidate - "${{ steps.verify.is-release-candidate }}" - name: deploy run: ... if: steps.verify.is-release-candidate debug release candidate: Run echo release candidate - "" release candidate - action.yml: .... outputs: is-release-candidate: description: true if this new version can be auto deployed, false if not
You almost got it right, except one small detail - you skipped `outputs` part when trying to access `is-release-candidate` \-- correct version: `steps.<id>.outputs.<name>`. - name: release candidate run: echo "release candidate - ${{ steps.verify.outputs.is-release-candidate }}" - name: deploy run: ... if: steps.verify.outputs.is-release-candidate
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "github actions" }
Rails: Paperclip with multiple placeholder images? I've been trying to experiment with having avatars for users in my app, and I've set this up where a user can upload an image using Paperclip. Paperclip has a nice default functionality where you can define a placeholder image when the user has not uploaded an image. What I'm wondering is, is there any way to create a set of placeholder images and have paperclip choose one at random when the associated record is created? IE so not all the "no avatar" icons have to be identical? Thanks!
My best guess for how to accomplish this would be to "override" how you access your avatar images. Maybe something along the following: module UserHelper def avatar_url(user) user.avatar ? user.avatar.url : random_avatar_url end def random_avatar_url ... end end This way you can use one interface to access the existing avatar or a randomly chosen one from your views. You don't want to use `random_avatar_url` directly from your views, so maybe private or protect it to make sure others know.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ruby on rails, ruby on rails 3, random, paperclip, placeholder" }
Inequality. $\frac{1}{\sqrt{x^2+yz+3}}+\frac{1}{\sqrt{y^2+zx+3}}+\frac{1}{\sqrt{z^2+xy+3}} \geq 1$ Prove that : $$\frac{1}{\sqrt{x^2+yz+3}}+\frac{1}{\sqrt{y^2+zx+3}}+\frac{1}{\sqrt{z^2+xy+3}} \geq 1$$ if $x^2+y^2+z^2 \leq9$. I try to apply Cauchy-Buniakowski and I obtaine the followin: $$\sum_{x,y,z}{\frac{1}{\sqrt{x^2+yz+3}}}\cdot \sum_{x,y,z}{\left(\sqrt{x^2+yz+3}\right)}\geq 9$$ So I have to prove that : $$\displaystyle\frac{9}{\sum_{x,y,z}{\left(\sqrt{x^2+yz+3}\right)}} \geq 1$$ if $x^2+y^2+z^2 \leq9$. Another trying : $$\left(\sum_{x,y,z}{\sqrt{x^2+yz+3}}\right) \leq \sqrt{\left(\sum{x^2+yz+3}\right)(1+1+1)} $$ so we have to prove that: $$\frac{9}{\sqrt{\left(\sum{x^2+yz+3}\right)(1+1+1)}} \geq 1$$ hence: $$3(x^2+y^2+z^2+xy+yz+zx+9) \leq 81$$ or $$(x^2+y^2+z^2+xy+yz+zx+9) \leq 27$$ or $$x^2+y^2+z^2+xy+yz+zx \leq 18$$ $$x^2+y^2+z^2+xy+yz+zx \leq 2\left(x^2+y^2+z^2\right) \leq 2 \cdot 9 =18.$$ Yes, it is ok :) thanks :)
I try to apply Cauchy-Buniakowski and I obtaine the followin: $$\sum_{x,y,z}{\frac{1}{\sqrt{x^2+yz+3}}}\cdot \sum_{x,y,z}{\left(\sqrt{x^2+yz+3}\right)}\geq 9$$ So I have to prove that : $$\displaystyle\frac{9}{\sum_{x,y,z}{\left(\sqrt{x^2+yz+3}\right)}} \geq 1$$ if $x^2+y^2+z^2 \leq9$. $$\left(\sum_{x,y,z}{\sqrt{x^2+yz+3}}\right) \leq \sqrt{\left(\sum{x^2+yz+3}\right)(1+1+1)} $$ so we have to prove that: $$\frac{9}{\sqrt{\left(\sum{x^2+yz+3}\right)(1+1+1)}} \geq 1$$ hence: $$3(x^2+y^2+z^2+xy+yz+zx+9) \leq 81$$ or $$(x^2+y^2+z^2+xy+yz+zx+9) \leq 27$$ or $$x^2+y^2+z^2+xy+yz+zx \leq 18$$ $$x^2+y^2+z^2+xy+yz+zx \leq 2\left(x^2+y^2+z^2\right) \leq 2 \cdot 9 =18.$$
stackexchange-math
{ "answer_score": 3, "question_score": 6, "tags": "inequality" }
Prove that the given map is not a covering map. ![enter image description here]( This problem is from Munkres' Topology section 53. I understand how p is not a covering map if U is connected. How is it not a covering map when U is not connected.
The (continuous) path $\gamma:[0,2\pi]\to S^1$ defined by $$\gamma(t)=e^{-it}$$ does not "lift" to any continuous path $\tilde{\gamma}:[0,2\pi]\to (0,\infty)$ starting at $\tilde{\gamma}(0)=2\pi$ (such a path would have the expression $\tilde{\gamma}(t)=2\pi-t$, and then $\gamma(2\pi)= 0\not\in (0,\infty)$).
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "general topology, covering spaces" }
CI with iOS (Objective-C) projects and Hudson At our company we use Hudson for our CI, we use a lot of different languages and they all work well on linux. We don't do this for our iOS projects. I know we can, using a mac with OSX and build projects using the terminal (command line). But can this be done using for instance Debian? Can one also run the unit tests xCode 4 creates? The reason I am asking this is because I need to know that ordering a new mac mini (or any other mac) is necessary in order to comply with CI.
it sure can be done (i've tried it some time ago) - however, it is questionable whether is it worth the hassle. It is (was) far from straightforward process and from the business point of view the acquisition of a mac mini is way more feasible (i think). However, if you seek challenges you might give it a try, there is a project on google code called iphone-dev that should get you started.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "objective c, ios, continuous integration, hudson" }
I know that 3 is a primitive root of $31$. How can I solve $3^b \equiv 22$? I'm trying to solve $$3^b \equiv 22 \mod 31$$ I know that this is of course equivalent to $$b \equiv L_3(2) + L_3(11) \mod 30$$ but I don't know how to solve those either. I can obviously just compute each exponent of $3$ by hand and hope to get lucky, but I'm looking for a shorter method.
Hint: $22\equiv -9\pmod{31}$, so it is enough to find $L_3(9)$ and $L_3(-1)$. For $L_3(-1)$, you can use the fact that $-1$ is the unique element of order $2$ in the multiplicative group.
stackexchange-math
{ "answer_score": 6, "question_score": 1, "tags": "group theory, number theory, finite groups, cryptography, discrete logarithms" }
Is Paul saying that Jews will be saved in Romans 4:16? > So the promise is received by faith. It is given as a free gift. And we are all certain to receive it, whether or not we live according to the law of Moses, if we have faith like Abraham's. For Abraham is the father of all who believe. > **Romans 4:16 NLT** Does this passage in particular mean that Jews and others belonging to Abrahamic faiths will be saved?
Most certainly not. > And we are all certain to receive it, whether or not we live according to the law of Moses, if we have faith like Abraham's. It hinges on the conditional at the end of the sentence, `...if we have faith like Abraham's`. Abraham didn't just 'have a faith', he had faith ('trust') in what God said. Faith has an object, and from the rest of Paul's development, it is specifically faith in Christ alone. The issue is who you have faith in. Also, 'faith' here does not mean being a member ofa religion or a group, but specifically, trusting a specific deity, namely Jesus.
stackexchange-hermeneutics
{ "answer_score": 1, "question_score": 2, "tags": "romans, soteriology, judaism" }
Active rigid bodies not colliding with passive ones I am trying to do pwnisher's community challenge. I downloaded base animation template (Blender). In blender the animation is playing just fine but when I add new objects for collision (rigid body : passive), the falling ball passes through it. Here are some settings that I'm using : Ball : * Rigid body type : active * Collision shape : sphere Cube : * Rigid body type : passive * Collision shape : mesh I want the ball to collide with the cube. I tried dropping a object on other objects in another blend file and it works fine (I tried adding new objects and saw if those collide). I am totally new to simulations in blender. What could be the problem ? .blend file : < Solutions I've tried so far: * Tried deleting all bakes. * Tried changing steps per second from 10 to 60. * Tried applying scale to the newly added cube (ctrl+A).
_**The solution does not work for 2.82**_ 1. Select your ball, and in the timeline delete all keyframes (so the physics can do its work). 2. uncheck the "animated" flag here: ![enter image description here]( 3. go to scene properties: hit "delete all bakes" in rigid body world 4. for your ball change sensitivity -> collision margin to 0 ![enter image description here]( run the animation you get this: ![enter image description here](
stackexchange-blender
{ "answer_score": 1, "question_score": 1, "tags": "rigid body simulation, collision, rigidbody" }
Mysql table format for store last 30 days Data I want to add this data : id,prod_name,value,date 1,samsung,340,02-02-2014 2,nokia,390,02-02-2014 3,samsung,340,03-02-2014 4,samsung,440,04-02-2014 Main problem is create each rows for each day records......So any way possible to no need to create every day record for each product i want to save last 30 days data.
Could you not truncate the data every day for any data that is older than 30 days?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "mysql" }
Get rid of blinking on css 3d transform Here is example: < On chrome I've got ugly blinking when pressing flip button. How can I get rid of it?
`.card article` should look like this .card article { display: block; height: 100%; width: 100%; position: absolute; -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; -o-backface-visibility: hidden; backface-visibility: hidden; -webkit-perspective: 1000; /* this line is added */ } where the last line of the code is added. Demo: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "css, twitter bootstrap 3, transform" }
How do you fix and error of an Invalid version of NPM for installing @nestjs/core? Hey so i just recently started learning Nestjs and I was asked to setup the environment on my Chromebook(Linux terminal). All packages have been successfully installed except a package _@nesjs/core_. I've tried running the command to install the package **npm install @nestjs/core** but anytime i run the command it keeps giving me this error: npm ERR! Invalid Version: npm ERR! A complete log of this run can be found in: npm ERR! /home/jefferson/.npm/_logs/2022-07-09T07_13_30_344Z-debug-0.log So far I've tried changing my version of npm to version 6.2.0, deleting and reinstalling nodejs and npm but there's been no positive result. Please what else should I try doing
If your Node version is very recent, try downgrading. Stable version 14.16.1 worked.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js, npm, npm install, npm scripts, npm start" }
MySQL Event update on every snapped 5 min I was using the following MySQL event to update the table with the (CURRENT_TIME)+5) every five min. however my plan is was to get the table updated with that time every full 5 min from current time: e.g., on 12:05 it writes 12:10, on 12:10 it writes 12:15... So I used to fire the below event at exactly 12:30:00 for example in order to get it accurate. CREATE EVENT x_next ON SCHEDULE EVERY 5 MINUTE STARTS CURRENT_TIMESTAMP DO UPDATE data SET x_next= CONCAT(CONCAT(HOUR(CURRENT_TIME),':'),MINUTE(CURRENT_TIME)+5); What I am looking now is to make it more accurate to make this event act like the following JSfiddle result where if the even started at any time it will update only on the next 5 min (snapped-to): < Where the result should be what the event should update. I am wondering if anyone had this experience before or any suggestions?
Try to define a start time instead of `current_timestamp` CREATE EVENT x_next ON SCHEDULE EVERY 5 MINUTE STARTS '2014-10-08 12:00:00' DO UPDATE data SET x_next= CONCAT(HOUR(DATE_ADD(Now(),INTERVAL +5 MINUTE)),':', MINUTE(DATE_ADD(Now(),INTERVAL +5 MINUTE))); This will start at `12:00:00` and execute every 5 minute. I changed your update syntax a bit also. It makes sure that the hour is added with 5 minutes, in case at `16:55` , the next value is `17:00`. I think this will give 17:0 and not 17:00, might have to fix a check for that. A bit hacky but it might do the trick?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, mysql" }
Yii create table from application In my yii aplication we need to create dynamic table. so i hav used like below: Yii::app()->db->createCommand("CREATE TABLE {$tokenid}( `column1` INT(11) NOT NULL AUTO_INCREMENT, `column2` VARCHAR(255) NOT NULL, PRIMARY KEY (`column1`) ); "); But it's not working. Any suggestion
You need to execute the command, Yii::app()->db->createCommand("CREATE TABLE {$tokenid}( column1 INT(11) NOT NULL AUTO_INCREMENT, column2 VARCHAR(255) NOT NULL, PRIMARY KEY (column1) ); ")->execute(); or look at the create table function <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "yii" }
How to populate an ArrayList from words in a text file? I have a text file containing words separated by newline , like the following format: >hello >world >example How do i create an ArrayList and store each word as an element?
You can use apache commons `FileUtils.readLines()`. I _think_ the `List` it returns is already an `ArrayList`, but you can use the constructor `ArrayList(Collection)` to make sure you get one.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, arraylist, file handling" }
Remove values from array I have array: $array = array('aaa', 'bbb', 333, 'ddd', 555, '666'); I would like remove all values where key is > 3; How is the best way for this?
$array = array_slice($array, 0, 3);
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 1, "tags": "php" }
コレクションの各要素がAND条件に合致するように検索したい class Dog: Object { dynamic var name = "" dynamic var age = 0 let owners = LinkingObjects(fromType: Person.self, property: "dogs") } class Person: Object { dynamic var name = "" let dogs = List<Dog>() } realm.add(Person(value: ["AAA", [["taro", 1], ["pochi", 6]]])) realm.add(Person(value: ["BBB", [["kuro", 1], ["hachi", 6]]])) realm.add(Person(value: ["CCC", [["taro", 6], ["pochi", 6]]])) realm.add(Person(value: ["DDD", [["kuro", 6], ["chibi", 6]]])) dogpersonkuropochi 3dogpersonIN let persons = realm.objects(Person.self).filter( NSPredicate(format: "ANY dogs.name IN %@ && ANY dogs.age <= %d", ["kuro", "pochi"], 3 )) ‌​'BBB'‌​'AAA'IN‌​‌​ kuropochi 3dogperson
let results = realm.objects(Person.self) .filter("SUBQUERY(dogs, $dog, $dog.name IN %@ && $dog.age <= %d).@count > 0", ["kuro", "pochi"], 3)
stackexchange-ja_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "swift, ios, realm" }
Prove that a polynomial an irreducible g has no multiple root in C I was looking at a question from Artin from Algebra which says that an irreducible polynomial g in F[x] where F is subfield of $\mathbb{C}$. So as per the proofs I have seen so far says as - $$g(x)=(x-\alpha)^2*p(x)$$ and $$g'(x) = (x-\alpha)*q(x)$$ where neither $(x-\alpha) \in F[x]\; nor\; p(x)$. Now finally to conclude they say that gcd(f, f') = 1 but how can f' will belong to F[x] this is not necessary because if we consider $\mathbb{Z}/2\mathbb{Z}$ here let $g(x) = x^5+1$ then $g'(x) = 5x^4+1$. and clearly $5\in \mathbb{Z}/2\mathbb{Z}$ until I write 5 as 1 but then g'(x) would not be derivative of g(x). Thanks in advance.
As $[5]=[1]$ (equivalence classes) in $\Bbb F_2$, $g'(x)=x^4$ in $\Bbb F_2[x]$. See Formal derivatives over finite fields., Introduction to Finite Fields and Appendix B Finite Fields. Quote from the last link: > The derivative of the polynomial $X^q-X$ is the constant polynomial -1.
stackexchange-math
{ "answer_score": -1, "question_score": 0, "tags": "ring theory, factoring" }
Elicitability of risk measures I read that CVaR (Conditional Value-at-Risk, also Expected Shortfall), satisfies coherence, but not Elicitability. On the other hand, VaR satisfies Elicitability, but not coherence. What is Elicitability?
From Ziegel (2013) : The risk of a financial position is usually summarized by a risk measure. As this risk measure has to be estimated from historical data, it is important to be able to verify and compare competing estimation procedures. In statistical decision theory, risk measures for which such verification and comparison is possible, are called elicitable. It is known that quantile based risk measures such as value at risk are elicitable. Better use CoVaR in fact (Value at risk conditional to other value at risk, as a conditional co-movement of another institution's distress)
stackexchange-quant
{ "answer_score": 1, "question_score": 2, "tags": "value at risk, coherent risk measure, cvar" }
Find the sum of all the digits of the least positive integer $n$ such that $(P_2 * P_3 * $ ... $ * P_n)$ exceeds $2010$ . > Let $P_k = 1 + \frac{1}{k} - \frac{1}{k^2} - \frac{1}{k^3}$ , where $k$ is a positive integer. Find the sum of all the digits of the least positive integer $n$ such that $(P_2 * P_3 * $ ... $ * P_n)$ exceeds $2010$ . **What I Tried** : I have that :- $$\rightarrow P_k = 1 + \frac{1}{k} - \frac{1}{k^2} - \frac{1}{k^3} = \frac{(k - 1)(k + 1)^2}{k^3}$$ But I could not find way to use this. I thought this would give me some way to work on the problem but no. Basically I have to find the least $n$ such that :- $$\displaystyle\prod_{k = 2}^{n} \bigg(1 + \frac{1}{k} - \frac{1}{k^2} - \frac{1}{k^3}\bigg) > 2010$$ I have no idea on how to find $n$ . I used Wolfram Alpha mainly for Trial and Error and to get the solution, and I found $n = 8038$ . Check this here:- < So the final answer would be $19$ , but mathematically, how can you find $n$? Can anyone help me?
**Hint** You already observed the key property $$ P_k = \frac{(k - 1)(k + 1)^2}{k^3}$$ Therefore $$P_2*P_3 *P_4*...*P_n= \frac{1(3)^2}{2^3} \frac{2(4)^2}{3^3} \frac{3(5)^2}{4^3} ... \frac{(n - 1)(n + 1)^2}{n^3}$$ Now, just cancel as much as you can, what do you have leftover?
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "linear algebra, number theory, inequality, problem solving" }
Normandy, France: Where to see the WW2 landing craft? I am visiting Normandy, France, more specifically the town of Bayeux. Where in vicinity (I have a car) is it possible to see landing craft used during operation Overlord on D-Day? Preferably on an actual beach and not in a museum.
Nearest american landing craft can be seen in Overlord Museum near American Cemetery, Omaha beach.
stackexchange-travel
{ "answer_score": 0, "question_score": 11, "tags": "france, history, world war ii, normandy" }
How to define and assign Verilog 2d Arrays I'm trying to create a two dimensional array in that form: reg arr[5:0][0:5]; and when I try to assign a value to it lets say assign arr[1] = 22; it gives some errors saying that: > "Reference to scalar reg array 'arr' is not a legal net lvalue" and "Illegal left hand side of continuous assign". So my intention is to assign a number in the index of the array. How does this assignment work? Any help, suggestion would be highly appreciated.
First of all, you can't `assign` to regs. `assigns` drive _wire_ types, not _reg_ types. To drive a reg type you need a statement inside a logic block like an always block. Secondly, based on what you've written, I think you're looking for an array of multi-bit elements, not a 2d array. `reg arr[5:0][0:5];` Defines a 2D array of single bits. If you want an array of multi-bit values that can hold larger than a bit, you declare it like this: `reg [M:0] arr[0:N]` \- This describes an array of (N+1) elements, where each element is a M+1 bit number. If you declare it in this fashion, then you should be able to store a value like 22 into it, assuming you use an always block.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 2, "tags": "arrays, verilog" }
JHipster - *jhiHasAnyAuthority directive - Display one thing when user and another thing when admin **Goal** To display different layouts according to the kind of user. **Try** I used the jhi directive: <span *jhiHasAnyAuthority="'ROLE_USER'"> User </span> <span *jhiHasAnyAuthority="'ROLE_ADMIN'"> Admin </span> **Issue** It works when I'm loggin with the user because its role is only ROLE_USER. However, when I'm loggin with the admin, since it the admin has two roles ROLE_USER and ROLE_ADMIN, the elements that I would like to be displayed only in the user HMI are also presents in the admin HMI. How can I bypass this issue, please? Thanks, Manuela
You could use `ngSwitch` and `ngSwitchCase` directives like in `navbar.component.html` using a condition defined in your component see < Alternatively, you can have a look at this pull request that implements `jhiHasNotAuthority` directive < it has not been merged into JHipster but it can help. Also, you could find a more recent question with more details here: JHipster *jhiHasAnyAuthority directive check for "no authority"
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "angular, jhipster" }
difference between isoFileWriter.Write() and isoFileWriter.WriteLine() When we use isolated storage in c# we have two functions from isoFileWriter. can someone explain the difference between `isoFileWriter.Write()` and `isoFileWriter.WriteLine()` I am using below code: IsolatedStorageFile myspace = IsolatedStorageFile.GetUserStoreForApplication(); myspace.CreateDirectory("Emotions"); using (var isoFileStream = new IsolatedStorageFileStream("Emotions\\history.txt", FileMode.OpenOrCreate, myspace)) { using (var isoFileWriter = new StreamWriter(isoFileStream)) { isoFileWriter.WriteLine(); } }
This is StreamWriter.Write and StreamWriter.WriteLine. The main difference between the two methods is that `WriteLine` will write a new line to the file, where `Write` will just write the data (without a new line character). Calling `isoFileWriter.WriteLine()` will just write a new line to the file. If you were to call `WriteLine` while passing a parameter, ie: `isoFileWriter.WriteLine("Foo")`, it would write `Foo` followed by a new line. `isoFileWriter.Write("Foo")`, on the other hand, would just write `Foo` without the new line character.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "c#, .net, windows" }
Difference between verdict and conviction According to my dictionary: **verdict** > an official decision made in a court of law, especially about whether someone is guilty of a crime or how a death happened **conviction** > a decision in a court of law that someone is guilty of a crime, or the process of proving that someone is guilty Both look very similar in meaning. What's the difference between these two words?
This question may have slightly different answers in different English-speaking countries, but in the US, the verdict is the decision itself. After hearing the evidence in the case, the judge or jury will deliberate and then "render the verdict," or "deliver the verdict." This will usually take the form of a pronouncement that the person is "guilty" or "not guilty." If you watch American TV or movies, you will see one of the jury members being asked to report its verdict in a formula that goes something like this: > "On the charge of murder, we the jury find the defendant not guilty." The conviction is the fact of the person's being found guilty of the crime. For example, > "After his conviction for murder, the man was sentenced to 25 years in prison."
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "word difference" }
HTML Preview via JavaScript or JQuery I'd like to throw together a quick HTML preview window that takes the contents of a text area and shows it in a modal dialogue with a single close button. The contents should be rendered as HTML. Not sure how to go about this.. what's the best way?
If you're using jQuery UI, something like this: **HTML** <textarea id="mytext"></textarea> <div id="dialog"></div> **JavaScript** $('#dialog').dialog({ modal: true, autoOpen: false }); function preview() { $('#dialog').html($('#mytext').val()); $('#dialog').dialog('open'); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "jquery, html, modal dialog, preview" }
Is it a good idea to set a different signal for performing a u-turn? For a long time, I wondered why is there not a separate indication to signify a u-turn, e.g. the rear lights would have two segments for flickering lights - one spaced on top of the other - as to indicate such intention. I've always felt that u-turning should have its own indication, as drivers should be notified on such a particularly risky maneuver. Well, is it really a good idea? And, are there any car manufacturers out there already implementing such a notion?
Nobody considers it necessary. Why is that? First of all, the number one cause of traffic accidents is still speeding. Followed by drunk driving. _Source:What are the most common causes of road accidents? (Sorry I couldn't find one in English)_ U-turn accidents are in fact so rare that german police put them together with normal turning ("abbiegen") and driving backwards ("ruckwartsfahren"). _Source:Traffic accident statistics - Significantly fewer deaths than in 2011_ Also, you should not forget that adding more signals wouldn't be necessarily more safe since it adds a lot more complexity and makes it harder to judge situations.
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "physical, indicator, cars" }
How to await a listener being called and return a Future value I have a Future function which adds a listener to a ValueNotifier. How can I return a value that I retrieve when the listener is called? Map<String,ValueNotifier<String>> _data = {}; Future<String> getAnswer(String text) async { if (_data["answer"] == null || _data["answer"]!.value.isEmpty) { _data["answer"] = ValueNotifier<String>(""); _data["answer"]!.addListener(() { if (_data["answer"]!.value.isNotEmpty) { // somehow return _data["answer"]!.value } else { // continue waiting for next listener call } }); } else { return _data["answer"]!.value; } return await //not sure what to put here. }
Ok I found a solution that works in this case is to use Completer() as follows: Map<String,ValueNotifier<String>> _data = {}; Future<String> getAnswer(String text) async { var completer = Completer<String>(); if (_data["answer"] == null || _data["answer"]!.value.isEmpty) { _data["answer"] = ValueNotifier<String>(""); _data["answer"]!.addListener(() { if (_data["answer"]!.value.isNotEmpty) { completer.complete(_data["answer"]!.value); _data["answer"]!.dispose(); } }); } else { return _data["answer"]!.value; } return completer.future; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "flutter, dart, asynchronous" }
Android Jni: Fastest way to pass a Map from Java to C++? The project I'm working on has a map in its Java parts, sometimes, this map is used by its c++ part, the strategy now is to encode the map into Json string and pass it to c++, then decode it. But the map grows as the application running, making the encoding and decoding cost more and more time, is there any faster way to pass an entire map from Java to c++? The Java map originally is a JSON object, which means there is only string, number, array and map in it.
One option would be to pass down the Java map to C and have it make JNI calls to Java to access the object. Another would be to do the reverse- pass the original string to C and parse it there (which ought to be faster) and access it in Java via JNI. Neither should have a significant time penalty, so long as for the first method you cache the method id and class object of the Java map.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, c++, java native interface" }
Reusing paste config entry I have the following Pyramid .ini file: [DEFAULT] redis.host = localhost redis.port = 6379 redis.db = 0 [app:main] ... # beaker session session.type = redis session.url = localhost:6379 In the `app:main` section's `session.url` I want to use what's defined under `DEFAULT` section's `redis.host` and `redis.port`. In my understanding everything under `DEFAULT` section is global and is passed to other sections. But if I want to reuse a settings from `DEFAULT` and assign it a different name under other sections how do I do that? I'm looking at the same way I can reference section entry in buildout .cfg files using `${<section name>:<entry>}`.
`session.url = %(redis.host)s:%(redis.port)s` Should do the trick.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, pyramid" }
What are some recommended frameworks for manipulating spatial data in C++? What are some recommended frameworks for manipulating spatial data in C++? I'm looking for a polygon object, point object, and some operations like union, intersection, distance, and area. I need to enter coordinates in WGS84 (lon,lat) and get area in square km. I would prefer a free/open source framework, but am open to suggestions. Edit: Unfortunately I need a non-GPL solution. LGPL is alright.
GEOS is an open source (LGPL) C++ geometry / topology engine. Might suit you? Useful places to look for this stuff are this useful article on the O'Reilly website and also OSGeo which is a collaboration to support open source geospatial stuff.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 7, "tags": "c++, geospatial, polygon, spatial" }
Sum last element in tuple where previous elements in tuple match I have a list of tuples in Python which contain three elements. The first two elements points to a location in an array and the final element is to be the value placed at that location. However, the same location sometimes appears more than once. In this case I want to add the values to be placed at that location. I have made a set from the list and sorted it. An extract from the list: (280, 9, 2), (280, 9, 4), (280, 9, 16), (280, 19, 1), (280, 19, 4), (280, 27, 32768), (280, 28, 262144), (280, 28, 524288), (281, 9, 2), (281, 9, 4), (281, 9, 8), etc. As you can see at the 'location' (280,9) there are three final values; 2, 4 and 16, so the value to be placed there should be 22. The same would hold for (280, 19), (280, 28) and so on. Any idea as to how I can achieve this please?
If you are aware of `pandas` then make `dataframe` from these points and make groups on the basis of first and second value using `groupby`. Then calculate the sum of all thired values of each group import pandas as pd points = [(280, 9, 2), (280, 9, 4), (280, 9, 16), (280, 19, 1), (280, 19, 4), (280, 27, 32768), (280, 28, 262144), (280, 28, 524288), (281, 9, 2), (281, 9, 4), (281, 9, 8)] points = pd.DataFrame(points).groupby([0,1])[2].sum().reset_index().to_numpy() points = [tuple(p) for p in points] print(points) [(280, 9, 22), (280, 19, 5), (280, 27, 32768), (280, 28, 786432), (281, 9, 14)]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, arrays, numpy, sorting" }
Check each element of an array is hidden i want to know how to check each element of an array is hidden?? my array contain 20 buttons btnsArr=[[NSMutableArray alloc] initWithObjects:btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn10,btn11,btn12,btn13,btn14,btn15,btn16,btn17,btn18,btn19,btn20, nil]; each button hides with a condition... Actually i am trying to develop a memory match game. I have a timer of two min as well. if user finishes before the time what condition should i put that popup the alert that you win??? any suggestions ?
For your first question, if you want to know if all are hidden, you can iterate and break: BOOL allHidden = YES; for (UIButton *button in btnsArr) { if (!button.hidden) { allHidden = NO; break; } } NSLog(@"All hidden: %@", (allHidden ? @"YES" : @"NO"));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "ios" }
How to build pluggable apps for Android? How does one creates pluggable applications for android? If you have used GoSMS Pro, you can see that themes can be installed separately and then be used to change the main applications appearance. I wonder how can this be done?
Well, you can simply send a broadcast that is received by all plugins (make sure they have a signature based permission!) You might want to have a look at How to release application plugin using Android Market?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, themes, android theme, pluggable" }
Codeigniter Routing: controller function and variable conflict I'm trying to simplify this code to a fewer lines. // Controller function routing $route['news/popular'] = "news/popular"; $route['news/featured'] = "news/featured"; $route['news/latest'] = "news/latest"; $route['news/index/(:any)'] = "news/index/$1"; // points to a url slug of article $route['news/(:any)'] = "news/index/$1"; // points to article without 'index' segment To this: $route['news/(:any)'] = "news/$1"; $route['news/(:any)'] = "news/index/$1"; $route['news/index/(:any)'] = "news/index/$1"; Not working at all. Are there any other methods for this? or should I stick to the long code?
No you can't do that way in codeigniter routes as how can codeigniter guess which function you want to use. What you can try to reduce your routes is categorize news in single function.Something like this : function get_news($news_type) { //check here which type of news is required and process accordingly. } In your route it goes like this $route['news/(:any)'] = 'news/get_news/$1'; Hope this help you
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, codeigniter, codeigniter routing" }
how to call methods created via prototypes in javascript? i'm getting an Uncaught TypeError: question1.pushIt is not a function function Question(){ this.question = []; } function Push(){ } Push.prototype.pushIt = function(array,text){ return array.push(text); } Push.prototype = Object.create(Question.prototype); var question1 = new Question(); question1.pushIt(this.question,"is 1 = 1 ?");// error
I think you might be looking for something like this. JavaScript: function Push() { this.pushIt = function(array, text){ return array.push(text); } }; function Question() { this.question = []; } Question.prototype = new Push(); var question1 = new Question(); question1.pushIt(question1.question,"is 1 = 1 ?"); console.log(question1.question); // ["is 1 = 1 ?"] console.log(question1 instanceof Question); // true console.log(question1 instanceof Push); // true
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "javascript, object, prototypal inheritance" }
How to order the GET response using loopback I've a simple model which looks something like this: { "name": "reason", "plural": "reasons", "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "properties": { "title": { "type": "string", "required": true }, "position": { "type": "number", "required": true } } When retrieving all entries, I would like to order them per default by the position field value. What would be the best way to go about this? Using a model hook? But how would I do it? I'm not sure about the implementation.
You can add a default scope to your model like so: { "name": "reason", "plural": "reasons", "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "properties": { "title": { "type": "string", "required": true }, "position": { "type": "number", "required": true } }, "scope": { "order": "position" } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, loopbackjs, strongloop" }
Segmentation fault while erasing vector while(!v1.empty() || !v2.empty()) { int k=0; if(v1[k] < v2[k]) v1.erase(v1.begin()); else v2.erase(v2.begin()); cout<<v1[0]; } this is my code here i want to remove the elements till one of them is empty(vectors are sorted) , like if > v1 contains 2,3,5,8 > > v2 contains 3,4,7 then according to me it should give me `8` but its giving `segmentation fault`
while(!v1.empty() && !v2.empty()) { int k=0; if(v1[k] < v2[k]) v1.erase(v1.begin()); else v2.erase(v2.begin()); } if (!v1.empty()) { cout << v1[0]; } else if (!v2.empty()) { cout << v2[0]; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, vector, segmentation fault" }
iOS Save State when device turns off or battery drains I have an app that syncs records created on the phone with a web-server. When app does not have internet connectivity, it store everything locally (Core Data) and then syncs it when internet is available again. Now a user has come up with a valid user case scenario ... say he is in an airplane making records (without network) ... so everything is getting stored locally. All is well till the air hostess commands him to switch off the phone. While in the app he immediately turns if off. Now the data is getting lost. I am saving sate while app goes in background or even when phone is locked. But how do I warrant for this? When user switches off the phone (long-pressing lock button), they still have to slide a bar and devices takes some time before switching off ... so there is some time I can save state in ... which delegate method is called during this time?
Your app will get applicationWillResignActive, applicationDidEnterBackground, applicationWillTerminate calls, in that order. < You can use applicationWillTerminate as a cue to save stuff. However it is standard good practice to make sure your data is saved periodically as you go along and not just in these situations - what about if your user has entered lots of lots and data and then your app crashes, the data will be lost. I'm not very familiar with Core Data but surely it must have atomic save ability.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ios, battery, savestate" }
How to add -moz & -o prefixes to code containing only -webkit tags Say, I have this page: < I save the page & run the html file in my localhost. It works fine in chrome as the css uses -webkit prefix. Now I want to test whether is runs on firefox & opera too. So I have to add a -moz & -o prefix in the same css code which has -webkit. Is there any other method rather than appending -moz & -o prefixes myself in the code? One method is writing a script to read the file & append the tags. Any others? **Note:** I am not concerned about whether the css3 transforms used by -webkit are currently supported by -moz or -o or not. All I want is how to duplicate the -webkit lines, adding -moz & -o vendor prefixes to them.
May be **vendor prefix** JS helps you <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "css, vendor prefix" }
Email client not working properly on device? i have made an application in which i first attach a file into my email and then start an intent to send email which i believe would be the default email client on the phone. I have tested this application my HTC- Desire phone with android 2.1 and the attachment is properly being attached to the mail and the mail is being sent successfully. But on another device which is Samsung galaxy s gt-19000, it is giving an error that attachment is too large. The size of my attachment would not be exceeding 1 MB. what is going wrong over here? thank you in advance.
Are the phones using the native mail applications? If yes, then I would guess that these have been programmed with a max size for attachments, which is something that you cannot change. Try attaching the attachment through in the email-client, and see if that works or not.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android" }
warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int **’ New to C, I have this function: void getNum(int *n) { scanf("%d", &n); } And in main: int main() { int someNum; getNum(&someNum); return 0; } Where exactly does the 'int **' part of this error come from, and are there other issues with how I'm passing things around?
The only problem is passing `&n` to scanf: `n` is already a pointer, and so your `scanf` call is passing a pointer to that pointer, hence the warning. Use: `scanf("%d", n);`
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "c, pointers, scanf" }
java integer array resets to default values after pushing the values using foreach Looks strange why the integer array resets again to the default values. int[] y = new int[5]; int z = 0; for(int j : y) { j = z++; System.out.print(j); //0 1 2 3 4 } for(int j : y) { System.out.print(j); //0 0 0 0 0 }
Java is pass by value. Therefore when you change the local variable `j` that contains the value of an array element, the element is not changed, only the local variable. To change the array element, you need to do: for (int j = 0; j < y.length; j++) { y[j] = z++; System.out.print(y[j]); // 0 1 2 3 4 }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, arrays" }
Auto-ML for only fixed estimator Am working on a binary classification with 1000 rows and 28 columns. I would wish to use an Auto-ML solution to try out different combinations of hyperparameters etc but the algo should only be `logistic regression`. I don't wish to use other algorithms for the lack of interpretability. So, I would like my auto-ML solution to stick to logistic regression and try out different values for hyperparameters. Of course, I might use fixed estimators like Decision trees, random forests etc as well Is there any auto-ML solution that can use fixed estimator? I read about `Tpot`, `Evalml`, `AutoML` etc but they all try multiple algorithms and finally output the best one (which may not be logistic regression). How can I restrict my auto-ML solution to only use logistic regression?
I found that we can do this using `Tpot's` `config_dict` and pass this as input to the classifier function like as shown below tpot_config = { 'sklearn.linear_model.LogisticRegression': { 'penalty': ["l1", "l2"], 'C': [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.], 'dual': [True, False] }, } tpot = TPOTClassifier(max_time_mins=10,verbosity=2, config_dict=tpot_config,scoring='f1') tpot.fit(ord_train_t, y_train) This will ensure that TPOT searches best pipeline based on the configs provided by the `config_dict`. However, if there are any other ML tool, I am interested to know from others here as well
stackexchange-datascience
{ "answer_score": 0, "question_score": 0, "tags": "machine learning, deep learning, neural network, data mining, machine learning model" }
FlutterIcon error: Invalid params: - data.config is required (undefined) I tried to "Download" data from **FlutterIcon** (< **What I had tried to do:** 1. Select Icons 2. Write "AppIcons" in "MyFlutterApp" 3. Press button "Download". Then I got this message: _" Invalid params: - data.config is required (undefined)"_
you can use this service to convert svg to font < 1. click on +import icon and after that converted 2. create dart file that contain class with attribute of IconData(int,fontName), the int take it from the site or in setting icon on right of download button you can check generate dart class for flutter
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "dart, flutter layout" }
How to compare 2 images and get percentage size difference how i can compare 2 images in c# suppose * imageA size 1024x640 * imageB size 320x480 i want to know how i can get percentage of size imageb like image B is nn% smaller than imageA i did this but want to know if i am doing it right??? image A total pixels 655360 (1024x640) image B total pixels 153600 (320x480) so string ImageBSize= (153600/655360)*100 +" smaller then imageA";
Assuming you're using System.Drawing.Image or System.Drawing.Bitmap, you could just request the 'Size' property of each of the images. The 'Size' is divided in 'Height' and 'Width'. Calculate 'Height * Width' for each of the images and then you can calculate the ratio between the 'Sizes' of both images. Image imageA = new System.Drawing.Image("ImageA.png"); Image imageB = new System.Drawing.Image("ImageB.png"); double imageASize = imageA.Size.Height * imageA.Size.Width; double imageBSize = imageB.Size.Height * imageB.Size.Width; string ratio = string.Format("Image B is {0}% of the size of image A", ((imageBSize / imageASize)*100).ToString("#0"));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, gdi+" }
How is DRUPAL_CACHE_PER_USER handled for anonymous users? If a block is set to use `DRUPAL_CACHE_PER_USER` for caching, will the block be unique for each anonymous user, or the same for all anonymous users? For reference from API docs: hook_block_info DRUPAL_CACHE_PER_USER Looking at `includes/common.inc` source it appears to be based on `uid`, so I'd assume it would use the same block for all anonymous users (`uid = 0`), but wanted to double-check in case I could use this instead of `DRUPAL_NO_CACHE` (doing geolocation-driven results in the block). elseif ($granularity & DRUPAL_CACHE_PER_USER) { $cid_parts[] = "u.$user->uid"; } _(lines 6084-6086)_
Yes. If a user is not logged in then uid is 0. So all anon users share the same user id. I guess you will have to do your own caching, e.g. based on the IP address.
stackexchange-drupal
{ "answer_score": 2, "question_score": 1, "tags": "blocks" }
Subtract day in specific format I would like to subtract one day each time through the loop in format %Y%m%d, but when I run this code, it shows some weird numbers. my $date = Time::Piece->strptime("20170306", "%Y%m%d"); $date = $date->strftime("%Y%m%d"); my $i = 7; while($i > 0) { $date -= ONE_DAY; print "Date: " . $date . "\n"; $i--; } Output: Date: 20083906 Date: 19997506 Date: 19911106 Date: 19824706 Date: 19738306 Date: 19651906 Date: 19565506
You need to use `strftime` for each iteration. Do not assign the return value of that call `$date` or it will overwrite your object with a string. This line is wrong: $date = $date->strftime("%Y%m%d"); I've removed the parsing from your code for this example as I don't know what your input is. use strict; use warnings; use Time::Piece; use Time::Seconds; my $date = localtime; my $i = 7; while($i > 0) { $date -= ONE_DAY; printf "Date: %s\n", $date->strftime('%Y%m%d'); $i--; } This prints a list of days, going from today backwards. Date: 20170312 Date: 20170311 Date: 20170310 Date: 20170309 Date: 20170308 Date: 20170307 Date: 20170306
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "perl, date" }
$ symbol in c++ I read the following code from an open source library. What confuses me is the usage of dollar sign. Can anyone please clarify the meaning of $ in the code. Your help is greatly appreciated! __forceinline MutexActive( void ) : $lock(LOCK_IS_FREE) {} void lock ( void ); __forceinline void unlock( void ) { __memory_barrier(); // compiler must not schedule loads and stores around this point $lock = LOCK_IS_FREE; } protected: enum ${ LOCK_IS_FREE = 0, LOCK_IS_TAKEN = 1 }; Atomic $lock;
It is being used as part of an _identifer_. `[C++11: 2.11/1]` defines an _identifier_ as "an arbitrarily long sequence of letters and digits." It defines "letters and digits" in a grammar given immediately above, which names only numeric digits, lower- and upper-case roman letters, and the underscore character explicitly, but does also allow "other implementation-defined characters", of which this is presumably one. In this scenario the `$` has no special meaning other than as part of an identifier -- in this case, the name of a variable. There is no special significance with it being at the _start_ of the variable name.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 9, "tags": "c++, multithreading, syntax, locking" }
Changing MFMailComposeViewController's toolbar color I'm using a tinted navigation bar and a tinted global UIToolbar in my iPhone app. In my info view, I have a button which opens a MFMailComposeViewController, and the toolbar at the top of that view (with the "cancel" and "send" button) is still blue. I'm calling the MFMailComposeViewController like this: -(void)displayMailSheet { MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; [picker setSubject:@"..."]; NSArray *toRecipients = [NSArray arrayWithObject:@"..."]; [picker setToRecipients:toRecipients]; [self presentModalViewController:picker animated:YES]; [picker release]; } Is it possible to change the color of that view's toolbar? If it is possible, how can I do this?
Here you go: [[picker navigationBar] setTintColor:[UIColor blackColor]]; for iOS 8.0 [[picker navigationBar] setBarTintColor:[UIColor blackColor]];
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 19, "tags": "ios, objective c, colors, toolbar, mfmailcomposeviewcontroller" }
How do I view the amount of L2 cache in windows? I know where to find CPU class and speed, and amount of RAM. But I don't see the amount of CPU cache in computer properties or device manager. Does windows (XP currently) provide this information, or is there a good program to retrieve it?
CPU-Z from CPUID is a great little tool for finding out information about your processor. !enter image description here More detail on the caches: !enter image description here
stackexchange-superuser
{ "answer_score": 6, "question_score": 1, "tags": "windows, cpu cache" }
Access attributes from another table - rails A user can have many mentors, a Mentor belongs to user class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable validates :firstname, :lastname, presence: true has_many :mentors class MentorsController < ApplicationController before_action :set_mentor, except: [:index, :new, :create] before_action :authenticate_user!, except: [:show] before_action :is_authorised, only: [:lesson] How can I show the mentor lesson attribute on the user page? I tried to do something like "#{@user.mentor.lesson}" but it doesn't work :(. Thank you, Lily
If a User has many mentors, then `@user.mentors` will give you an `ActiveRecord_Associations_CollectionProxy`, with more than 1 record corresponding to each Mentor. You can access to each them but to get an specific attribute of Mentor you need to iterate over this collection, like: @user.mentors.each do |mentor| puts mentor.lesson end What you're trying to do is the inverse of what you need to do, as one mentor belongs to one user, then you could `@mentor.user` and to get the specific user and query its attributes without having to iterate, but in your case is accessing the plural of mentor.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ruby on rails" }
cannot find symbol with isLowerCase I took this code directly out of Thinking in java 4th edition and it keeps giving me 'cannot find symbol: method isLowerCase(Char). Is the book wrong, do I maybe not have the character class with all my files, or am I doing a really really really stupid mistake? public class ListCharacters{ public static void main(String[] args) { for(char c = 0; c < 128; c++) if(Character.isLowerCase(c)) System.out.println("value:"+(int)c+ " character: " + c); } }
Do you have a class called `Character` in the same folder as your `ListCharacters` class? On its own, your `ListCharacters` class compiled fine for me. However, when I added a class called `Character` to the same folder, I got a 'cannot find symbol' error for the `isLowerCase` method.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, character" }
Why is WOTS-type signature schemes OTS? I'm sure I've missed something super trivial, but why are WOTS-type schemes one-time? I've been looking into hash-based schemes, and I feel like I understand WOTS quite well (specifically I have looked at WOTS+), but I cannot figure out why WOTS would not be safe to use just a few times as an FTS such as HORS(T) for example?
I'll only talk about things on a very high level here, probably much higher than what you already know and will use Matthew Green's blog post as the primary reference. Nevertheless the idea should come across. So in that post, WOTS is described as a smart way to have more than two (0 and 1) lists of of secret key values to publish as the signature. Now what you do is that for each symbol (eg byte), you publish one entry from these lists (in a smart way). But if you do this twice for different message which differ in at least 2 bytes, you can take one byte from the one and one byte from the other signature to forge a new signature! Also note that (as far as I can tell), it's usually _not_ assumed for this kind of signature scheme to mandate hashing the input and only passing the hash to the signature primitive.
stackexchange-crypto
{ "answer_score": 1, "question_score": 2, "tags": "signature, hash signature" }
How to display only one figure in a loop Matlab I want to display a figure in a loop in Matlab. I'm using this code as a simple example of mine for i=1:10 figure('renderer','zbuffer') end but the problem is that in every iteration a new figure is created for example, if i have 10 iterations then 10 figures will appear, which I don't want, I want only one figure to appear in all the iterations as `figure 1`where in each iteration the old data is replaced by the new ones. So, if anyone could advise how to do this?
Before the loop, open the figure with h=figure(1) and then set the renderer with set(h,'renderer','zbuffer') then start the loop. I can't see why you would need to set the renderer every iteration. If you do want to set the renderer at each iteration, then you can just put the `set(h,'renderer','zbuffer)` line inside the loop to replace your `figure('renderer','zbuffer')`. Edited to add: The reason it was opening a new figure each time for you was that `figure('renderer','zbuffer')` opens a new figure window. To change the properties of an already-opened figure window you must use `set`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "matlab" }
jquery issues with chrome/safari $('#div1').children('div:last').css('border-bottom', ''); $('#div2').focus(); I am using above and it works fine with ie but not with chrome & safari. I haven't tried FF. 1st line is to find all child divs and remove underline from last one. 2nd one is to focus on div2 on some action. What could be wrong in here? Or do i need any special treatment for those browsers?
Focus() is really intended to be used with input elements -- which a DIV is not. Of course, I have no way of knowing whether you've given one of your inputs the name "div2", but I suspect not. I think what you really want to do is scroll to the position of the div, not give it focus (or you could give focus to an input in the div). Thankfully, there's a plugin for that. As to the border issue, I'd try using 'none' instead of ''.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
Would "metaphor use" be hyphenated? As in "metaphor-use" versus "metaphor use".
The phrase "metaphor use" (which could be rephrased as "use of metaphor") would not be hyphenated on its own, but it would be hyphenated when used as a **compound modifier** , ie, a joint phrase forming an adjective for a noun. See this article on Grammarly: > A compound modifier consists of two words connected by a hyphen, which act together like one adjective. Usually, compound modifier words could be understood as individual modifiers or nouns, so the hyphen is required to clarify the function of the words. An example of this would be the phrase "metaphor-use frequency". Note that this rule is often missed by the casual English user.
stackexchange-english
{ "answer_score": 1, "question_score": 0, "tags": "hyphenation" }
How do you find memory leaks using the Netbeans profiler? I want to find memory leaks in my java application but I don't know how to use Netbeans profiler to do that.
There are several resources on the web that can give you a hand < < < In a nutshell, you monitor the "surviving generators", objects that are kept in the memory by your application. When you see that this metric gets out of hand, you can switch to the Memory Live profiling mode, sort the classes by surviving generators and then with the right click mouse button select the "Show Allocation Stack Traces" option
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 15, "tags": "java, netbeans, profiler" }
What's the advantage of buying a fixed 50mm f/1.8 lens when my camera has an 18-55mm zoom lens? I've got a Nikon D3100 with an 18-55mm zoom lens. I'm keen to experiment with some other lenses and a friend of mine recently reccommended I purchase a fixed 50mm f/1.8 lens as he said it's good for portrait photography and capturing really sharp images. He also said that as it isn't a zoom lens it will sharpen my composition skills. My question is - I currently have an 18-55mm zoom lens, so by purchasing a 50mm fixed lens, won't I be purchasing a spec of lens already covered by my 18-55mm lens? What are the main differences between these two lenses? Finally - can anybody vouch for the Nikon fixed 50mm f/1.8 lens as being a good lens to go for?
At 50mm on your 18-55, the max aperture is f/5.6. On the 50mm f/1.8, the max aperture is - obviously - f/1.8. It is perhaps not immediately obvious, but f/1.8 lets in 10-12 times more light than f/5.6. That is the difference between shooting at 1/10 second shutter speed (which is absolutely a no-go for moving subjects) and shooting at 1/100 (which is a usable shutter speed for moving subjects). Big difference indoors at night, for example. It lets you shoot without flash, or with the flash used as mere fill flash instead of it being the main light-source. Note that Nikon has two variants of the 50/1.8, one with a built-in autofocus motor and an older one without. Do get the new one.
stackexchange-photo
{ "answer_score": 29, "question_score": 19, "tags": "lens, zoom, prime, kit lens, 50mm" }
"He's the one to do the job" > He’s the one **to do** the job. > > (The Cambridge Grammar of the English Language, p.174) CGEL says the meaning of the above “is comparable to that of _the one who should do the job_ or _the one whom we should get to do the job_ , with modal _should_ ”. While I read that to-infinitives have the meaning of ‘potentiality’ (CGEL, p.1240~1243), I’ve not come across any mention about the modal meaning. Is the to-infinitive above has only the meaning of oughtness? Or could it have other meanings? (I think ‘He’s the one who would do the job,’ might be the candidate, but I’m not sure.)
I can only applaud that you're reading such a scholarly grammar. However, bear in mind that it was written for language professionals (linguists and language teachers), not language learners. To answer your question, I would strongly suggest re-reading the relevant section again, more carefully. The answer is there, in the book. Huddleston discusses ways of expressing **modality** on pages 173-175. Your example is from section (c) Other verb inflection. Huddleston, who wrote chapter 3, clearly says that > "the plain form of the verb is commonly used with a **modal** sense [emphasis mine - Alex B.]" and > "in non-finite clauses, the plain form is used in the infitinival construction, where it is often associated with **non-actuality** [i.e. potentiality - Alex B.] in contrast with the gerund-participial construction" [emphasis mine - Alex B.] (p. 174).
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "infinitives" }
The icons in my Dock is locked Some time ago I locked my Dock, because I was annoyed by accidently dragging the icons around in the Dock. I did that by running this command: defaults write com.apple.dock contents-immutable -bool true; killall Dock; Now I want to rearrange some icons, therefor I want to disable it again. I have tried to do so by running this command: defaults write com.apple.dock contents-immutable -bool false; killall Dock; But it does not work and I have tried to reboot afterwards, but the Dock is still locked. I have checked the com.apple.dock.plist file and the value for contents-immutable is set to NO. My user is the admin user of the Mac, so that shouldn't be the problem. I am running OS X 10.9.3. How can I fix this?
Turns out I simply forgot how to move the icons. I thought I should click and hold, wait until the menu appeared and then drag. That wasn't the way to do it. I found this and it turns out that you should Click, hold and drag before the menu appears.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "macos, mac, osx mavericks, dock" }
Adding complementary proportions below each line of a file My file looks like this: 0.35 0.45 0.25 0.44 0.35 0.06 0.10 0.14 0.15 0.00 and I would like to add below each line the complementary proportions of each value, i.e.: 0.35 0.45 0.25 0.44 0.35 0.65 0.55 0.75 0.56 0.65 0.06 0.10 0.14 0.15 0.00 0.94 0.90 0.86 0.85 1.00 So far I only managed to insert a string below each line: typeset TMP_FILE=$( mktemp ) touch "${TMP_FILE}" cp -p proportions_file "${TMP_FILE}" sed -e 's/$/\nstring after each line/' "${TMP_FILE}" > proportions_file_final where proportions_file is the original file and proportions_file_final the output: 0.35 0.45 0.25 0.44 0.35 string after each line 0.06 0.10 0.14 0.15 0.00 string after each line Is there a function I could use instead of "string after each line" that calculates the complementary proportion of the value above it?
You can use `awk`: awk 'function printdiff() { for (i=1; i<n; i++) printf "%.2f%s", (1-a[i]), (i<n-1?OFS:ORS) } NR > 1 { printdiff() } { for (n=1; n<=NF; n++) a[n] = $n } 1; END { printdiff() }' file 0.35 0.45 0.25 0.44 0.35 0.65 0.55 0.75 0.56 0.65 0.06 0.10 0.14 0.15 0.00 0.94 0.90 0.86 0.85 1.00 In one line: awk 'function printdiff(){for (i=1; i<n; i++) printf "%.2f%s", (1-a[i]), (i<n-1?OFS:ORS)} NR>1{printdiff()} {for (n=1; n<=NF; n++) a[n]=$n} 1; END{printdiff()}' file
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bash, sed" }
Scala traits stacking I have the following traits: trait A trait B extends A trait C extends B I have to now stack these traits: trait Stackable extends C Is B and A automatically stacked in Stackable? or should I explicitly stack them using with?
Yes, `Stackable` will extend/mixin `C`, `B`, and `A` It's not necessarily wrong to explicitly mention them, i.e. `trait stackable extends C with A`; this won't cause any problems, but it's unnecessary. Ultimately it's up to you and your judgement to decide whether it makes sense to call them out explicitly.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "scala" }
Como fazer LTRIM() e RTRIM() em Java? Preciso processar umas _strings_ em Java. Sei que existe o método `trim()`, mas preciso de um _Left Trim_ e de um _Right Trim_. Como faço isto? Por enquanto estou percorrendo a _string_ com um laço e retirando todos os espaços em branco do começo (até atingir um caractere) ou do final (fazendo um _loop_ do final para o começo da _string_ ).
Você pode utilizar regex: Right Trim: String texto_filtrado = original.replaceAll("\\s+$", ""); Left Trim: String texto_filtrado = original.replaceAll("^\\s+", ""); Fonte: <
stackexchange-pt_stackoverflow
{ "answer_score": 13, "question_score": 17, "tags": "java, string" }
How to password protect an email in Gmail? I want to send a password protected email using gmail. Yes I Know I could attach a document, and protect that instead, but I would like to protect the email body, if that is possible?
No, that is not possible with email. Such a function is not specified in the email protocoll. The only possibility would be to encrypt the text in your email body with a tool like PGP or S/MIME. The recipient needs to enter his private password to decrypt the email body. But you need a email client or third party tools to support this (as well as your mail recipient).
stackexchange-webapps
{ "answer_score": 18, "question_score": 12, "tags": "gmail" }
How do I output unicode character captured as a substring of command line argument? I am running into some confusion about unicode characters in C++ strings. I have a program like this: #include <iostream> int main(int argc, char* argv[]) { std::cout << "3rd char of " << argv[1] << "is: " << argv[1][2] << std::endl; } when I run it with this command: mapper abͲ It returns this: 3rd character of abͲis: Now, clearly my system supports unicode (Ubuntu 16.04) and the compiler doesn't mind the program (g++ 5.3.1). I understand argv is a vector of char* objects, but how can I access a single character inside a single argument vector if the character is unicode? There must be some type conflict I am missing.
The most important thing to remember when dealing with text in C++ is that one `char` is not equivalent to one character. For a single-byte character encoding like ASCII one `char` == one character, but for a multi-byte encoding like UTF-8, a character can be composed of multiple `char`s. In this case, the character you're trying to output (U+0372 GREEK CAPITAL LETTER ARCHAIC SAMPI) doesn't fit in a single `char`. It's actual value will depend on your system text encoding since it's passed into `argv`. The default encoding on Ubuntu 16.04 is UTF-8, so that character will be the two bytes `0xCD 0xB2`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c++, c++11, unicode" }
concat() in XPath here is my xml : <compositeurs> <compositeur></compositeur> <compositeur id="5"> <dates naissance="1687" deces="1770"></dates> <nom> <prenom>Johann</prenom> <prenom>Sebastian</prenom> <prenom>Sebastian</prenom> <prenom>Sebastian</prenom> <famille>Bach</famille> </nom> </compositeur> <pays>Alemagne</pays> <compositeur></compositeur> </compositeurs> I would like to concat all the elements prenom that have famille="Bach". I used `concat(//nom[famille='Bach']/prenom)` but its wrong.
It's not possible to do it in XPath 1.0 Here's the way to do it in XPath 2.0: string-join(//nom[famille='Bach']/prenom, ' ') If XPath 2.0 is unavailable, you can always concatenate the results of your original expression in whatever imperative language you're using.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "xml, xpath" }
How to pass a multidimensional array to a function without inner dimension in c++? I was wondering if there was a way to say pass this for example `double MyArray[][2] = {{0.1,0.8},{0.4,0.6}}` to a function like this `void MyFunction(double myArray[][]);`, without saying this `void MyFunction(double myArray[][2]);`. I need this because I want my function to be able to handle arrays with different inner dimensions for example: `double MyArray[][3] = {{0.1,0.8},{0.4,0.6},{0.3,0.9}}`. To pass this to a function as far as I know I would have to change MyFunctions's parameters to `MyFunction(myArray[][3]);`. From what I have read I don't know if this is possible, so if it is not then is there some other way of doing this?
You can pass an arbitrary 2d array by reference if you could change `MyFunction` to: template<std::size_t N, std::size_t M> void MyFunction(double (&myArray)[N][M]) { // ... } This way you would also have dimensions of the array.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c++, arrays, function, multidimensional array" }
What is the benefit of using sqlite3_data_count() over sqlite3_column_count() in the SQLite C API? After reading the docs, it seems the the function sqlite3_column_count does all the same, but doesn't have the restrictions that sqlite3_data_count has. Why would I ever want to use sqlite3_data_count over sqlite3_column_count? thanks!
`sqlite3_data_count` returns the number of values (columns) of the currently executing statement. With no results it returns 0. `sqlite3_column_count` on the other hand, returns always the number of columns, with or without results. Which one you'll use depends on whether you must get the number of columns or not.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "c, api, sqlite" }
finding a y value whose x value is closest to zero in R vectors I have two columns of numbers. First column is called `ddd` and second column `post`. You can easily import my data into your Rstudio this way: id <- "0B5V8AyEFBTmXM1VIYUYxSG5tSjQ" Points <- read.csv(paste0(" My question is how I can find out first, what is `post` when `ddd` is 0 AND second, if there is no 0 for `post` when `ddd` is 0, find the closest to 0? (so I need R to do the both checks for me?) I have used the following R code which doesn't work: Points$post[Points$ddd == 0]
If you have a `Points` dataframe with two columns, `post` and `ddd`, zero or near zero could be acheived with `which.min(abs(Points$ddd))` which will return the index so `Points$post[which.min(abs(Points$ddd))]` should get you there. Note, you will have issues if you have multiple zeros or minimum values.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "r, function, curve" }
Friends list private but Facebook reveals it with "Do you know X,Y,Z" emails My Facebook Friends list is private, because there are some people I don't want to show I am friend with. A while ago I created a `Bob` account for testing purposes and added `Bob` as a friend. **PROBLEM:** Every week or so, `Bob`'s email address receives such an email: > Do you know Deng Yaping, Liu Guoliang and 8 others? > People You May Know > Add the people you know to see their photos and updates. > > Deng Yaping > Tibet University > > [... 9 more names, with their networks and link to their profiles ...] That defeats the purpose of having my Friends list private. Is it a bug that affects only me or is it a known issue? Is there a solution, or should I just refrain from using Facebook? Note: I am aware that `Bob` can see the friends with whom I have any post/like/comment/tag activity, I am more concerned about some friends with whom I only exchange private messages.
I should note that if someone adds JUST him and gets these emails. Much like he set up the "Bob" account. They would only receive emails about friends on HIS account. Since he'd be their only friend it would be rather obvious wouldn't it? I'd say it's a problem with facebook's privacy for sure.
stackexchange-webapps
{ "answer_score": 4, "question_score": 7, "tags": "facebook, privacy" }
Data from parent site list displayed on subsite list I have a parent site that has a list of team members along with other data about their positions. I would like to display this list in a subsite. I understand that with SP Designer I can link a web part from the parent to the subsite, but how to I get the subsite to show the data contained in the parent site list?
**Without using SharePoint Designer** you can achieve that via `Content Query Web Part` as the following * Open your Page > Click on Add web Part > below Content Rollup > Add Content Query Web Part . * Click to open the tool pane to edit * At Query section,> at Show items from the following list: > click browse to `browse any list from any site below your site collection`. * Select the list that you need from the parent site. ![enter image description here]( Although this method will achieve your goal to show a list from the parent site, unfortunately, it will need some customization (ItemStyle) to show your CQWP as List view, and to can do this check SharePoint Content Query web part like a SharePoint List View **Using SharePoint Designer,** check * Display a SharePoint List from Parent Site in Sub Site * SP 2016 - Display list from Parent site in sub-site
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 3, "tags": "sharepoint designer, list, web part, sharepoint addin, sub site" }
Clockworkmod doesn't find the update files I recently added a 16GB storage card to my phone and set it as an extension to the internal memory using the built-in tool in Cyanogenmod 13. But now, the recovery can not find the update files anymore. I can only open the /storage/sdcard folder, but when I try to open /storage/sdcard/0 to access the cmupdater folder, it says that there are no files in there. I can install updates using adb commands though. How can I fix this?
For future Visitors: just install the TWRP recovery on your phone(I used the Flashify appfrom the Play Store to install). Look for the folders there. I found what I looked for in /sdcard. With TWRP, it should be very easy to install the update.
stackexchange-android
{ "answer_score": -1, "question_score": 0, "tags": "cyanogenmod, updates, recovery mode, clockworkmod recovery, samsung galaxy s 4 mini" }
SQL - Multiple Joins to one table - Two values from two keys I'm ashamed to say that my SQL experience is used so infrequently, it falls down when I have to construct a slightly complex query so I'd appreciate an SQL experts advice. Essentially I have two tables, similar to the following games(game_id, game_date, player_a_id, player_a_score, player_b_id, player_b_score) players(player_id, player_name) I wish to construct a query that returns in the same result set, player names and scores ie. game_id, game_date, player_a_name, player_a_score, player_b_name, player_b_score Here is my naive approach that I would like to optimize select games.game_id, games.game_date, (select player_name from players where player_id = games.player_a_id), games.player_a_score, (select player_name from players where player_id = games.player_b_id), games.player_b_score) Can anyone advise me the best way to approach this? Thanks!
Maybe something like this: select games.game_id, games.game_date, pa.player_name as 'player_a_name', games.player_a_score, pb.player_name as 'player_b_name', games.player_b_score from games inner join players pa on (games.player_a_id = pa.player_id) inner join players pb on (games.player_b_id = pb.player_id)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "sql" }
Java Regex to split a String with int, doubles I have a String that I want to split; String x = "abc4.5efg2hij89k.9"; I want the output as abc, 4.5, efg, 2, hij, 89, k, .9 I can easily split across digits and non digits however '.' is considered a character. x.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)") [abc, 4, ., 5, efg, 2, hij, 89, k., 9] What is the best way of supporting doubles?
Have you considered letter characters instead of using the `\D` token? String s = "abc4.5efg2hij89k.9"; String[] parts = s.split("(?<=[a-z])(?=[\\d.])|(?<=\\d)(?=[a-z])"); System.out.println(Arrays.toString(parts)); Output [abc, 4.5, efg, 2, hij, 89, k, .9]
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "java, regex, split" }
C# setting object as null I want to set an object as null so I can 'consume' it of sorts. In Java we have this. //In some function/object Vector3 position = new Vector3(); //In some loop. if(position != null){ consumePositionAsForce(position); position = null; } I'm aware in C# that one has to 'Box' the and 'Unbox' the object if you are using primitive types buut I cannot find any documentation on nullable value types. I'm trying to do the same in C# but I'm getting an errors/warning about type cast. As in I cannot set Vector3 = null.
You can use nullable types to do this: Vector3? vector = null; And assign its value from some place: position = new Vector3(); And then you can easily compare it to `null` as you would have compared a reference type object: if(position != null) //or position.HasValue if you want { //... } After you verify it is not `null`, to access the `Vector3` value, you should use `position.Value`.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "c#" }
What does this figurative usage of "swampy" mean? > Not to pooh-pooh the Doobs and their smooth, aged take on **swampy** , countrified soul, but this show belongs to Steely Dan. (source) I have checked several dictionaries but haven't found one listing a figurative usage of "swampy". As far as I know the word is only used to describe terrain. What does it mean in this sentence? What does it mean for soul music to be " **swampy** "?
There is a sub-genre of rock music called _swamp rock_ , which originated in the deepest southern states, where the terrain is, in fact, swampy. The quote is suggesting that the Doobie Brothers' music is influenced by this style.
stackexchange-ell
{ "answer_score": 2, "question_score": 0, "tags": "meaning, word usage, meaning in context, word meaning, figurative language" }
How to remove an element from an array using _.set or equivalent How to remove an element using lodash/fp's `set` or equivalent method. I tried `_.set({data:[1,2,3]},"data[1]", undefined)` which results in `{data:[1,undefined,3]}` where as I would like to get the output as `{data:[1,3]}` also tried `unset` which results in `{data:[1,empty,3]}`
Here is a clean solution for you. The only thing you need to change is the `_.isEqual(idx, 1)` for whatever index that you want to remove, or even change it and use an array, if you need by using `_.includes([1, 5, 10], idx)` instead of the `_.isEqual()` functionality. // Your idea: _.set({data:[1,2,3]},"data[1]", undefined) // Using a simple _.reject() function: const newData = _.assign({}, myObj, { data: _.reject(myObj.data, (val, idx) => _.isEqual(idx, 1)) });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, arrays, lodash" }
HTML Picture and header alignment trouble Hi I'm having trouble getting things in the right place on my website using HTML and CSS. I am very new to coding in these languages as I only learnt them yesterday. This is the code I have: My Code <h1 class="jumbotron"><img class="logo" src="logo2.jpg"/>My website</h1> <ul> <li><a style="border-top 1px solid #bbb" class="active" href="index.html">Home</a></li> <li><a href="news.html">News</a></li> <li><a href="contact.html">Contact</a></li> <li><a href="about.html">About</a></li> </ul> The picture on the left just above the Home button is what I am having trouble with, I want to move up as only half of it is showing. I want it to fit in the top left corner square. Thanks.
In your CSS, here is edited code to make the picture placed in top left. .logo { position: absolute; top: 0; left: 0; width: 230px; height: 230px; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css" }
Conditional Filtering in Generator with random integer I would like to create a generator of random numbers. import numpy as np rd_list = (np.random.randint(10) for i in range(6)) When I try with this I get values [7, 1, 4, 2, 0, 6]. I would like to filter these results by this condition < 5. How can I get this result?
Another way using assignment expression (Python 3.8+): import random nums = (n for _ in range(6) if (n := random.randint(0, 10)) < 5) Thanks to Andrej's comment: Since you are already using `numpy`, you don't need the loop: import numpy as np nums = (n for n in np.random.randint(0, 10, 6) if n < 5)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, loops, generator" }
What is the name of this flower I had this flowers a few years ago but I don't know what it is called so I don't know how to look for it now. Can anyone help identifying it. This is the only photo I have !enter image description here
It's a Lewisia - quite possibly the one shown here (Sunset Strain). They must have excellent drainage and full sun. Hardy to Zone 5 in the US. -![\(Lewisia 'Sunset Strain'](
stackexchange-gardening
{ "answer_score": 3, "question_score": 2, "tags": "identification, flowers" }
What is the difference between local and global data association in object tracking context? I come across these two papers from Zhang, et. al (2008) and Wu & Nevatia (2007). One of them classified the paper as local data association based, and the other is global data association based. After reading the two papers, I assume that by local data association, they used local shape features to the result of foreground extraction such as edgelet features, and boosting edgelet based, and by global data association, they only used common (or should I say non-specific?) features, such as position, scale, appearance, and frame index. Could anyone make sure that my understanding is right? Also, is there any literature that I should read to enhance my comprehension on this context? Thank you for your attention. I'm looking forward to your reply.
Think of it as local referring to your neighborhood. You know various things around there i.e. what you have learned over time. But if you move to a new neighbourhood you know a little about it. But you still know some things like the new neighbourhood would have a parking space for each house and things like that. In the same way when you use specific features like some special shapes that are local data association because a shape of an apple would not fit a banana. But if you used some other feature you might be able to generalize your result over multiple inputs which is a case of global data association.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "computer vision, video tracking" }
What is the probability density function of $X_1+X_2$? Given $X_1 \sim \exp(\lambda_1)$ and $X_2 \sim \exp(\lambda_2)$, and that they are independent, how can I calculate the probability density function of $X_1+X_2$? * * * I tried to define $Z=X_1+X_2$ and then: $f_Z(z)=\int_{-\infty}^\infty f_{Z,X_1}(z,x) \, dx = \int_0^\infty f_{Z,X_1}(z,x) \, dx$. And I don't know how to continue from this point.
$$f_Z(z)=\int f_{X_1}(x)f_{X_2}(z-x)dx$$ Note that in your case the RHS has integrand $0$ if $z\leq0$ so that $f_Z(z)=0$ if $z\leq0$. For $z>0$ we have:$$f_Z(z)=\int f_{X_1}(x)f_{X_2}(z-x)dx=\int_0^{z}f_{X_1}(x)f_{X_2}(z-x)dx$$ Work this out yourself.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "probability, random variables, convolution, density function" }
Create new Child on Parent's show On the show view of an existing Parent, I would like to have a form to create Children. I've figured out how to create a Child form and include it on the Parent's show, but not how to exclude the parent_id field. How can I assign a parent_id to a child without using a form field?
I think the best way to handle this is by using member routes for the parent controller so that when you create the child, you always know which parent it belongs to through the routing. For example: # routes.rb resources :parents do member do post 'create_child' end end And then in your view # parents/show.html.erb <%= form_for @child, :url => create_child_parent_path(@parent) do |f| %> ... <% end %> And finally in your controller # parents_controller.rb def create_child @parent = Parent.find(params[:id]) @child = @parent.children.build(params[:child]) if @child.save @child = Child.new end render :action => :show end The key here is that even though the form contains no information about the parent, the parent_id gets assigned by default when you use the build method on the association.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "ruby on rails, ruby, activerecord" }
Spring @value to inject values without properties file My question is simple. Consider the class below. I need to place value of i=1 , str ="abc" directly without using any properties file using @Value annotation. How to do that ? import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Example { int i; String str; @Autowired AccountService obj; public void setI(int i) { this.i = i; } public void setStr(String str) { this.str = str; } public void setObj(AccountService obj) { this.obj = obj; } }
Well, simply do @Component public class Example { @Value("1") int i; @Value("abc") String str; @Autowired AccountService obj; public void setI(int i) { this.i = i; } public void setStr(String str) { this.str = str; } public void setObj(AccountService obj) { this.obj = obj; } } This is equivalent of writing in XML `<property name="" value="" />` which calls setter for injecting the values.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "spring" }
What's the best practice to do something after some events all fired For example, I want to tell user that everything is ready after a bunch of async initialization(they fire events when they are done), what's the best practice? My solution is using a counter counting the number of events, and once the value of counter equal to total number of events, then I toast a message.
If you have a definite number of events that will be fired, then I don't see the problem with using a counter for the events, as you suggested. That way you will know for certain that all of the events have been fired, and it's only slightly inefficient since it requires checking the count in every callback. Otherwise, promises, which are "then'able" could work, e.g.: var promises = [ asyncProcessOne(), asyncProcessTwo(), asyncProcessThree() ]; Promise.all(promises) .then(onFulfilled, onRejected) // run onFulfilled if process is successful
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
Array : store array in array for example i have some element like below <div class="1">abc,cbc</div> <div class="1">GSV,SDG</div> How can i store it as below, an array in array format. var new arr = [[abc,cbc],[GSV,SDG]]
You can use `map` of jQuery. It helps you to create an `array` out of all selected elements. Just `return` the values you want to store in the resulting array. Your class `1` is invalid. A class must start with `-`, `_` or `a-z`. So I renamed it for this example. var array = $("div.class1").map(function() { return [$(this).html().split(",")]; }).get(); console.log(array); <script src=" <div class="class1">abc,cbc</div> <div class="class1">GSV,SDG</div>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "javascript, jquery, arrays" }