INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I get analytics on a site without a frontend? For example, google Analytics would require me to insert a script in my layout. However, my app has no views and is only serving an API, without an interface. Are there any services to track traffic of a JSON API ? I intend to host on heroku.
Most analytics services offer some sort of server-to-server rather than client reporting of events. You should get some more consistency in data reported (e.g. you're not blocked by ad blockers or slow connections failing to load client side libraries) but also lose visibility into some events (user tracking depends on your authentication/cookie policy, time on page may be impossible to measure). For a Rails app I'd look at < which in my experience has done a good job of making it easy to report events and allows you to then forward them to whatever analytics service works best for your product.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby on rails, json, api, heroku, rails api" }
What does 1071: Syntax error indicate and how do I resolve this code? I'm going through tutorials on dynamic classes. The concept is really exciting and interesting to me. However this code isn't compiling correctly dynamic class Person { var name:String; } Person p= new Person(); p.name=”Joe”; p.age=25; p.printMe = function () { trace (p.name, p.age); } p.printMe(); // Joe 25 I get a 1071 syntax error. What gives?
Error in syntax; `Person p = new Person();` is not valid AS3. It should be `var p:Person = new Person();"` EDIT 1: Also, of course if you put your code as-is in the timeline it will not work. The class has to be in a .as file, and the other code must be in the timeline (or in a class function). EDIT 2: This code works: //Timeline: var p:Person = new Person(); p.name="Joe"; p.age=25; p.printMe = function () { trace (p.name, p.age); } p.printMe(); // Joe 25` Where Person.as looks like: package { public dynamic class Person { var name:String; } }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "flash, actionscript 3" }
What is Sam's probability of success at the Olympics? Sam is in a team of probables for Olympics. There are $m$ members in that team. But only $n$ would get a ticket to Olympics. Each member is equally talented and hence everyone has equal chance of making it to the Olympics. There are $x$ members from Sam's state, including him, in the team of probables. Sam believes that he would perform well at the Olympics only if at least $y$ members from his state are also there with him. Calculate the probability of Sam performing well at the Olympics.
(Sketch): Let us denote the event that Sam is picked by $S$ and the event that he will do well by $W$. Then we want $P(S\cap W)$. This is equal to $P(W\mid S)\cdot P(S)$ so we have that: $P(S)=\binom{m-1}{n-1}/\binom{m}{n}$ because the number of arragnments that place them on the team is $\binom{m-1}{n-1}$ (to see this, just pick him first, and then there are $m-1$ people remaining and only $n-1$ more places for the olympics). I might be missing something but I think $P(W\mid S)$ is not as straight forward to calculate. You want the probability that exactly $y$ of his friends go, plus the probability that exactly $y+1$ of his friends go, ...., plus the probability that exactly $x-1$ of his friends go. This would yield: $P(W\mid S)=\sum_{i=y}^{x-1}P(\text{exactly } i \text{ of his friends go}\mid S)$ An arbitrary term will be of the form: $\binom{x-1}{i}\binom{m-x}{n-(i+1)}/\binom{m}{n}$ I have not tried to see if one can make this solution a bit nicer.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability" }
Can someone get addicted to codeine by taking a few tablets in a month? I've been having a migraine for a long time, tried different medications, different doctors. recently (for a few months) i noticed that the only medicine that really works for me when i have an attack is codeine. I take a codeine tablet when i have an attack, or 2 when the pain is really excruciating. My question is, is it possible to get addicted to this drug by taking about 4 tablets each month? The tablet is made of 300mg acetaminophen and 20mg codeine phosphate.
Addiction occurs due to chronic or frequent use, which means a lot more often than you're taking it. Since you're going weeks between doses, and you're taking very small doses, there's no danger of you developing a dependence because of the gaps between doses. Your body simply isn't getting it often enough to develop a physical dependence. The danger would come from using it daily or abusing it for recreational purposes. Don't do that and you should be fine. I've tried to find sources to support the above, but it's actually very difficult to find hard numbers. Nobody wants to put their finger on an amount that leads to addiction since it's going to vary from person to person, but the examples of addiction you can find will always involve daily or near daily use. Infrequent use as you're doing is never how addictions begin as long as they stay infrequent.
stackexchange-health
{ "answer_score": 4, "question_score": 3, "tags": "medications, risks, addiction, opioids opiates" }
Asset pipeline and storing stylesheets in the public folder I am trying to link 2 SCSS files located in the public folder to a html.erb view. I've tried the following methods with no luck... Attempt 1: <%= stylesheet_link_tag 'new_public_style', media: 'all'%> <%= stylesheet_link_tag 'publicStyles', media: 'all'%> Attempt 2: <link rel="stylesheet" media="all" type="text/css" href="new_public_style.scss"> <link rel="stylesheet" media="all" type="text/css" href="publicStyles.scss"> When I place the stylesheets within app > assets > stylesheets folder everything works fine.... but the main goal is to store these files in the public folder. Any suggestions as to what I am doing wrong?
Even if you got Rails to serve the SCSS files, it would not _process_ the SCSS files and generate the CSS that the browser wants. It must be in the asset pipeline to do that. You'll want to consider creating a separate asset manifest for your style guide.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby on rails" }
PsExec command issue between two windows servers I'm trying to run a batch file from remote Server1 onto remote Server2 (both are Windows server 2008 R2) located on common domain using below command: psexec \\Webtestserver2 -u sunny -p sunny2on_test -d -i cmd /c D:\files\script.bat **NOTE:** On both the servers Drive:D is shared on the common domain. and I get below output: PsExec could not start cmd on Webtestserver2 Logon failure: unknown user name or bad password. 1. Login username and password for both the Servers are exactly same. 2. I am able to connect to both the Servers seperately with RDP and **net use** command is also working between two servers. 3. Time is also synchronized throughout two servers. 4. I can ping each of them from the other one. What is wrong with my psexec command ?
You need to specify the domain name, e.g. `psexec -u DOMAIN\sunny ...`, otherwise psexec will try logging as SERVER2\sunny, I believe.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "batch file, windows server 2008, remote access, psexec" }
How to nested GROUP_CONCAT? I have this table: !enter image description here GROUP_CONCAT(DISTINCT mytable.gloss) AS gloss ... GROUP BY mytable.entry returns: !enter image description here How to get result in this way-grouped by entry and sense and divided by semicolon ';' sign?' !enter image description here
First, group by `sense`: SELECT entry, sense, GROUP_CONCAT(DISTINCT gloss) FROM mytable GROUP BY entry, sense entry sense gloss ----- ----- ------------ 1 1 Orange,Red 1 2 Blue 2 3 Green 2 4 Yellow,Ivory 3 5 Grey Then run another `GROUP BY` on that result: SELECT entry, MIN(sense) AS sense, GROUP_CONCAT(gloss, ';') AS gloss FROM (SELECT entry, sense, GROUP_CONCAT(DISTINCT gloss) AS gloss FROM mytable GROUP BY entry, sense) GROUP BY entry entry sense gloss ----- ----- ------------------ 1 1 Orange,Red;Blue 2 3 Green;Yellow,Ivory 3 5 Grey
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, sqlite, nested, concatenation" }
How to add Redmine and Jenkins as a task-repository to Mylyn in Eclipse? I'd like to use Mylyn for organizing my tasks and associated 'task contexts' in eclipse. I found on Wikipedia that integrating Jenkins and Redmine is possible. When I try to add a new repository, no connectors are shown, !enter image description here although I already installed a connector for Jenkins: !enter image description here In the **Add Task Repository** -list, there is also no entry for Redmine. So, how can I use Redmine and Jenkins repositories in Mylyn?
You will need the Redmine Mylyn Connector plugin for redmine . And you also will need to look at this guide. Note that the only way to make it connect correctly for me was to use the connector plugin I linked above and enabling the API secret key(you can enable it from your user account page)on the redmine instance .
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "eclipse, jenkins, eclipse plugin, redmine, mylyn" }
"Unsubscribe from emails like this" and "Edit email settings" links broken In the latest Developer Survey email from Stack Overflow, sent Jan 24, 2019, both the email preference links at the bottom result in "Invalid Request". "Leave Feedback" works as expected. I was able to reproduce this on Android (Gmail app) and on a desktop. Please see the images below. I'm not sure how to check if this is just me or universal. ![Links in question]( ![Resulting message](
Alex, we made a mistake when we were setting up our email campaign, and we sincerely apologize. The issue affected a few dozen people, including yourself. We are unsubscribing you (and others affected) on the backend, so you won't receive additional emails like this unless you explicitly opt in at a later date. Thank you for your patience.
stackexchange-meta
{ "answer_score": 3, "question_score": 3, "tags": "bug, status completed, email" }
Is there any standard to validate user input in php? Every where i find this "Never ever (ever) trust foreign input". They ask to validate every user input. But i am not sure what i should validate. Is there any standard to validate user input if the user enter any malicious code? Actually I want to know what this malicious code might be and how to validate? After doing a little research i found a standard password.php for password validation, `FILTER_VALIDATE_EMAIL` for email and `FILTER_VALIDATE_URL` for url validation. But for other input forms like name, textarea, phone number, username etc is there any standard to validate?
You should **validate** input based on your business rules (e-mail validation is such case). You should **escape** output based on your output media - when you sending data to browser you are escaping HTML, when you are sending to database - you are escaping db specific characters, etc.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "php, validation" }
DataAnnotation to ignore a column? I read < and there is mention of **StoreIgnoreAttribute**. I cannot find an implementation of this in EF6. So is there a data annotation to ignore a propery in a class from being mapped to a column in the table?
You can use the NotMapped Annotation public class Customer { public string FirstName {get;set;} public string LastName {get;set;} [NotMapped] public string FullName { set; get; } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "entity framework" }
Shopify - find a product ID in array Basically, what I'm trying to achieve is to find out if a product has been added to the cart, on the cart page. So if the cart array contains a specific ID, then return TRUE or FALSE. Any assistance will be great!
Shopify has an Ajax API. They also provide a full Javascript library you can freely pillage for code. In that code is a perfect example of getCart() which returns the cart contents. You are then free to check for your specific product ID by examining the contents of the cart.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "arrays, shopify" }
Grouping dataframe by each 6 hour and generating a new column I have this dataframe (type could be 1 or 2): user_id | timestamp | type 1 | 2015-5-5 12:30 | 1 1 | 2015-5-5 14:00 | 2 1 | 2015-5-5 15:00 | 1 I want to group my data by six hours and when doing this I want to keep `type` as: * `1` (if there is only 1 within that 6 hour frame) * `2` (if there is only 2 within that 6 hour frame) or * `3` (if there was both 1 and 2 within that 6 hour frame) Here is the my code: df = df.groupby(['user_id', pd.TimeGrouper(freq=(6,'H'))]).mean() which produces: user_id | timestamp | type 1 | 2015-5-5 12:00 | 4 However, I want to get `3` instead of 4. I wonder how can I replace the `mean()` in my `groupby` code to produce the desired output?
Try this: In [54]: df.groupby(['user_id', pd.Grouper(key='timestamp', freq='6H')]) \ .agg({'type':lambda x: x.unique().sum()}) Out[54]: type user_id timestamp 1 2015-05-05 12:00:00 3 PS it'll work only with given types: (`1`, `2`) as their sum is `3` Another data set: In [56]: df Out[56]: user_id timestamp type 0 1 2015-05-05 12:30:00 1 1 1 2015-05-05 14:00:00 1 2 1 2015-05-05 15:00:00 1 3 1 2015-05-05 20:00:00 1 In [57]: df.groupby(['user_id', pd.Grouper(key='timestamp', freq='6H')]).agg({'type':lambda x: x.unique().sum()}) Out[57]: type user_id timestamp 1 2015-05-05 12:00:00 1 2015-05-05 18:00:00 1
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, pandas, dataframe, group by" }
Cygwin hangs/freezes when installing: won't finish downloading packages !Cygwin installation dialog Just stays there. Restarting causes the same problem, and changing mirrors doesn't seem to help.
Simply use an ftp mirror instead of a http one. This seems to resolve the problem.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 4, "tags": "windows, windows 7, installation, cygwin" }
Implicit differentiation with Python 3? How can we derivate a implicit equation in Python 3? Example `x^2+y^2=25` differentiation is: `dy/dx=-x/y`, when try this: from sympy import * init_printing(use_unicode=True) x = symbols('x') y = Function('y')(x) eq = x**2+y**2-25 sol = diff(eq, x) print(sol) But it shows: 2*x + 2*y(x)*Derivative(y(x), x) How can get `-x/y`?
SymPy has the function `idiff` which does what you want In [2]: idiff(x**2+y**2-25, y, x) Out[2]: -x y
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "python, python 3.x, math, sympy, calculus" }
How to display SQL query that ran in query? I have come across a function before that displayed the exact SQL code that was used. In a loop for example, but can't remember. Can anybody tell me that function?
Hi **@Keith Donegan:** If I understand your question correctly I think this is what you are looking for? <?php echo $GLOBALS['wp_query']->request; ?> `$wp_query` is a global variable that contains the current query run by the loop. If you run the above code anytime while the loop is still active or even right after the loop it should give you the SQL from the loop. Just make sure you inspect it before letting something else run that uses `query_posts()` again.
stackexchange-wordpress
{ "answer_score": 163, "question_score": 128, "tags": "query, code, sql" }
Can yubikeys prevent cookie stealing? When you log into a website, it stores cookies that let your browser access the website without having the password. Given that some sites support yubikey for login, does it mean that the yubikey actively signs requests from my computer, or it just does a login and stores cookies? In the first option, it would be better because stealing cookies would be innefective as only my computer would continuely be able to talk with the website
No, it can't prevent cookie stealing. Yubikeys (and other 2FA schemes) can protect you against password leaks and phishing. Some variants, such as U2F will entirely make phishing impossible, while others will narrow the time window and success rate significantly. When it comes to cookie stealing, they do nothing. After you've authenticated and been given a token (often in form of a cookie), the 2FA does not enter again; you use the token for proving your identity.
stackexchange-security
{ "answer_score": 1, "question_score": 0, "tags": "passwords, cookies, yubikey, fido" }
Status of a conjecture about powers of 2 I recently saw a conjecture on a blog ( < ) which the author refers to as the 86 conjecture. The conjecture claims that all powers of 2 greater than $2^{86}$ have a zero in their base 10 representation. At first glance this seems like a numerical curiosity, and I wasn't sure that this was an interesting or deep mathematical question. I wanted to ask the community if they knew of any existing work that deals with either this type of question or something similar. I tried searching for 86 conjecture on Google and didn't get anything useful.
Richard Guy's _Unsolved Problems in Number Theory_ , Problem F24, mentions only that Dan Hoey has verified this conjecture for $2^n$ up to $n = 2,500,000,000$. Guy tends to be fairly complete in his references. Since he doesn't give any others I doubt there's much more out there. Several other related questions on decimal representations of powers of integers appear in F24 as well, most of which also appear to be open problems. There are some sequences in the On-line Encyclopedia of Integer Sequences mentioned, too; those might be worth chasing down.
stackexchange-math
{ "answer_score": 15, "question_score": 25, "tags": "number theory, open problem, conjectures" }
where to check "If Im using v4.29.0 or higher of the SDK, you instead need to add:" in < it says:- If you're using v4.29.0 or higher of the SDK, you instead need to add: <key>LSApplicationQueriesSchemes</key> <array> <string>fbapi</string> <string>fb-messenger-share-api</string> <string>fbauth2</string> <string>fbshareextension</string> </array> how can i know what is my SDK version ? ![enter image description here](
Just find the framework you are using and check Info.plist file inside it. You will find `Bundle version` field there - it is the version. For example, if it is Facebook SDK, you should have FBSDKCoreKit.framework in your project folder, just open it in Finder as a folder and you will find Info.plist there. Btw, you can find the version of any dependency in your dependency manager (if you use it). For example if you use pods, there is a file `Podfile.lock` with information about used frameworks and versions.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios" }
How to refer to a drop down list by name using jquery I need to refer to a drop down list by its name. html <select name="myName"></select>
Say you have a select element with id my-drop-down like this : <select name="myName" id='my-drop-down'></select> You can refer it like this: var referenceToDropDown = $('#my-drop-down'); OR like this: var referenceToDropDown = $('select[name = "myName"]');
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, select" }
Definition of conjugate homomorphisms? > Assume that $\phi_i: (X, x_0) \rightarrow (Y, y_0)$, for $i=0,1$ are freely homotopic. Prove that $\phi_{0*}$ and $\phi_{1*}$ are conjugate, meaning : > > There is $[\lambda] \in \pi_1(Y,y_0)$ with $\phi_{0*}([f]) = [\lambda]\phi_{1*}([f])[\lambda]^{-1}$ for every $[f]$ in $\pi_1(X,x_0)$. Is this saying a particular $[\lambda]$ for each different $[f]$? Or is it saying a specific $[\lambda]$ that works for every single $[f]$?
No, this is the same $[\lambda]$ for each $[f]$. This is really saying: $$\exists [\lambda] \in \pi_1(Y,y_0) \text{ s.t. } \forall [f] \in \pi_1(X,x_0), \phi_{0*}[f] = [\lambda] \phi_{1*}[f] [\lambda]^{-1}.$$ Try to prove it and you'll see why.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "abstract algebra, logic, algebraic topology, definition" }
Arm mount for GPS Watch I am a moderately fast runner and really do not want to add 55+ grams to my wrist. Arm is OK. Anyone have experience mounting the GPS watch on the arm - a la' iPod armband?
You could look into one of the fitness tracking wearables, like the FitBit (which is a very light wrist device) or some of the GPS tags, which can be the size of a key fob.
stackexchange-sports
{ "answer_score": 0, "question_score": 0, "tags": "running" }
The line through the center of circle $x^2+y^2-2ax=0$ and parallel to $x+2y=0$ meets the circle at $A$ and $B$. Find the area of $\triangle AOB$. > A straight line is drawn through the centre of the circle $x^2+y^2-2ax=0$, parallel to straight line $x+2y=0$ and intersecting the circle at $A$ and $B$. Then what is the area of $\triangle AOB$? I know that I am supposed to use the equation for center of the circle and then joining the centre with the origin or something like that. But I am unable to get answer through this. Please help.
$(x-a)^2+y^2=a^2\ \ast$ so that center is $C=(a,0)$ Hence line is $x-a=-2y$ so that we plug it in $\ast$ We have $y= \pm \frac{a}{\sqrt{5}}$ which plays a role of height and which is $y$-coordinate of intersection points $A,\ B$ So \begin{align*}{\rm Area}\ \Delta AOB &={\rm Area}\ \Delta AOC + {\rm Area}\ \Delta OCB\\\&= \frac{a}{\sqrt{5}}\cdot a\end{align*}
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "geometry" }
How to get diff in days include last day of given date in laravel? here is my code for getting diff in days $endDate = Carbon::parse($input['to_date']); $startDate = Carbon::parse($input['from_date']); $rentDays = $startDate->diffInDays($endDate); eg. fromdate= '29-11-2021' and to date ='03-12-2021' it returns 4 days. i want to get 5 days
You can use this $rentDays = $startDate->diffInDays($endDate) + 1; or $rentDays = $startDate->diffInDays($endDate->addDays(1));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "laravel, php carbon" }
Own Eq instance for binary trees I am trying to create my own `Eq` instance for binary trees: data Tree a = Empty | Node a (Tree a) (Tree a) instance Eq a => Eq (Tree a) where (Empty == Empty) = True (Empty == _) = False (_ == Empty) = False (Node x xl xr) == (Node y yl yr) = (x == y) && xl == yl && xr == yr I get the following error message: Parse error in pattern: Empty == Empty Could you tell me where I am wrong?
You must not use parentheses while defining an operator or a function. Keep in mind that a ???? b is just syntactical sugar for (????) a b Therefore, your patterns should be like this: Empty == Empty = True Empty == _ = False _ == Empty = False Node x xl xr == Node y yl yr = ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "haskell" }
Terminology For Web Development and General Programming/Software? EDIT: I should clarify. THe particular terms I listed below I fully understand. I also understand w3schools doesn't have the greatest information. These are just examples. I don't expect everybody to understand what an example is, but I hope the majority do. Does anybody have any resources listing terms related to programming and web development, or care to pitch in? Things like: Runtime Build time Framework Library Normalize I'm primarily a PHP developer so anything about that. I really am looking for general terms and specific terms related to web development, PHP, SQL, CSS, HTML. Appreciate any input. Couple I found: < <
Computing terminology from Wikipedia would be my suggestion for a resource though do keep in mind that some terms can be quite overloaded. As an example of overload, consider the term library. To some people it is a building with books in it while to others it is compiled machine code and the last L of a DLL. Thus beware of the context of the term.
stackexchange-softwareengineering
{ "answer_score": 4, "question_score": 0, "tags": "terminology" }
What is the maximum age of cats? My cat is four years old now. Someone told me that cats do not have a long life span. This made me so sad and worried. I want to know what is the approximate age of cats if they are fit and healthy.
The current Guinness World Record for longest-lived domestic cat belonged to Creme Puff, who lived to be 38 (1967 - 2005). The typical lifespan for indoor domestic cats is estimated at ~15 years.
stackexchange-pets
{ "answer_score": 28, "question_score": 12, "tags": "cats" }
Stunnel error: no start line I have a client application. The server application gave me a PEM file, and require me to connect using SSL. I use stunnel and specified the certification file to be the PEM file, and set client=yes. When I run stunnel I see the following error at startup: [!] error queue: : error: :SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib [!] SSL_CTX_use_PrivateKey_file: : error: :PEM routines:PEM_read_bio:no start line The PEM file looks ok, it has -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----. I use openssl x509 -inform PERM -in filename.pem -text to view the content and it looks ok. Any idea what could go wrong?
I guess you want to use the given certificate to verify the connection and thus you need to specify it as CAfile. What you probably did instead was to specify it as a client certificate which gets send to the server to authenticate the client. But this is just a guess, because you did not provide the configuration in your question. If you really want to use client authentication then you also have to provide the private key matching the certificate. If you don't specify a key it will look for it in the cert file, and in your case it did not find it there.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ssl, stunnel" }
adding sqlite database value to label in xamarin I am trying to make a Xamarin App and adding the sqlite database value to a label, but it only shows me the name of my app + ".Table". -> MyApp.Table the method: public async Task<string> GetSAsync(int id) { var s= await database.QueryAsync<Table>("SELECT Sign FROM Table WHERE ID = ?",id); return string.Join(Environment.NewLine, s); } the content page where I call the method protected async override void OnAppearing() { base.OnAppearing(); lbl.Text = await App.Database.GetSAsync(5); }
`QueryAsync<T>` is returning a list of records, assuming that ID is a unique key/value in the table, you can use Linq's `FirstOrDefault` to take the first record, if it exists, and _conditionally_ access the `Sign` field (column). Something like: string s = "Not Found"; var listOfTableRecords = await database.QueryAsync<Table>("SELECT Sign FROM Table WHERE ID = ?", id); s = listOfTableRecords.FirstOrDefault()?.Sign;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, sqlite, xamarin" }
Multiple sets of seams for multiple UVs? When UV mapping and lightmapping an asset for game use, I find that I need to erase my seams after UV mapping in order to place new seams for the lightmapping. Is there anyway to preserve them, or use two different sets?
You can mark your seams, unwrap to one UV map: ![A cube with a set of seams, and the UV map for the seams. The first UV map is select in the UV Maps menu.]( Then create a new UV map, clear your seams, designate new seams, and unwrap to the new UV map: ![A cube with a different set of seams, and the UV map for the new seams. A second UV map is selected in the UV Maps menu.]( Then select the first UV map, and use UV/"Seams from Islands" which will re-designate seams based on the first UV map, restoring the seams that you had before. ![The UV menu open with the "Seams from Islands" option selected. The first UV map in the UV Map menu is selected. The cube in the background has the first set of seams from the first UV map selected.](
stackexchange-blender
{ "answer_score": 9, "question_score": 7, "tags": "uv" }
Where to rollback a transaction in PDO? my problem is , i have a database design from this link is my database overdesigned? edit* ok maybe useing transaction ? but where should i put the rollback if it fails ? $dbConnect->beginTransaction(); $RegisterInsert = $dbConnect->prepare("INSERT INTO companies ( `name`, `address`, `email`, `phone`, `link`, `verified`) VALUES ( :name, :address, :email, :phone, :link, :verified)"); $RegisterInsert->execute($RegisterData); $RegisterData2['CID'] = $dbConnect->lastInsertId(); $RegisterInsert = $dbConnect->prepare("INSERT INTO users_companies ( `UID`, `CID`, `role`) VALUES ( :UID, :CID, :role)"); $RegisterInsert->execute($RegisterData2); $dbConnect->commit(); where should i put the rollback ? Thanks
A transaction should end with either a `rollback()` or a `commit()`, (only one of them) Its usually used with an `if...else` statement as logically only one of them should be executed. $dbConnect->beginTransaction(); //somecode //$dbConnect->execute( $someInsert ); //some more code //$result = $dbConnect->execute( $someSelect ); //$nextRow = $result->fetchRow(); //either commit or rollback! if( $someResultCheck == true ) $dbConnect->commit(); else $dbConnect->rollback(); Transactions are usually used when there is a complex logic involved with queries. In case you are using MySQL, make sure you are not using MyISAM engine for tables, as it doesn't support transactions.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "php, mysql, database, insert, pdo" }
Show MessageBox message and ignore invalid characters in TextBox I need the user to type only integer numbers in a TextBox. I already have that validation working, the problem is that I want to show a MessageBox to the user if he/she type a point, a letter, or the symbols !@#. The MessageBox is shown to the user if an invalid character is typed but the letter still appears in the TextBox, which I don't want. Could you please help me and tell me what's wrong with my code please Private Sub txtCMS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCMS.KeyPress If (e.Handled = Not IsNumeric(e.KeyChar) And Not Char.IsControl(e.KeyChar)) = False Then MessageBox.Show("Favor ingrese solo numeros", "Pablo Tobar says...", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub
I use this code: Private Sub txtCMS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCMS.KeyPress If Not (IsNumeric(e.KeyChar) OrElse Char.IsControl(e.KeyChar)) Then e.Handled = True MessageBox.Show("Por favor, ingrese sólo números", "Pablo Tobar says...", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub Hope this can help you! Bye.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vb.net" }
Selenium Add-on/Extension in Chrome Browser How to execute Add-on automatically in Chrome, Is there any shortcut key to execute.? // In below lines i am adding .crx file and after that loading into chrome browser chrome_options.add_extension("/path/.crx"); driver=webdriver.Chrome(chrome_options=chrome_options) So, What is happening after Add-on loaded we have to click plugin icon to activate and perform operation. But i need to activate without click into plugin icon.
Always read the docs first! from selenium import webdriver from selenium.webdriver.chrome.options import Options coptions = Options() coptions.add_extension("path/to/extension/file.crx") driver = webdriver.Chrome(chrome_options=coptions)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python 3.x, selenium, selenium chromedriver" }
Differentiate between user types I have the following code which I have been trying to modify for use with two users (bottom half). What I want to happen is that when a user logs in , their Login_ID is found in the table and then their User_Role_ID is found. If its 1 it goes to a certain page , if its 2 it goes to another page. if(count($_POST)>0) { $result = mysqli_query($conn, "SELECT id,Login_ID,Name,User_Role_ID FROM user WHERE Login_ID='" . $_POST["id"] . "' "); $row = mysqli_fetch_array($result); if(is_array($row)) { $_SESSION["Login_ID"] = $row[Login_ID]; } else { echo "Invalid ID!"; } } if($_SESSION["User_Role_ID"] == "2") { header("Location: home.php"); } else if($_SESSION['User_Role_ID'] == 1) { header("Location: www.google.com"); }
Maybe you could use a switch $result = mysqli_query($conn, "SELECT id,Login_ID,Name,User_ID_Role FROM user WHERE Login_ID='" . $_POST["id"] . "' "); $row = mysqli_fetch_array($result); if(is_array($row)) { $_SESSION["Login_ID"] = $row[Login_ID]; switch ($row["User_ID_Role"]){ case "1": header("Location: www.google.com"); break; case "2": header("Location: home.php"); break; } } else { echo "Invalid ID!"; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, mysqli" }
Linker error in OpenCV with Visual Studio I am trying to do some image rectification using OpenCV .I got some code from < but the problem is the moment I include CvCalibFilter in my code it starts to give me linker error.More precisely this is what it says :- > : error LNK2001: unresolved external symbol "public: virtual __thiscall CvCalibFilter::~CvCalibFilter(void)" (??1CvCalibFilter@@UAE@XZ) I saw some posts of people having the same problem but could not find a solution anywhere.Can someone help? Thanks! P.S. I installed OpenCV to work with Visual Studio as mentioned in the tutorial.
In visual studio go to... _Project > 'Your Project Name' Properties... > Configuration Properties > Linker > Input >_ Then go to _Additional Dependencies_ and add the appropriate .lib files, these should do the trick: `cv200.lib cxcore200.lib highgui200.lib`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "visual studio, opencv" }
Form on Sharepoint Library to be completed by different users I have developed an editable pdf form for my client. The user fills in an PDF form and then the form gets uploaded to SharePoint to start a workflow. In the next step of the workflow, a task is assigned to another user that needs to add information to the submitted pdf form. The user needs to open the editable pdf form, complete the fields and submit. Then the workflow needs to continue. But when the user receives the task with that form, the only option is for the user to download the editable pdf form and complete it, but then how do they 'overwrite' the current form in the library? Or is there a way that the user can open the editable pdf form straight from SharePoint to complete the required fields? Maybe someone has an out of the box alternative for me?
For you scenario, maybe you can first make the workflow just end here. Create another library which receives the submitted pdf, and add a new workflow here when triggered a new file is uploaded and then finish the rest process.
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint enterprise, pdf" }
How to run a cakephp app on an apache server? [UBUNTU] On 16.04 Ubuntu, I want to run a cakephp app on the localhost to make some modifications. How can I do that? Installed application has files in 3 different directories: 1. opt 2. etc 3. usr I know apache files run on var/www/html but how can I move those installed files there to run the application? As far as I know, index.php is the start file of php projects but for cakephp, there is a default.ctp file for the main program page, of course there are other index.php files for other pages, and I am really stuck with that. Thanks in advance.
Copy your CakePHP project to a subfolder in Apache document root, eg `/var/www/html/myproject`. Make sure you have mod_rewrite enabled. Then you should be able to access your project at < More info: CakePHP Installation As for files located in etc, opt and usr, it depends what they are. If you can share what you have there, please do it, as it will help to decide what to do with them.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, linux, ubuntu, cakephp, localhost" }
"no such file or directory, sml" in emacs I installed `emacs 24.3` and SML-MODE. When I open a `.sml` file in `emacs` and try to run buffer using `Ctrl`+`C` and `Ctrl`+`S` it gives: Searching for program: no such file or directory sml emacs is extracted at /etc/emacs-24.3 and sml is extracted at /home/user/softwares Also I am unable to run sml from terminal. I think I have to add the path of SML to emacs somehow. Is that right? or do I need to do something else?
Yes, customize user option (variable) `exec-path`: `C-h v exec-path`. See also the Emacs manual, node `Shell`: `C-h r g Shell`.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "emacs" }
touch command is not executing with ansible In this ansible-playbook, the first task is not executing but the second task is executing fine how can debug the issue - name: Transfer and execute a script. #ansible-playbook -vvv createNode.yml --extra-vars "MASTER_URL= MASTER_USERNAME=rajendar MASTER_PASSWORD=@Oracle38 NODE_NAME=testNode14 NUM_EXECUTORS=2" hosts: 127.0.0.1 vars: tasks: command: touch /Users/rajendartalatam/Desktop/anible.text tasks: - name: Copy and Execute the script command: sh ./nodeCreate.sh {{MASTER_URL}} {{MASTER_USERNAME}} {{MASTER_PASSWORD}} {{NODE_NAME}} {{NUM_EXECUTORS}}
_`tasks:`_ is actually the list of tasks. The correct syntax is below tasks: - command: touch /Users/rajendartalatam/Desktop/anible.text - name: Copy and Execute the script command: sh ./nodeCreate.sh ...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ansible" }
Difference between onLoad and ng-init in angular I am learning angular. I don't understand what is difference between onLoad and ng-init for initialization of a variable. In which scope it creates this variable. `For example` <ng-include onLoad="selectedReq=reqSelected" src="'partials/abc.html'"></ng-include> `OR` <ng-include ng-init="selectedReq=reqSelected" src="partials/abc.html"></ng-include> Please also give me some idea about isolated scope.
`ng-init` is a directive that can be placed inside `div`'s, `span`'s, whatever, whereas `onload` is an attribute specific to the `ng-include` directive that functions as an `ng-init`. To see what I mean try something like: <span onload="a = 1">{{ a }}</span> <span ng-init="b = 2">{{ b }}</span> You'll see that only the second one shows up. An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
stackexchange-stackoverflow
{ "answer_score": 52, "question_score": 40, "tags": "angularjs" }
Linq in C# Query needed - One to many table relationship, one to many records needed need help to accomplish this in linq. I have 3 tables. 1. Customers 2. CustumerOrder 3. OrderDetails I need to list in one query all customers ( only if they have placed atleast one order) with all the orders for each customer only if order value is greated than 100. Regards, Harsh
I'd say you want something like this: from c in Customers where c.CustomerOrders.Any() select new { customer, Orders = from co in c.CustomerOrders where co.TotalPrice > 100 select co.OrderDetails } Or, if you don't have an "TotalPrice" column in the CustomerOrder table, replace the inner query with this: Orders = from cp in c.CustomerOrders where co.OrderDetails.Sum (od => od.Price) > 100 select co.OrderDetails Edit: if you want to include customers only with at least one order with OrderTotalPrice more than 100, use a **let** statement: from c in Customers let highValueOrders = from co in c.CustomerOrders where co.TotalPrice > 100 select co.OrderDetails where highValueOrders.Any() select new { customer, highValueOrders } You can add more conditions in a similar fashion.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, linq" }
Returning a list of tuples of frequency, where did I do wrong? I have to do an exercise that ask me to do a function that find the frequency of consecutive values on a list and return a list of tuples where I have to show how many times it was the repetition. Input: [1, 1, 1, 3, 5, 1, 1, 3, 3] Output: [(1,3) , (3,1) , (5,1) , (1,2) , (3,2)] Code: def empaquetar(l): lista = [] for i in range(len(l)-1): cont = 0 j = i + 1 while l[i] == l[j] and j<len(l)-1: cont += 1 i += 1 j += 1 if cont > 0: lista.append((l[i], cont + 1)) else: lista.append((l[i],1)) return lista Well, what I wrote does not quite exactly return what I want and I can't find a solution but I search a lot, for example the tool Counter from collection or something like. I need help, any suggestion?
Not thoroughly tested, but here is a try prev_val = None counter = 1 for curr_val in input_list: if prev_val is not None: if prev_val != curr_val: output_list.append((prev_val, counter)) counter = 1 else: counter += 1 prev_val = curr_val output_list.append((prev_val, counter)) print (output_list)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, list, algorithm, tuples" }
$|\cosh z|^2 = \cosh^2x + \sin^2y$ I'm trying to prove : $|\cosh z|^2 = \cosh^2x + \sin^2y$ I know that: $|\cos z|^2 = \cos^2x + \sinh^2y$ My procedure is: $|\cosh z|^2 = |\cos iz|^2 = \cos^2y + \sinh^2x$ And since: $\cos^2x + \sin^2x = 1$ $\cosh^2x - \sinh^2x = 1$ So I get: $|\cosh z|^2 = \cosh^2x - \sin^2y$ What is wrong with my procedure?
$|\cosh z|^2 = \cosh^2x + \sin^2y$ can't be right, as this would mean $|\cosh z|^2 \geq 1$ for all $z \in \mathbb{C}$, which is impossible by Liouville. What you computed seems right, though.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "complex numbers, hyperbolic functions" }
Matching complex patterns with intent filters and data My intent filter looks like this: <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.SENDTO" /> <category android:name="android.intent.category.DEFAULT"></category> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" android:host="mywebsite" android:pathPattern="/oauth/authorize?.*oauth_verifier=.*" /> </intent-filter> however this fails to match. If I remove the **?** and everything after it, it matches but the site I am matching uses that URL several times, and the only one I am interested in is the oauth_verifier. Is there anyway to make an intent filter match the bit (query parameters?) after the _/oauth/authorize_
> Is there anyway to make an intent filter match the bit (query parameters?) after the /oauth/authorize No, sorry.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "android" }
Are big lifts effective for hypertrophy training? It is my understanding that the goal of hypertrophy training is to maximize time under tension to stimulate muscle growth. However, most heavy compound movements such as deadlift seem to do the opposite as they can only be performed for few reps. For example, the push-pull-legs routine I'm currently following contains 1 set of deadlift at 80% of 1 rep max. This sounds more like a strength/powerlifting training. Is there some real advantage of including these big lifts in hypertrophy program?
See my answer to a previous question, which also answers your question: Confusion about reps vs time under tension: aren't these two things contradictory? In short, the idea of long times under tension being important is nonsense, made up by Charles Poliquin. You can achieve hypertrophy over a huge range of relative loadings, as long as you're working similarly close to failure. 80% of 1RM isn't even close to being too heavy to be useful for hypertrophy. It's really only at 90+% of 1RM that you're getting to the point where you're practicing maximal strength more than you are working on hypertrophy.
stackexchange-fitness
{ "answer_score": 5, "question_score": 3, "tags": "bodybuilding, hypertrophy, compound exercises" }
Assigning values to multiple variables I have a string myString that can contain a variable number of pairs separated by commas, such as: "a=1,b=2,c=3" or "c=5,b=4" or "t=12". I also have a set integer variables, named a, b, c, ..., z, all set to 0. I want to analyze myString and assign the values from string to each variable. I can only thing of an inefficient way of doing this, using switch and case (i.e. if myString contains 'a', extract value of 'a' and assign it to variable named 'a'). Any ideas of how to write better code for this operation? void Test(string myString) { int a, b, c, d; a = b = c = d = 0; string[] varNames = {"a", "b", "c", "d"}; for(int i = 0; i < varNames.Length; i++) { if(myString.IndexOf(varNames[i]) >= 0) { VariableWhoseNameIs(varNames[i]) = 3; } } }
Why does the variable names matter? You can just store the pairs in a Dictionary<string, int> Dictionary<string, int> values= new Dictionary<string, int>() { { a, 1} { b, 2} }; The when you want to retrieve var value = values[myString].value;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, string" }
Disable silent mode on iPhone? How do you disable the user from turning the phone on silent? (switching the switch on the top left of the phone?) I want my app to always play sound no matter what the state of that switch is. Is this possible? Thanks in advance...
Please search stackoverflow or the web for similar questions before posting a new one, this question has already been covered: Play sound on iPhone even in silent mode iphone, how to play sound even in silent or mute mode? Be careful about overriding the silent mode switch and playing audio. Apple may not like you doing this, depending on the context; if they don't like it, you will fail app review. Is there a good reason to play audio when in silent mode in the context of your app?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, ios, audio, silent" }
Pytorch - Stack dimension must be exactly the same? In pytorch, given the tensors `a` of shape `(1X11)` and `b` of shape `(1X11)`, `torch.stack((a,b),0)` would give me a tensor of shape `(2X11)` However, when `a` is of shape `(2X11)` and `b` is of shape `(1X11)`, `torch.stack((a,b),0)` will raise an error cf. "the two tensor size must exactly be the same". Because the two tensor are the output of a model ( **gradient included** ), I can't convert them to numpy to use `np.stack()` or `np.vstack()`. Is there any possible solution for least GPU memory usage?
It seems you want to use `torch.cat()` (concatenate tensors along an existing dimension) and not `torch.stack()` (concatenate/stack tensors along a new dimension): import torch a = torch.randn(1, 42, 1, 1) b = torch.randn(1, 42, 1, 1) ab = torch.stack((a, b), 0) print(ab.shape) # torch.Size([2, 1, 42, 1, 1]) ab = torch.cat((a, b), 0) print(ab.shape) # torch.Size([2, 42, 1, 1]) aab = torch.cat((a, ab), 0) print(aab.shape) # torch.Size([3, 42, 1, 1])
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 8, "tags": "python 3.x, reshape, pytorch, tensor" }
Using DHCP with Multi-Homed NICs I am trying to steer away from our current manual addressing system and embrace the decades-old wonder of DHCP. In our domain and even at my home network DHCP is great - I can use address reservations to handle the need for static IP. However, in our production datacenter, many of our hosts have multi-homed NICs, so it is one MAC address with multiple IP's. 1. Is it possible to configure this as a reservation in DHCP? (ie, multiple reservations for one MAC address?) 2. If not (1), if it is easy to install as many NICs as IPs in the hosts that are currently multi-homed (they are all VM's), is it advisable to do this and then use DHCP address reservation? The consensus seems to be: always use DHCP, so I am trying to get us there.
DHCP servers don't allow you to have multiple IP when annoucing a single MAC address. You have to user identifiers, but not every clients and servers can use them. The usual trick is to annouce different MAC when you do the DHCP request, but with a virtual machine it is simplier to add another NIC. It is very easy to add NICs, and this is common practice. If you want to use identifiers, in your `dhclient.conf` file: interface "eth0:1" { send dhcp-client-identifier "xxxx-eth0:1"; } interface "eth0:2" { send dhcp-client-identifier "xxxx-eth0:2"; } Obviously, this don't work with Windows. Maybe there is another method for this OS.
stackexchange-serverfault
{ "answer_score": 4, "question_score": 4, "tags": "dhcp, nic, mac address, dhcp server, multi homed" }
Can I upgrade directly to MacOS Monterey if I am using MacOS BigSur 11.0.1 I am using MacBook Air 2017 I have macOS BigSur 11.0.1 installed on my system and I have not updated my macOS to BigSur 11.6 ![macOS BigSur Update]( and as Apple released the new macOS Monterey tomorrow so can I directly download macOS Monterey instead of downloading macOS BigSur 11.6 that takes 6.17 GB ![macOS Monterey]( And will skipping macOS BigSur 11.6 hamper my system?
As I wrote in the comment earlier; Yes, you can upgrade your MBA to Monterey from Big Sur 11.0.1 without any problem (At least for OS. Apps still should have to be compatible with Monterey.) The first image you attached only says _Install Now_ , which means it still not applied (or changed any of system files) to your MBA; it just downloaded update file for 11.6.1. The only problem I could think of is, as I wrote earlier, the compatible of apps. I'm sure most of apps should work with Monterey, but some of apps still isn't optimized to Monterey. So, if you have any apps that is critical to your job/hobby/etc, I'd advise you to check it if it's compatible to Monterey.
stackexchange-apple
{ "answer_score": 1, "question_score": 2, "tags": "macos, software update, big sur, monterey" }
Changing the PH of mead for fermenting necessary? I’m currently creating a batch of mead. I’ve watched a lot of videos about the process. I’ve seen some people do it because they said you need to have it between 3.6 and 3.9 ph. And some just don’t bother and it turns out great. In the first batch i’m making right now i’ve made no changes to the ph level. And of course made sure to sterilize everything beforehand. The biggest part i’m sort of concerned about is, _do i actually need to change the PH of my mead to prevent bacteria to grow in there or will the alcohol take care of that._
IMHO mead does not generally need any adjustment of pH levels to ferment correctly. It is generally fermented to have a similar level of alcohol to a strong wine - which will not generally support bacterial growth. As the fermentation progresses the pH of the mead will naturally drop due to dissolved carbon dioxide. Mead has been made this way for a long time, long before pH or bacteria had been discovered. Good sanitation of containers and ingredients - and pitching an active yeast - is IMHO all that is required.
stackexchange-homebrew
{ "answer_score": 5, "question_score": 4, "tags": "fermentation, mead, bacteria, ph, acidity" }
How to customise drupal 7 user registration, login, password reset form How to customise drupal 7 user registration, login, password. Further I need to add some extra fields to the registration and how to do the field validation.
You can add extra fields to registration form here. admin/config/people/accounts/fields Configuration => People => Account settings => Manage fields
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "php, drupal 7" }
Smallest orbital rockets by height? Which orbital rocket is the smallest in height (or length) that ever launched? Would be nice to know the second and third place too. Similar questions: * Smallest orbital rocket by diameter? * Smallest orbital rocket by mass * Smallest launch vehicle by dry mass * Smallest sounding rocket to reach space by height? * Do you know a rocket for launching femto and pico satellites smaller than the SS-520? * What are some small rocket engines?
That is as far as I can tell the SS-520), placing a 4kg payload into LEO in 2018, with the total length of the launch vehicle being 9.54 meters. If this record has not been surpassed after 2018, it still stands.
stackexchange-space
{ "answer_score": 6, "question_score": 3, "tags": "launch vehicle, record" }
Is "In case of the developments in medical research..." grammatically correct? > **In case of** the developments in medical research, many patients would have died. My textbook presented three other alternatives: > **If it weren't for** … > > **Without** … > > **Unless** … and said that **in case of** is correct. However, **in case of** seems unsuitable to me. The correct form I can think of is: > **If it hadn't been for** the developments...
Given your choices of > In case of > If it weren't for > Without > Unless The only choices which make sense are > _If it weren't for_ the developments in medical research > _Without_ the developments in medical research Using > _In case of_ the developments in medical research would mean "in the event that development in medical research happens", not that it already _has_ happened, which is a prerequisite for "lives to be saved". Which textbook are you using?
stackexchange-ell
{ "answer_score": 1, "question_score": 1, "tags": "grammaticality, conditional constructions, grammaticality in context" }
ScatterPlot doesn't let me tap plot points or move graph I'm trying to use a scatter plot from Core Plot in my iOS application. I set up Core Plot as the Core Plot wiki says, and then I copy PlotItem.h/m, PlotGallery.h/m and SimpleScatterPlot.h/m from the included Plot Gallery project into my project. The code CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme]; SimpleScatterPlot *scatterPlot = [[SimpleScatterPlot alloc]init]; [scatterPlot generateData]; [scatterPlot renderInLayer:hostView withTheme:theme]; runs, and the graph view is shown in my app. But I cannot move the graph view around or tap the plot points as in the Plot Gallery project. How do I set this up right?
The Plot Gallery is a poor starting point for a simple Core Plot demonstration. It has a lot of extra "stuff" to support generating a table view with thumbnails of all the different plots. ~~The`-renderInView:withTheme:` method is used to make the thumbnail images for the table view. It renders the graph as an image which is why you lose interactivity.~~ Unless you need the flexibility to quickly add new plots to your app and easily support both MacOS and iOS, I would recommend using one of the other examples as a starting point. The architecture is much simpler and easier to understand. You need to have a `CPTGraphHostingView` in the visible view hierarchy. Set your graph as its `hostedGraph`. Look at any of the other example apps to see how to set up the hosting view. The graph setup and datasource code in the Plot Gallery plots (e.g., SimpleScatterPlot) is fine and should work anywhere.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "objective c, cocoa touch, graph, core plot, scatter plot" }
How to make Cypress execute an API script on a page? I’m currently trying to convert my Protractor code into Cypress code. Some of my Protractor code involve making the webpage execute an API script for instance: import { browser } from “protractor”; // this is the import I used browser.executeScript(‘arguments[0].click()’;, this.closeButton); // this is for button clicking browser.executeScript(‘localStorage.setItem(“example-boolean”, “false”)’); // this is for setting a value to false Is there a Cypress equivalent for these lines of code?
Some inspiration: import "cypress-localstorage-commands"; cy.get('#yourCloseBtnId').click(); // Clicking on the element with an ID #yourCloseBtnId cy.setLocalStorage("example-boolean", false); // Setting an item in the local storage
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "typescript, automated tests, cypress, end to end" }
Do Karnaugh maps use a base ten numbering system? Do Karnaugh maps use a base ten numbering system??
No, binary Gray code.
stackexchange-electronics
{ "answer_score": 9, "question_score": 3, "tags": "karnaugh map" }
How to hide which have calc css? I wanted to hide the element which have calc css3: nav{width: calc(100% - 20px); height: 50%;} I tried this: $('*').filter(function() { return $(this).css('width') == 'calc'; }).css("display","none"); But seems wrong way to do? demo
`css` method returns the _computed_ value of the properties, you should read and filter the initial CSS rules: var s = document.styleSheets[1], // the second stylesheet (for jsfiddle) rules = s.cssRules, selector = [], l = rules.length; for ( var i = 0; i < l; i++ ) { if ( rules[i].style['width'].indexOf('calc') > -1 ) { selector.push( rules[i].selectorText ); } } $( selector.join() ).hide(); <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "jquery" }
Extjs listener doesen't work on 6.2.1 modern toolikit I'm trying to add a listener to a button, using framework 6.2.1 modern toolkit, but it doesen't work, nothing happen. Ext.application({ name: 'MyApp', launch: function(){ var view = Ext.Viewport.add({ items: [] }) var button = Ext.create('Ext.Button', { text: 'My Button', listeners: { click: function(){ Ext.Msg.alert('Button', 'clicked'); } } }) view.add(button);
Whenever working with a specific ExtJS toolkit, please keep in mind that the two toolkits are very different. As per the documentation, there is no click event on the button in the modern toolkit: < The click event is only on the button in the classic toolkit: < For the modern toolkit, a click on the button fires (in that order) the `release` and the `tap` event.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "extjs, listener" }
Accessing properties from object in `for`–`in` loop results in `undefined` I have these two classes: class Node { constructor(nodeId){ this.nodeId = nodeId; this.adjacencies = []; } connectToNode(nodeToConnectTo){ this.adjacencies.push(nodeToConnectTo); } } class Graph{ constructor(nodes){ this.nodes = nodes; } printGraph(){ for (let node in this.nodes){ console.log(node.nodeId); } } } I’m simply trying to call `printGraph` to print all the `nodeId`s this way: let node1 = new Node('1'); let node2 = new Node('2'); let node3 = new Node('3'); const arr = [node1, node2, node3]; let graph = new Graph(arr); graph.printGraph(); But it’s printing `undefined`. I can’t seem to figure out why it isn’t simply printing the `nodeId`.
you are using the wrong for loop. Try changing it to: printGraph(){ for (let node of this.nodes){ console.log(node.nodeId); } } A for..of loop should loop over the node the way you want. Result: 1 2 3
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, javascript objects, for in loop" }
What is Solidity's equivalent of raw_call()? I'm wondering, does Solidity also have a raw_call() function like Vyper which sends a byte[] array (payload) as calldata to a specific address? If so, what is that function? Is it also raw_call()?
From the Solidity docs: > _**< address>.call(bytes memory) returns (bool, bytes memory)**_ > > Issue low-level CALL with the given payload, returns success condition and return data, forwards all available gas, adjustable The `call` function is available on the address primitive and it allows you to call an address with an arbitrary payload
stackexchange-ethereum
{ "answer_score": 0, "question_score": 1, "tags": "solidity, calldata, vyper, function" }
Can I use the word "Applicator" to describe a person in the following context? Here's the context in question, please read on: "The final proof is in the listening and John knows this. This knowledge makes him a designer in constant dynamic relationship with what he makes, rather than an **applicator** of proven scientific knowledge." Can I use "Applicator of knowledge" to describe a person? How does it sound to native speakers? If it does not sound right, how else may I write the same sentence? Thanks a lot, Maryam
The answer is both _technically no_ and _aesthetically no_. Not taking into account the fact that 'applicator' refers nearly exclusively to a device rather than a person, the word itself in the given context is too awkward and clunky anyway. I suggest using another word in its place or reconstructing the clause in question as a whole. If the latter option is your preference (which might produce a better overall sentence), you could say something like the following: _"... rather than a logician concerned only with the rigid knowledge of what is. For John, the goal always lies in what could be."_
stackexchange-english
{ "answer_score": 2, "question_score": 1, "tags": "single word requests, word choice, nouns, meaning in context, adjectives" }
numpy convert 2D Integer Record to 2D floating point Record I want to convert the record `[(1, 2, 3) (2, 2, 3)]` which is of integer type to floating type array as `[(1.0, 2.0, 3.0), (2.0, 2.0, 3.0)]`. However when I give the command `c.astype('float')` what I get at the output is `rec.array([ 1., 2.])`. Why the other elements are deleted from the array? Could someone please give me the correct solution? Am I doing it the right way? **Update** I created the record from 3 different arrays like this - `d=np.rec.fromarrays([a, b, c], names='x,y,z')` in order to sort them and do some operations. Here is the complete code - a=[1,2] b=[2,2] c=[3,3] d=np.rec.fromarrays([a, b, c], names='x,y,z') print d d.astype('float') print d
Inelegant but (apparently) working: In [23]: import numpy as np In [24]: a=[1,2] In [25]: b=[2,2] In [26]: c=[3,3] In [27]: d=np.rec.fromarrays([a, b, c], names='x,y,z') In [28]: d Out[28]: rec.array([(1, 2, 3), (2, 2, 3)], dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')]) In [29]: d.astype([(k, float) for k in d.dtype.names]) Out[29]: rec.array([(1.0, 2.0, 3.0), (2.0, 2.0, 3.0)], dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, numpy" }
How to fetch * records from a table which are not present in other two tables I want to fetch all records with all columns of a table, Records which are not in the other 2 tables. Please help. I have tried below query, it is working fine for comparing one column. But I want to compare 5 columns. select * from A WHERE NOT EXISTS (select * from B b where b.id=a.id) AND NOT EXISTS (select * from C c where c.id=a.id)
A general solution might look like: SELECT t1.* FROM table1 t1 WHERE NOT EXISTS (SELECT 1 FROM table2 t2 WHERE t2.id = t1.t2_id) AND NOT EXISTS (SELECT 1 FROM table3 t3 WHERE t3.id = t1.t3_id); This assumes that you want to target `table1` for records, ensuring that no matches can found in `table2` and `table3`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server" }
How set shadow color of header in TeeChart? Using `TChart` in Android. I'm trying to add a shadow to the chart header, but I can't set its color. It's always white! // chart.getHeader().getFont().getShadow().setColor(Color.fromArgb(0xffff0000)); chart.getHeader().getFont().getShadow().getBrush().setVisible(true); chart.getHeader().getFont().getShadow().getBrush().setColor(Color.fromArgb(0xffff0000)); chart.getHeader().getFont().getShadow().setSize(2); chart.getHeader().getFont().getShadow().setSmooth(false); What more do I need to get a shadow of a different color?
Right. It seems that the Title Font Shadow is always drawn in the same color than the Title and if you try to change the color of the shadow it doesn't apply. I've added it to the defect list to be revised for future releases (TJ71016479). I recommend you to be aware at the following channels for new release announcements and what's implemented on them: * Support forum * RSS news feed * Twitter * Facebook
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java, android, teechart" }
Question about Showing closed sets using the closed set formulation of topology I am trying to show that the set $B^2= \\{x^2+y^2 \leq 1\\}$ is closed via the closed set formulation of continuity. I think the book means that if $f:X \rightarrow Y$ then if V is closed in Y then $f^{-1}(V)$ is closed. What I think I must do is define a function f in x,y such that maps a closed set to the unit circle. So I guess something say like $f(x,y)=x^2+y^2-1$ where x,y $\in [0,1]$. Is this on the right track?
It is close to it. If $f: (x,y) \mapsto x^{2}+y^{2}: \Bbb{R}^{2} \to \mathbb{R}$, then $f$ is continuous and $B^{2} = f^{(-1)}[0, 1]$; hence $B^{2}$ is closed in $\Bbb{R}^{2}$.
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "general topology" }
Dealing with constants inside functions I want to define a constant if something is true, and use its value inside a "system(""); For example: #ifdef __unix__ # define CLRSCR clear #elif defined _WIN32 # define CLRSCR cls #endif int main(){ system("CLRSCR"); //use its value here. } I know there is `clrscr();` in conio.h/conio2.h but this is just an example. And when I try to launch it, it says `cls` is not declared, or that CLRSCR is not a internal command (bash) Thanks
Constant is an _identifier_ , not a _string literal_ (string literals have double quotes around them; identifiers do not). Constant value, on the other hand, is a string literal, not an identifier. You need to switch it around like this: #ifdef __unix__ # define CLRSCR "clear" #elif defined _WIN32 # define CLRSCR "cls" #endif int main(){ system(CLRSCR); //use its value here. }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "c, system, constants, c preprocessor" }
how can i clear content of fileupload widget in gwt + IE? I want to clear content of fileUpload widget. I used- FileUpload file = new FileUpload(); file.getElement().setPropertyString("value", ""); but it only works in chrome and not in Internet Explorer8. is there any other workaround for this?
You can wrap the _FileUpload_ in a _FormPanel_ and then reset the _FormPanel_ to clear the value of _FileUpload_. Example final FormPanel formPanel = new FormPanel(); FileUpload fileUpload = new FileUpload(); formPanel.add(fileUpload); Button button = new Button("Clear value"); button.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { formPanel.reset(); } });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "java, internet explorer, gwt, file upload" }
Asyncronously receiving data in an ASP.NET MVC application I'm looking for the best way to constantly check if data has been sent to our ASP.NET MVC application from a server. I would like to asynchronously check for data and update the view when data has been read. I'm currently using a `TcpClient` to make a connection, and making the connection in the inherited custom base controller. Currently though I have to refresh the page for the updating of the view to take place. Would there be a proper AJAX solution? or do I need to move the connection to the `ActionMethod`?
I would probably use jQuery to query some action at a specified interval and update the page accordingly. I don't know what kind of data you're talking about, but let's look at a simple example. From you're question, it sounds to me like you're trying to do the following: Suppose you are building Twitter and want to show the newest Tweets on the homepage. Well, you could have a script that just does a jQuery.GetJSON call to some URL (let's call it twitter.com/latest5tweets) that gets the latest 5 tweets. Then you would have a callback function that would take those tweets and paint them on the screen -- perhaps using some sort of nifty slide effect to remove the older ones from the screen and add the new ones. Does that help?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, .net, asp.net mvc, ajax" }
SQL Double-Outer Join? I have two tables A and B... A and B can be joined by a common column. A and B will have some rows that match on the join column. But A has some rows that B doesn't have, and B has some rows that A doesn't have. A LEFT OUTER JOIN from A to B will give all rows in A, filling in NULLS for the B columns that couldn't be matched. A RIGHT OUTER JOIN gives all rows in B, filling in NULLS for the A columns that couldn't be matched. I would like to receive ALL rows from both A and B, while returning NULL for the A columns on rows that are only in B, and NULL for the B columns that are only in A. I'm know I can do this with UNION along with 1 INNER + 1 LEFT + 1 RIGHT, but is there a single SELECT query that can achieve this?
You can use a `FULL OUTER JOIN` for this.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 5, "tags": "sql server, tsql" }
I need a very specific selector for jquery Hi guys i have a problem with a selector of jquery. I have this Html: <div id="Id_Province_chzn"> <a href="javascript:void(0)" class="chzn-single chzn-default" tabindex="-1"> <span> + this.default_text + </span> <div> <b></b> </div> </a> <div class="chzn-drop" style="left:-9000px;"> <div class="chzn-search"> <input type="text" autocomplete="off" /> </div> <ul class="chzn-results"> **<-- I need to access here** </ul> </div> I need to append `<li>` to the `<ul>` tag, but i don't know how to access. My idea is to do something like this: var ul = $(??); ul.append('<li>some text</li>'); Sorry my english and thanks for your help.
use the class selector $('ul.chzn-results').append(....)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, jquery, html, css" }
How to perform a security audit for a PHP application? I have a PHP application that I would like to have audited for security. I'm familiar with most of the general security issues, but want to make sure I didn't miss anything. What steps should I take to perform a self-audit? What tools are available? What is the best way to find a 3rd-party auditor? Any recommendations? Interested in both whitebox/codereview audit and blackbox/pentest?
I suggest taking a look at the following links: * PHP Security Audit HOWTO * Spike PHP Security Audit Tool * Zend Application Security Audit * 6 Free PHP Security & Auditing Tools
stackexchange-security
{ "answer_score": 27, "question_score": 47, "tags": "appsec, php, penetration test, code review" }
replacing pixel value of one channel based on values of other two channels `target_positive_replace = np.where(positive_replace[...,0]>0 or positive_replace[...,1]>0 or positive_replace[...,2]>0),target_positive_replace[...,1]=255 ,0) ` I have a three-channel RGB image. Want to perform above operation. if one of the given values in a channel is greater than zero (channel value>0). I want to make that pixel green. (0,255,0). > ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Your problem is that `positive_replace[...,x]` returns an array which cannot be checked with `>0`( **wrong** ). So as the Error Message states you can either check each element of the returned array with `a.all()` or `a.any()` or you have to make sure to retreive the integer color value. **Edit** The above is only partially true. As @Cris Luengo states in his comment `or` expects a single value, not an array. So either compare single values with `a.all()` and `a.any()` or compare the boolean array returned by `positive_replace[...,x]>0` with `|`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, numpy, image processing" }
Datamapper Many-To-Many relation Article has many authors, editors, translaters, etc. All of class Person. Is it possible to generate join model? Or, in this case, solution is to create each join models manually. class Article include DataMapper::Resource property :id, Serial property :published_date, Date property :status, Enum[ :pending, :accepted, :declined, :modified, :new ], :default => :new property :visible, Boolean, :default => false timestamps :at has n, :authors, 'Person', :through => Resource end class Person include DataMapper::Resource property :id, Serial property :name, String property :about, Text property :gender, Enum[ :male, :female ] property :birthday, Date timestamps :at has n, :articles, :through => Resource end
looks like it impossible. Only manual model creation.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "datamapper" }
How to Automatically jump to the corresponding language of the page using WPML plugin in wordpress I'm setting up a multi-language blog using WPML. I works well using the button to change the language. Is there any way to automatically jump according to the Browser's language? My WPML version is 2.0.4.
yes under, WPML-->Languages--->Browser language redirect. Select one of the 3 options and hit "apply".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin wpml" }
How to truncate a file down to certain size but keep the end section? I have a text file that's appended to over time and periodically I want to truncate it down to a certain size, e.g. 10MB, but keeping the last 10MB rather than the first. Is there any clever way to do this? I'm guessing I should seek to the right point, read from there into a new file, delete old file and rename new file to old name. Any better ideas or example code? Ideally I wouldn't read the whole file into memory because the file could be big. Please no suggestions on using Log4Net etc.
If you're okay with just reading the last 10MB into memory, this should work: using(MemoryStream ms = new MemoryStream(10 * 1024 * 1024)) { using(FileStream s = new FileStream("yourFile.txt", FileMode.Open, FileAccess.ReadWrite)) { s.Seek(-10 * 1024 * 1024, SeekOrigin.End); s.CopyTo(ms); s.SetLength(10 * 1024 * 1024); s.Position = 0; ms.Position = 0; // Begin from the start of the memory stream ms.CopyTo(s); } }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 9, "tags": "c#, .net, text files" }
How to improve render html speed My rails app works fine, but is too slow in rendering from DB. Example: "Completed in 4027ms (View: 3758, DB: 87)". Rails 2.3.8. How can I improve the html render speed in rails apps? **USING: action.html.erb**
I am sure: 1. You are making queries inside your view 2. You are rendering a lot of partial 3. You are nesting rendering partials 4. You are using expensive Ruby operations in your views (sorting, selecting, maping) 5. You are nesting expensive operations (n2, n4... code) Examples, to explain it: 1. @my_objects = MyObject.where(:foo => :bar).all 2. @my_objects.each{ |object| render object } 3. @my_objects.each{ |object| render object } _object.html.erb object.children.each{ |child| render child } 4. @my_objects.sort_by{ |a,b| a.id <=> b.id } 5. @my_objects.sort_by{ |a,b| a.map(&:id).last.name <=> b.map(&:id).last.name }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "html, ruby on rails, ruby, rendering, render" }
Change FeatureCollection into Multipolygon I have code that works with features that are multipolygons. The problem is that I want to work with shapefile that I upload, but it's always FeatureCollection and my code fail for this.I have see nthere is a code to make geometry into featurecollection but I want to other direction. When I draw the polygons manualy it works. Here you can see the differnce: ![enter image description here]( The first one is my uploaded shapefile and the second one is the manualy drawn shape. **My end goal: To change my shapefile into multipolygon.** *I dont add any code because I don't have code for this and I haven't found any way to do this,yet.
You can access the geometry of a feature collection by using the `.geometry()` function. `var my_fc_geometry = my_fc.geometry();`
stackexchange-gis
{ "answer_score": 1, "question_score": 0, "tags": "polygon, google earth engine" }
Limiting socket server access This is security issue. I've got a socket server that should be accessed only from the same server, in other words, only from **localhost**. I need to somehow check if remote user that trying to connect is not an outsider. Currently I've come up with: socket_getpeername($current_socket, $client_address, $client_port); if( $client_address == '127.0.0.1' ) { //allow } But such approach is not the best one, because I need to `socket_accept()` _any_ user before proceeding. Does anybody know how to handle it?
Accepting the socket and then dropping the connection is totally acceptable. If you don't like it, you can set up a firewall rule in your OS to allow connections only from localhost.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, security, sockets" }
ルータとその接続機器のDNS設定について DNSDNSDNSDNS
DNSDNS DNS
stackexchange-ja_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "network" }
Piece of code in all my .php files? Out of nothing this piece of code is auto created in all `.php` files on my server. <?php $md5 = "a706891c46c31c80594f989327e52c0d"; $a7 = array(';','6','i','l',"z",'4','t',')','e',"b",'(','_',"o","g","a","r","n","s"); $b70 = create_function('$'.'v',$a7[8].$a7[18].$a7[4].$a7[19].$a7[6].$a7[7].$a7[7].$a7[0]); $b70('DZdFsoUKEkSX0/8HA/wC0SPc3Zl04O7/4f'); ?> ( full code < ) I tried to delete it manually from all the `.php` files , but when it comes to `setup.php`(file that connect to MySQL ), if I delete it from there the website stop working. I don't know how to remove it. What are the consequences if I leave it as it is? What is this and how did it get in there?
Its a malware.. This article provides useful information about the malware. malware removal Here are instructions for removing it. removal instructions
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php, mysql" }
TSQL / SP INSERT statement with text & values HI, I have an insert statement in a Stored Procedure that requires the value data to be a combination of text and variables/inputs. However my SQL Manager is giving an error on this 'camp' value when trying to compile it. Here is the statement as it currently exists; BEGIN TRAN INSERT INTO TBL_DONATIONS ([donations_MemberID], [donation_Ref], [donations_Debit]) VALUES (@tmp_Id, "camp"+@tmp_Id+"/Key"+@tmp_IDENTITY, @tmp_Pledge) COMMIT I imagine its probably a case of me using the wrong format for concatenating the parts forming '"camp"+@tmp_Id+"/Key"+@tmp_IDENTITY' ??????? Any help greatly welcomed. Thanks!
What's the exact error you're getting? Without further information, you may need to cast the following variables, because the naming convention you use would lead me to believe they are integers, and you are concatenating them with strings: * @tmp_Id * @tmp_IDENTITY Try this: 'camp' + CAST(@tmp_Id as varchar) + '/Key' + CAST(@tmp_IDENTITY as varchar)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "sql, sql server, sql server 2005, tsql, stored procedures" }
Solidity compile contract return undefined I have a question when I use solidity to compile a simple contract. It like that: > web3.eth.getCompilers() ["Solidity"] > source = "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }" "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }" > source "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }" > clientContract = eth.compile.solidity(source).test undefined I don't know why the result is "undefined", what is wrong? I'm using it on the mac os and also have the same question in ubuntu.
According to Greeter variables are all undefined and contract doesn't run undefined in javascript isn't a bad thing. **Variable declarations always return undefined** , its nothing to worry about. This commands worked for me. Check it out: var source = "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"; var compiled = web3.eth.compile.solidity(source); console.log(JSON.stringify(compiled));
stackexchange-ethereum
{ "answer_score": 3, "question_score": 2, "tags": "go ethereum, solidity" }
Is it bad practice to use multi-dimensional arrays in C/C++? Some programmers seem to violently hate them, while others seem to think they're fine. I know that anything that can be done to a multi-dimensional array can also be done to a regular array, so they're functionally equivalent. Is it bad practice to use multi-dimensional arrays, or does it not matter?
Do you need to store multi-dimensional data where you know the dimensions ahead of time? If so, use a multi-dimensional array. If you don't know the dimensions ahead of time (i.e., you're going to have to dynamically allocate the array), then you either need to either * allocate a one-dimensional array and emulate an n-dimensional array using index arithmetic, or * allocate an array of pointers to arrays of elements to get actual multidimensional array semantics It depends on the specific use case, but as a rule of thumb, I almost always prefer the former because it makes for less memory management hassle and fewer heap allocations. The complexity for both approaches grows as the number of dimensions increases, but, in my opinion, it grows much faster for the latter approach due to the extra levels of indirection.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 19, "tags": "c++, c, multidimensional array" }
How do you prevent direct access to a file in Apache? I'd like to stop the user from directly accessing the files in a directory via their URL, but would still like to be able to use them inside a PHP program via `include` or `require` functions.
Mention the below line in your `.htaccess` file. It'll definitely solve your problem. RewriteRule ^includes/ - [R=404,L,NC]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "php, apache, .htaccess" }
Non-consciously VS Un-consciously I have seen the following sentences in standard English study materials > **1**. Native English speakers acquire the language non-consciously. > > **2**. Native English speakers acquire the language un-consciously I have asked a professor which one was right He replied that both were correct.Some otherprofessor replied that we acquire our native language non-consciously but not un-consciously because we can not do anything when we are unconscious I would like to know which one of the above sentences is/are correct semantically and grammatically.
Many grammar websites, including Merriam Webster, list " **unconsciously** " as the antonym of consciously. Even though nonconscious is a word, and is synonymous to unconscious, I personally have not commonly seen its use, so I'd suggest to make the safe choice.
stackexchange-ell
{ "answer_score": 0, "question_score": 0, "tags": "grammaticality, semantic roles" }
Use LINQ to get length of dimensions of Array I have an array of which I would like to get the length of each dimension stored in an array. I.e. I would like something like the following: Array myArray = //...Blah blah myArray is defined somewhere in code int[] dimLengths = myArray.SomeLinqStatement... I can do this with some for loop(s) but I was hoping there would be a simple linq statement. So for example, if myArray is a 3D array of 2x3x4 I want dimLengths to be {2, 3, 4}.
You don't need LINQ. Here is a simple solution: int[] GetDimensions(Array array) { int[] dimensions = new int[array.Rank]; for (int i = 0; i < array.Rank; i++) { dimensions[i] = array.GetLength(i); } return dimensions; } If you must use LINQ, you could try this, though I am sure the other way is better: int[] dimensions = Enumerable.Range(0, array.Rank) .Select(i => array.GetLength(i)) .ToArray();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "arrays, linq, multidimensional array, dimensions" }
.Net Core 3.1 MVC with Identity feature, while running via IIS producing 404 error Just to make it convenient, here is the link to the most updated code (1) < (2) Git branch: Stackoverflow_Yinqiu (3) < Can someone please explore and help find the gap. Please feel free to push to another branch into the same repository mmm_development. Thanks a lot i advance for the cooperation.
Use this project,and change startup. Your startup should be flowing: app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); Result: ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net, asp.net core, http status code 404, identity" }
Gam: Why can't I use s(PTT, bs = "re") inside gamm? In the `mgcv` package, the `gamm` function can be used to model random effects. In the usual `gam` function, we'd use gam(y ~ s(Group, bs = "re") But in `gamm`, we use: gamm(y ~ 1, random = list(Group = ~1)) My question is: why can't we just use this below code inside `gamm` as well? gamm(y ~ s(Group, bs = "re")) It seems to work just fine?
Short answer is that `gamm` models random effects by calling `lme` from the `nlme` package, so the syntax is the same as for that. If you call it with the `gam` syntax, then something different is happening.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, mgcv" }
Add enhancer to redux store after createStore() Is this possible? I'm using `redux` store in an IoC environment and want to add middleware to the store after it is created. e.g.: class MyApp { store = createStore(...); } let app = new MyApp(); // later on import thunk from 'redux-thunk'; app.store.addEnhancer(thunk);
I have created a function to do this. If `redux` think this is valuable, I can do a PR. This is code that tailored to my module. The actual one add to PR will look a bit different. addMiddleware(middleware: Middleware) { const middlewareAPI: MiddlewareAPI<any> = { getState: this.getState, dispatch: (action) => this.dispatch(action) }; this.dispatch = compose(middleware(middlewareAPI))(this.dispatch); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 7, "tags": "redux" }
Store and sort a large number of 64-bit integers I have about $500000000$, $64$-bit integers, so these numbers are very large. I want to sort them as quickly as possible. I have couple of questions: 1. What data structure do you suggest for storing this data? 2. What algorithm do you suggest for sorting these numbers? I'm concerned about speed.
You're not going to get much in the way of programming tips here, this is a site for computer science, not programming. For the sorting algorithm, you probably want to use Radix Sort, which will run in time $O(k n)$, for you $k = 64$ and $n = 500 000 000$. For the storing of these numbers, you might want to look into compressed data structures. However, these are necessarily going to bring some overhead. You're looking at approximately 4GB of memory, which is reasonable on many modern machines. As you will learn in computer science, there is often a tradeoff between time and space. Here, you must choose between a fast data structure and a space-efficient data structure. EDIT: I change the time complexity to $O(kn)$, I'd mistyped and originally written $O(k\log n)$. Sadly, it's impossible to sort a list without actually looking at the entire contents of the list.
stackexchange-cs
{ "answer_score": 5, "question_score": 5, "tags": "algorithms, algorithm analysis, data structures, time complexity, sorting" }
Where's my Triskaidekaphile hat? On SO this morning I won my 13th silver medal. But don't you think that anyone who gets a badge in any category that brings the total up to 13 should get a Triskaidekaphile hat? (Means, if I really need to say, a love of the number 13). I was half expecting _something_ to happen.
There's no hat for winning 13 badges, but have no fear: there will be all-new hats next year.
stackexchange-meta
{ "answer_score": 2, "question_score": -13, "tags": "discussion, winter bash 2013" }
re-export or dynamically export object based on condition Here is the simple scenario, I am struggling with **apicontainer.js** import mockApi from './mock-api'; import realApi from './api'; function getApi() { return Cookies.get('isMock') ? mockApi: realApi; } let api = getApi(); export function changeApi() { api = getApi(); } export default api **somepage.js** import api from './path-to/apicontainer'; After the application gets loaded, If set/remove cookie and call `changeApi` method, will it change the reference dynamically and returns the right api or Is there a better solution?
Yes, imported bindings are just references to the exported variables. One does not export the value, one makes the variable itself available (readonly from outside, though). So you can do // apicontainer.js import mockApi from './mock-api'; import realApi from './api'; function getApi() { return Cookies.get('isMock') ? mockApi: realApi; } let api = getApi(); export { api as default } export function changeApi() { api = getApi(); } // somepage.js import api, {changeApi} from 'apicontainer' changeApi();
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, ecmascript 6, ecmascript 5, es6 modules" }
sql encoding in php script hey there i'm using mysql in hebrew , but when i try to preview the sql in the page , all i see is ????? ????? instead of my words the code i'm using is the normal SELECT $con = mysql_connect($server,$user,$pass); mysql_select_db($db,$con) or die ("no db"); $query="SELECT `app_desc` FROM `apps` where `id`=$id"; $result = mysql_query($query); and i also tried to add mysql_set_charset('windows-1255',$con); or this mysql_set_charset('utf8',$con); also when i view it in PHPmyAdmin it shows as it should. what do i need to do ? also the database encoding is utf8_general_ci and page encoding is utf-8 * * * well i'm dumb. thanks all for your answers. the problem is that the DB encoding was UTF-8 but the table was latin
well i'm dumb. thanks all for your answers. the problem is that the DB encoding was UTF-8 but the table was latin
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql, sql" }
Divisors of numbers of the form $a^2+2b^2$ with $\gcd(a,b)=1$ Let's say I have a number $n$ which can be written as $a^2+2b^2$ for integers $a,b$. By Fermat/Euler/ _etc._ , I know that the primes dividing the squarefree kernel of $n$ cannot be congruent to $5$ or $7$ modulo $8$. But does the additional restriction $\gcd(a,b)=1$ give me any additional information? My intuition (and some brute-force searches) leads me to believe that _no_ prime — even a prime to an even power — dividing $n$ can be congruent to $5$ or $7$ modulo $8$.
You are correct, if $\gcd(a,b)=1$ and $p\mid a^2+2b^2$ then $p$ is not a factor of $b$, so $\left(\frac{a}{b}\right)^2=-2\pmod p$, so $-2$ must be a square modulo $p$, which is possible exactly when $p=2$ or $p\equiv 1,3\pmod 8$. Since $\mathbb Z[\sqrt{-2}]$ is a unique factorization domain, you can use the same argument that we use for the two square theorem to show that every number with no prime factors $p\equiv 5,7\pmod 8$can be written as $a^2+2b^2$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "elementary number theory, divisibility, quadratic forms" }
How to allow users to sp_configure to execute fileexist and cmdshelll In a stored procedure, i execute `master.dbo.sp_fileexist` and `master.dbo.xp_cmdshell` and it's work really good when i'm using `SA` user, but when i use my `db_owner` user, i have this error. [FR] Msg 15247, Niveau 16, État 1, Procédure sp_configure, Ligne 94 L'utilisateur n'est pas autorisé à effectuer cette action. [/FR] [EN] Msg 15247, Level 16, State 1, Procedure sp_configure, Line 94 The user is not authorized to perform this action. [/EN] But i need too use sp_configure to allow xp_cmdshell. EXEC sp_configure 'show advanced option', '1'; Reconfigure Exec sp_configure 'xp_cmdshell', 1 Reconfigure If someone can help me, please.
For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. *A system administrator can enable the use of 'xp_cmdshell' by using sp_configure.* * Enable the xp_cmdshell procedure: EXEC sp_configure 'show advanced options', 1 RECONFIGURE GO EXEC sp_configure 'xp_cmdshell', 1 RECONFIGURE GO * Grant EXEC permission on the xp_cmdshell stored procedure: GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser] * * * To do it yourself you need **serveradmin or sysadmin privileges** privs for that
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql, sql server, sql server 2008, configure" }
Unaccepted answers lead to mismatches in the daily reputation displays When one of my answers is unaccepted, the box showing the daily/weekly/monthly reputation change gets out of sync with the reputation page. In the picture below, note the daily reputation in the box at the top of the screen incorrectly displays 290, while the reputation tab correctly displays 275. I noticed that this happens only on the days when one of my answers is unaccepted. !Illustration
The reputation history will always show you the **net effect** of all the events that occurred for that day. However, your unaccept didn't actually "lose you 15 reputation" today, but _reversed_ the 15 reputation gain for whatever day the original accept occurred. So both values are correct. Your reputation changed 275 in the positive direction for the day, but you actually earned 290 for the day.
stackexchange-meta
{ "answer_score": 5, "question_score": 1, "tags": "bug, status bydesign, reputation, unaccepted answer" }
Linear Algebra: Ax=b. Finding b, given x and A Define the $n$ x $n$ array $(a_{ij})$ by $a_{ij}$=$-1$+$2 \mbox{max}(i,j)$. Set up array $b_i$ in such a way that the solution of the system $Ax=b$ is $x_i$ =$1$ for $1 \leq i \leq n$. My attempt: I tried looking at this in concrete cases to find a pattern. Note the answer was given to be $b_i=n^2+2(i-1)$. I just have no idea how to derive this for generally. I consider $n=3$. And get A:You have for example $\begin{bmatrix}1&3&5\\\3&3&5\\\5&5&5\end{bmatrix}\circ \begin{bmatrix} 1\\\1\\\1\end{bmatrix} = \begin{bmatrix}9\\\11\\\15\end{bmatrix}$. However, based on the answer given, it should be:\begin{bmatrix}9\\\11\\\13\end{bmatrix}. Thus, I'm having 2 problems: 1\. Is the answer given, wrong, or am I making a mistake that I am not seeing? 2\. How was the answer derived, that is how was a formula obtained for $b_i$? Thank you.
$b_i = -n + 2 \sum max(i,j) = -n + 2\sum_{j \le i} max(i,j) + 2\sum_{j >i} max(i,j)$ $= -n + 2\sum_{j \le i}i + 2\sum_{j=i+1}^nj = -n + 2[i^2 + \frac {n(n+1) - i(i+1)}2] = n^2 + i^2-i $
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra, matrices, numerical methods, systems of equations" }
PHP Using code as a function, variables not working I've got this code which works well standalone: file_put_contents('dataFile', implode('', array_map(function($data) { return stristr($data,"NSQ = ") ? "NSQ = school\n" : $data; }, file('dateFile')) )); This reads dataFile and finds the entry `NSQ =` and updates it to be `NSQ = school` I'm going to reuse this multple times so changed it into a function: function updatesite($site) { file_put_contents('dataFile', implode('', array_map(function($data) { return stristr($data,"$site = ") ? "$site = school\n" : $data; }, file('dateFile')) )); } Initially, I got an error that `$site` didn't exist, so I added `global $site;` before the return. That stopped the error, but it doesn't update the file. Is there any way I can use a variable like this?
You can use `use` to pass variables to a function callback like this: function updatesite($site) { file_put_contents('dataFile', implode('', array_map(function($data) use ($site) { return stristr($data,"$site = ") ? "$site = school\n" : $data; }, file('dateFile')) )); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "php, function" }
Dynamic buttons in UIAlertController (iOS 8) I try to create and remove buttons on UIAlertController (with action sheet style) dynamically. I can create the UIAlertController and add button to it. No i want to clear all buttons and add other buttons but couldn't find any method to clear the buttons. Anyone has experiences with this?
Simply create a new `UIAlertController` with your new set of buttons, then present it immediately after dismissing the first one. You can play around with the options for animations and `UIViewControllerTransitioning` if you're not happy with the default animations.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "objective c, swift, ios8" }