INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
sql query using two tables Table one: |user_id|hotel_id| | 1 | 4 | | 1 | 5 | | 2 | 6 | | 4 | 7 | table two: |hotel_id|hotel_name|more_ifo| | 4 | bla |bla | | 5 | bla |bla | | 6 |more bla |bla | | 7 | bla |bla | I want to get all the info of the hotels that a certain user have for example user one hotels 4 and 5 .. any help? I tried using join but I guess I'm not using it correctly..?
SELECT users.*, hotels.* FROM users INNER JOIN hotels ON users.hotel_id = hotels.hotel_id Note that using `*` in a `SELECT` clause is considered bad practice; I only do it here as part of an example of using joins. If you want to search for the hotels associated with a specific user, just add a `WHERE` clause to that effect: SELECT users.*, hotels.* FROM users INNER JOIN hotels ON users.hotel_id = hotels.hotel_id WHERE users.user_id = ?
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, join" }
Как в php в функцию передать аргумент из js? Такой вопрос интересный назрел, как и можно ли вообще так сделать, чтобы передать в php функцию аргументом js переменную?... /* файл index.php */ <div id="box"></div> <?php function getNum($num){ return $num*5; } ?> <script> var a = 5; var html = <?php echo getNum(/*как сюда вставить переменную a из js?*/); ?>; $('#box').html(html); </script> Пытался в getNum просто закрыть php, вставить переменную js и вновь открыть php - но ошибку так бьет. Как правильно это сделать, и можно ли так?
**PHP** работает с сервером, а **Javascript** с клиентом, по-этому Вы не можете использовать одну и ту же переменную в скриптах этих двух языков без передачи этой переменной на сервер с клиента. Но, Вы можете указать переменную **PHP** в переменную **JS** : <script type="text/javascript"> var foo = '<?= $foo ?>'; </script> Чтобы отправить переменную **Javascript** в код **PHP** , Вам надо использовать `ajax`. Это будет выглядеть как-то так _(самый простой пример)_: var variableToSend = 'foo'; $.post('file.php', {variable: variableToSend}); На сервере Вы можете получить переменную в массиве `$_POST`: $variable = $_POST['variable'];
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "php, javascript" }
facebox white gap I want to load facebox programatically, and it should display the contents of a div as below: $.facebox({ div: '#inline_demo' }); the problem is that the div which is hidden, has a 600x600 image in it that will be displayed on the facebox. So the browser shows a big gap, and the scrollers move up as if there was content there. Overflow is set to hidden for that div, but still. Can anybody help? Thanks a lot
How about using `display:none`? Then change it to `display:block` upon activation...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, facebox" }
Storing really huge ints in MySQL Is it possible to efficiently store big ints in MySQL? Not big as in `bigint`, more like 1000th Catalan number or so, and there are at least hundreds of them. More likely, thousands. The speed of storing and loading values is a priority. The numbers are created using gmpy2, Python's GMP wrapper. So it'd be nice if the stored numbers were accessible in the same format, but if not, I can always write a converter.
I would convert the `mpz` integer to a Python string (for v2) or bytes (for v3) and save it as a BLOB entity in mysql. Here are the relevant `gmpy2` commands using Python 2. >>> import gmpy2 >>> gmpy2.mpz(1234) mpz(1234) >>> gmpy2.to_binary(mpz(1234)) '\x01\x01\xd2\x04' >>> gmpy2.from_binary('\x01\x01\xd2\x04') mpz(1234) >>> `gmpy2.to_binary` will convert an arbitrary `gmpy2` object to a binary string. `gmpy2.from_binary` will convert the binary string back to a `gmpy2` object. The object's type is encoded into the binary string so you don't need to track the object's type. Disclaimer: I maintain gmpy2.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, mysql, gmp, gmpy" }
Construct a disproving example to the statement Let $g(x,y)$ be a continuous odd function on the unit circle. We define a function on plane as a linear interpolation of $g(x,y)$ on each straight line passing through $0$: $f(x,y)=|x,y|*g(\frac{(x,y)}{|x,y|})$ if $(x,y) \ne 0$ and $f(x,y)=0$ if $(x,y) = 0$. Statement: $f$ is not differentiable at zero, except for the case $g ≡ 0$. Construct a disproving example to this statement. Give the correct wording and prove it.
Let $g(x,y) = x$, then $f(x,y) = x$. Clearly, $g$ is odd and $f$ is differentiable.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "functional analysis, analysis, multivariable calculus" }
About the rank of sets Let us work in ZFC set theory, let A and B be two sets and C be the set of functions with domain A and range B. Question: what can be said about c=rank(C), knowing a=rank(A) and b=rank(B) ? Gérard Lang
Note that every function $f$ is a subset of $A\times B$, and so the rank of $C$ is at most $\newcommand{\rank}{\operatorname{rank}}\rank(\mathcal P(A\times B))$. It is possible that $\rank(A\times B)=\rank(A)=\rank(B)$. For example in the case $A=B=\omega$. But it is possible that $\rank(A\times B)>\rank(A),\rank(B)$. For example where $A$ and $B$ are finite sets. More generally if $\max\\{\rank(A),\rank(B)\\}$ is a limit ordinal then you can show that $A\times B$ will have the same rank as that maximum, otherwise it will have a strictly larger rank. To be on the safe side, you can always show that $\rank{A^B}\geq\max\\{\rank(A),\rank(B)\\}+3$.
stackexchange-mathoverflow_net_7z
{ "answer_score": 2, "question_score": 0, "tags": "set theory" }
Regular expression to match 3 capital letters followed by a small letter followed by 3 capital letters? I need a regular expression in python which matches exactly 3 capital letters followed by a small letter followed by exactly 3 capital letters. For example, it should match ASDfGHJ and not ASDFgHJK.
r'\b[A-Z]{3}[a-z][A-Z]{3}\b' This will match what you posted if it is a complete word. r'(?<![^A-Z])[A-Z]{3}[a-z][A-Z]{3}(?![A-Z])' This will match what you posted so long as it's not preceded or followed by another capital letter.
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 6, "tags": "python, regex" }
regex filter out words wrapped in certain characters I am trying to use regex in c# to handle a scenario where I want to find all instances of a word that are not wrapped in certain characters. A quick example is below when trying to highlight the word "high" highlight [+highlight highlight+] [+highlight some more+] [+highlight+] I was trying to use negative look ahead and behind but this doesn't appear to play all that nice. Something like this (?<!\[[\+|-])\w*high\w*(?![\+|-]\]) The outcome I am after is the word "high" would be found in all but the last scenario.
Try this pattern: (?<=^|\s)(?<!\[[+|-])\w*high\w*|\w*high\w*(?![+|-]\])(?=$|\s) Regex101
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, regex" }
How can I put the link in telegram group to bot with command My goal is to make a message in telegram group and put the link to bot with command 'subscribe' How can I do it ?
If you want to open the chat with the bot with a link then you can use deeplinking. You can use this URL to redirect anyone to your bot. You can check more details here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, telegram, telegraf" }
Como faço para verificar com nodejs, se uma tabela está sem registos? Bom, pretendo fazer uma verificação a uma tabela com nodejs, para ver se a mesma está sem registos. Como posso fazer isso de forma a que não dê erro, com nodejs? Obrigado.
Verifica o `.length` do resultado: db.query('SELECT * from tabela', (err, res) => { console.log(err, res, res.length); // deve dar null, [], 0 if (res.length == 0){ console.log('A tabela está vazia!'); } });
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "node.js" }
How to calculate Current/Longest Streak of income vs Goal in Google Sheets I have a list of People, tracking the number of units sold per month. They have their goals listed in the sheet, so each month has 2 columns ("units sold" and "vs goal" which is calculated `units sold - goal`). I want to calculate the current streak, counting meeting their goal or exceeding it as a win and not meeting as a loss, and their longest win streak. Sheet included with manually entering what the values should be for current and longest streak. <
try: =ARRAYFORMULA(IF(A3:A="",,MMULT(IF((E2:Z2="sold"), IF(E3:Z>=B3:B, 1, 0), 0), SIGN(TRANSPOSE(COLUMN(E:Z)))^0))) ![0](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "if statement, google sheets, sum, google sheets formula, array formulas" }
get Firebase nodes by children If I have a database that is set up like so -users -uId0 -Name: "Bill" -uId1 -Name: "Bob" -uId2 -Name: "Dave" How do I get the uId elements if there name child starts with B. The query should return somthing like this? -uId0 -Name: "Bill" -uId1 -Name: "Bob" Thanks!!
DatabaseReference myReference = FirebaseDatabase.getInstance().getReference(); myReference.child("users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //looping all your users for (DataSnapshot messageSnapshot:dataSnapshot.getChildren()) { name = (String)messageSnapshot.child("Name").getValue(); if (name.toLowerCase().contains("b")) { //u can save your name with 'b' string here } } } @Override public void onCancelled(DatabaseError databaseError) { } });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, firebase, firebase realtime database" }
How many times divided by 2 until reach value 1 I am looking for a formula which will tell me how many times I must divide a number $(n)$ by $2$ until its value is less than or equal to $1$. For example, for $n=30$ $(30,15,7.5,3.25,1.75,0.875)$ would yield $5$ (number of times divided by $2$). How can I express this as a formula?
If you do not have the ceil function at your disposal, you can use the following formula : $$m=\begin{cases}\left\lfloor\dfrac{\ln n}{\ln2}\right\rfloor+1\quad\text{ if }\;n\;\text{ is not a power of }2\\\\\left\lfloor\dfrac{\ln n}{\ln2}\right\rfloor\qquad\;\text{ if }\;n\;\text{ is a power of }2\end{cases}$$ which does not require $\;\log_2x\;$ function but just the natural logarithm. In other words : if $\;\left\lfloor\dfrac{\ln n}{\ln 2}\right\rfloor=\dfrac{\ln n}{\ln 2}\;,\;$ then $m=\left\lfloor\dfrac{\ln n}{\ln 2}\right\rfloor\quad$ otherwise $\quad m=\left\lfloor\dfrac{\ln n}{\ln 2}\right\rfloor+1\;.$ The symbol $\lfloor x\rfloor$ is the floor function and means "the greatest integer less than or equal to $x$". Programming languages have the floor function.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "logarithms" }
Bijection on a component of a cartesian product I have been recently studying relations and mappings and I have come across the following problem. Consider two non empty finite sets $I,J$ and their cartesian product $I\times J$. Let $f\colon I\times J\to I\times J$ be some bijection. Suposse now, that $|I|=n\in\mathbb{N}$ and let $i_1,i_2,\dots,i_n$ be the elements of $I$. For each $1\leq j\leq n$ define $$ A_j=\\{a\in I; (\exists j_1,j_2\in J)\ [f((i_j,j_1))=(a,j_2)]\\} $$ My question is, does now necessarily exists a bijection $g\colon I\to I$ such that $g(i_j)\in A_j$ for every $j=1,2,\dots,n$? I would appreciate any help with this, as I am really stuck. Thanks.
For a particular j, Aj is just the projection of f(ij x J) back on I. Every element of I must appear in some Aj because f is a bijection: if ik is not in any Aj then ik x J cannot appear in the mapping by f from I x J to I x J. So you can choose (without AofC because the sets are finite) a sequence of elements from I such that each belongs to the correspondinlgy sequenced Aj. Therefore you can map the the original sequence of elements to this new sequence by a bijection (permutation) g and then have g(ij) an element of Aj (must learn how to do the mark-up sometime).
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "elementary set theory, relations" }
IPHONE: Testing for iPhone OS 2.+ and 3.+ I have an application developed for iPhone OS 3.+. This application uses in-app purchase. I would like to release a version now, that it is compatible with 2.+. Obviously I will have to use that techniques described by Apple that tests for the presence of the frameworks I am using from 3.0 and make alternative code for 2.0, without using those 3.0 frameworks. my question is: my iPhone is updated to 3.0. How do I test to see for 2.0? Do I need an iPhone that is already using 2.0 or is there anything I can do to simulate this? thanks for any answer
Yes, you'll need a 2.x device. Optionally, you can installed an older version of Xcode on Leopard, and test using the sim, but still, you should always test on a device.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "iphone, iphone sdk 3.0" }
How can I galvanically isolate 5V 1A DC power? I want a circuit to pass on ~5V DC at ~1-2A, but galvanically isolate it. Can somebody help? THX
> What kind of dc-dc converter isolates galvanically? Pretty much +90% of them. If I look in Farnell I see there are 5640 isolating types and about 400 non-isolating types: - ![enter image description here]( Common Suppliers: Traco_Power, XP Power, Murata, Artesyn, Recom, TDK_Lambda
stackexchange-electronics
{ "answer_score": 1, "question_score": 0, "tags": "power supply, power, opto isolator, isolation" }
UiTableView inside AlertView iOS 7 I wondering, how can I add uitableview in the Alert? In my app I have an uitableview and if the user press in one row is going to show a dialog with a table (the table have some action). How can I made this behavior in IOS 7? I just try this library < but I couldn't fix my issue. Regards, David
Since there is not option to this in the standard `UIAlertView` you will have to make your own class. Because the `UIAlertView` clear states: > **Subclassing Notes** > > The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modifie
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "iphone, ios, objective c, uitableview, ios7" }
Symfony Yaml component: how to always wrap string in quotes when using Yaml::dump When using the Yaml::dump function of Symfony Yaml component, the output will have some strings wrapped by single quotes and other strings not wrapped at all. I know that both wrapped and non-wrapped strings are correct in Yaml, but I was wondering if there was a way to standardize the ouput (e.g. setting strings always be wrapped by single or double quotes) in order to make it consistent.
According to the documentation, `dump` takes some flags. They are listed at the top of the documentation (without explanation): * DUMP_OBJECT * DUMP_EXCEPTION_ON_INVALID_TYPE * DUMP_OBJECT_AS_MAP * DUMP_MULTI_LINE_LITERAL_BLOCK None of these have to do with quotation, so the answer is: No, it's not possible. Quotation is decided by the Escaper, which does not have any customization options.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "php, symfony, yaml" }
IOS 9.2: My "General> Profiles and Device management" is gone? I have looked and looked and I can't find a solution. I need to get to the profiles and device management section on my ipad 3 but it is not under general. I tried searching for it in settings and it shows up as an option. I tap on it and it just opens General, where there is no option for profiles and device management. Please help, I already tried restarting the device. How can I find it?
This option will not be displayed if you do not have an installed profile. You don't actually install profiles from the settings. Profiles can be installed through different channels, whether it be an email invitation or a website. The only reason profiles show up in settings is so you can manage/delete them easily. Before I had profiles, I didn't have the settings option to manage them.
stackexchange-apple
{ "answer_score": 14, "question_score": 20, "tags": "ios, settings" }
topology: is $(1/2,1]$ open in $[-1,1]$? If $Y = [-1,1]$ is subspace of $\Bbb R$, is $(1/2,1]$ open in $Y$? And what about in $\Bbb R$? I know $(1/2,1)$ is open in both $Y$ and $\Bbb R$ but I am confused when it is half closed and half open.
The subspace topology on $Y\subseteq X$ is defined by: $\tau_Y:=\\{U\cap Y| U\,\,\text{open in}\,\,X\\}$ To decide if $(\tfrac12, 1]$ is open in $Y$ (with regards to $\tau_Y$), we have to give an open set U in $\mathbb{R}$, with $U\cap [-1,1]=(\tfrac12, 1]$. And indeed we can give this easily: Because $(\tfrac12, 2)$ is open in $\mathbb{R}$ and $(\tfrac12, 2)\cap [-1,1]=(\tfrac12, 1]$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "general topology" }
How to check the VPN setting created by an app on an iOS device? Many VPN apps would create VPN profiles on the iOS device. Unlike VPN profiles create by the user, they cannot be edited, and therefore the user cannot see the setting of said profile. With a jailbroken device, is there a way to hunt down such profile and read the setting in file?
You won't need to use OpenSSH at all whatsoever. The VPN settings are saved in /var/preferneces/com.apple.networkextension.plist file. Open it with a text editor. It's not encrypted. The passwords are saved in the keychain instead of inside this file. You cannot access the keychain on an iOS device and decrypt it easily but you can do it over a macbook that shares the keychain with your iOS device (if you enabled it). Type in your master password to view the saved passwords.
stackexchange-apple
{ "answer_score": 3, "question_score": 6, "tags": "ios, network, jailbreak, vpn" }
Set values for all records in a Kdb table based on values of other columns I need to perform a global update on a KDB table to update two columns. For the FirstName column, I want to remove it's value for records which have empty string in the SecondName column, and for the FullName column I want to replace an encoded delimiter with a space for all rows in the table. These need not be done in a single update statement if that helps. update FirstName:$[SecondName like ""; FirstName; ""], FullName[FullName; "&nbsp;"; " "] from table } I'm struggling with the syntax - the above is my best attempt but it doesn't work.
One way to achieve that in a sinlge update statement: q) update FirstName:?[SecondName like ""; SecondName;FirstName], FullName:ssr[;"&nbsp;"; " "]@'FullName from table
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "kdb" }
Find parametric equation of path of particle if acted on by force $\mu y^{-2}$ parallel to $y$-axis A particle is acted on by a force parallel to $y$-axis whose acceleration (always towards the $x$-axis) is $\mu y^{-2}$ and whenn $y=a$, it is projected parallel to the $x$-axis with velocity $\sqrt\frac{2\mu}{a}$. Find the parametric equation of the path of the particle. Here $\mu$ is a constant. Since there is no acceleration along $x$-axis; $x=\sqrt\frac{2\mu}{a}t$ Now for $y$; I proceeded with $v\frac{dv}{dy}=\frac{-\mu}{y^2}$ I got $\frac{dy}{\sqrt{\frac{1}{y}-\frac{1}{a}}}=\sqrt{2\mu}t$ I am having trouble integrating this. I am unable to obtain $y$ in terms of $t$.
$$\sqrt{2\mu}\:t=\int\frac{dy}{\sqrt{\frac{1}{y}-\frac{1}{a}}}=\int\sqrt{\frac{ay}{a-y}}dy$$ Change of variable :$\quad y=a \sin^2(Y)\quad$ leading to : $$\sqrt{2\mu}\:t=2a^{3/2}\int \sin^2(Y)dY = a^{3/2}\left(Y-\frac{1}{2}\sin(2Y )\right)+\text{constant}$$ $Y=\sin^{-1}(\sqrt{\frac{y}{a}})\quad$ After simplification : $$t(y)=\frac{1}{\sqrt{2\mu}}\left( a^{3/2}\sin^{-1}\left(\sqrt{\frac{y}{a}}\right)-\sqrt{ay(a-y)} \right)+C$$ Do not try to express the inverse function $y(t)$ as a combination of a finite number of standard functions. There is no convenient special function available for a closed form. Use numerical calculus to compute or draw $y(t)$ . A parametric form: $$\begin{cases} t = \frac{a^{3/2}}{\sqrt{2\mu}}\left(Y-\frac{1}{2}\sin(2Y )\right)+c \\\ y=a\sin^2(Y) \end{cases}$$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "integration" }
Meteor Collections using find selector to discriminate against certain variable I understand we can use find with the selector to get specific elements in a collection like so: usernames.find(selector) To specify finding all usernames with a specific property like "Bob" as the name I would do: usernames.find({name: "Bob"}) Which would only show me documents that have the name Bob. But let's say there are other people in my collection like Alice and Kat and I want to find everyone in the collection whose name is not Bob. **How would I specify a selector to find everything in the usernames collection whose name is not Bob?** I've tried: usernames.find({name: !"Bob"}) I'm stuck on the syntax. Thank you!
Use $ne operator `usernames.find( { name: { $ne: "Bob" } })` $ne selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mongodb, meteor" }
jquery remove then append and do something onclick On document ready, I have an onclick function that changes css of some elements with a class=project. If I remove those elements with class=project because of another event using .remove() then append new elements using .append() with class=project because of a different event, shouldn't my onclick event which changes the css still work because the new elements have class=project? It doesn't look like it is but is there a way around that?
I learned about jQuery's .delegate and it does exactly want I want. I can remove and append all I want. I hope this helps someone else out.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, onclick, append" }
Can bowler bowl with two hands (left & right) in international cricket Recently I've seen in domestic match there was one bowler (spinner) who used his both hands while delivering the ball? I've doubt can it be possible in International Cricket. Does ICC has any rule about this?
This is perfectly legal, so long as the bowler informs the umpire before changing from bowling left-handed to right-handed or vice versa. Quoting Law 21.1.1, Mode of delivery: > The umpire shall ascertain whether the bowler intends to bowl right handed or left handed, over or round the wicket, and shall so inform the striker. > > It is unfair if the bowler fails to notify the umpire of a change in his/her mode of delivery. In this case the umpire shall call and signal No ball. There is nothing in any of the ICC Playing Conditions for Test Matches, One Day Internationals or T20 Internationals which overrides this.
stackexchange-sports
{ "answer_score": 1, "question_score": 0, "tags": "rules, cricket, icc" }
Having NA level for missing values with cut function from R The cut function in R omits NA. But I want to have a level for missing values. Here is my MWE. set.seed(12345) Y <- c(rnorm(n = 50, mean = 500, sd = 1), NA) Y1 <- cut(log(Y), 5) Labs <- levels(Y1) Labs [1] "(6.21,6.212]" "(6.212,6.213]" "(6.213,6.215]" "(6.215,6.217]" "(6.217,6.219]" **Desired Output** [1] "(6.21,6.212]" "(6.212,6.213]" "(6.213,6.215]" "(6.215,6.217]" "(6.217,6.219]" "NA"
You could use `addNA` Labs <- levels(addNA(Y1)) Labs #[1] "(6.21,6.212]" "(6.212,6.213]" "(6.213,6.215]" "(6.215,6.217]" #[5] "(6.217,6.219]" NA In the expected output, you had character "NA". But, I think it is better to have real NA as it can be removed/replaced with `is.na` is.na(Labs) #[1] FALSE FALSE FALSE FALSE FALSE TRUE
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "r, cut" }
Beamer vs. Minted: overlays How to use beamer overlay inside minted code? The obvious solution does not work: \documentclass{beamer} \usepackage{minted} \begin{document} \begin{frame}[fragile] \frametitle{Foo} \begin{minted}{lua} \uncover<1>{print("foo")} \uncover<2>{print("bar")} \uncover<3>{print("baz")} \end{minted} \end{frame} \end{document}
Unfortunately, there is no obvious way to make this work due to the way minted works internally. In fact, it is vital that the code is _not_ parsed by TeX in the usual way. There might be some trickery possible to circumvent this but for now I suggest that the easiest way to approximate the desired behaviour is to use multiple sequential `minted` environments: \uncover<1>{\begin{minted}{lua} print("foo") \end{minted}} \uncover<2>{\begin{minted}{lua} print("bar") \end{minted}} \uncover<3>{\begin{minted}{lua} print("baz") \end{minted}} Though to be honest I’m not certain if this even works.
stackexchange-tex
{ "answer_score": 7, "question_score": 13, "tags": "beamer, overlays, minted" }
Registering with Google Schemas: What is the process when sending from multiple email addresses? I work for a direct marketing company that sends many emails on behalf of many clients, and we wish to start using Actions in Gmail. I am in charge of heading up the testing of this. I am concerned about this step in the registration process: > Send a real-life email coming from your production servers (or a server with similar DKIM/SPF/From:/Return-Path: headers) including the markup / schema to schema.whitelisting+sample@gmail.com. Since we will be sending email on behalf of many clients, we will need to send from a multitude of sender addresses. Is it possible to whitelist our company as a whole or will we need to whitelist each email that we wish to send?
For this you have to list all the email id's to be whitelisted or create a common domain and then you can request for whitelisting. However, in order to whitelist these emails id's the emails you are requesting should be transactional not promotional emails. Like the email notifications that user has been subscribed for or emails related to order processing etc. You can refer to Actions / Schema Guidelines in this page for more details. Hope that helps!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google schemas" }
current date as argument in a task scheduled with celerybeatC I'm trying to setup a crontab task passing the date at runtime, like this: beat_schedule = { 'mytask': { 'task': 'mytask', 'schedule': crontab(day_of_week='mon,tue,wed,thu,fri,sat', hour=3, minute=0), 'args': (date.today().strftime('%Y%m%d')), }, } How can I accomplish this? Thanks
I do not think Celery beat can do that. Workaround that comes first to mind is to write a tiny Celery task that passes `date.today().strftime('%Y%m%d')` to the `mytask`. Then you add that task to the Celery beat config instead of the `mytask`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, celery, celerybeat" }
python re.sub() function adding additional character - e - garbage characters I am using the `re` package in pandas 3 and trying to `re.sub()` a pattern. My code is below import re test = "xyz/b2117fe1e" obfuscate_pattern = r'/[^g-z]+[0-9]' val1 = re.sub(obfuscate_pattern,'',test) print(test) print(val1) The issue I have is that when I run the code I have an additional letter that appears after `xyx`. The result should be `xyz` for the input `xyz/b2117fe1e`. But, what I am getting is `xyze` (the last `e` is additional) for the same input `xyz/b2117fe1e`. I am not able to diagnose the issue, what are your suggestions?
`/[^g-z]+[0-9]` is going to match anything (that isn't between `g` and `z`) starting after the `/` and including the _last digit_. In your test case you have a letter _following_ that last digit so it remains after you perform your substitution. If you remove the `[0-9]`, your pattern will remove anything that isn't between a `g` and `z` after the `/`, including any digits (since they aren't `g-z`)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }
Expected value of e^-2x I have the following problem: > The expectation of an exponentially distributed random variable $X$ is equals to $1/2$. Compute $\mathbb{E}[e^{-2x}]$. The final answer is: $1/2$ I already know that $\mathbb{E}[x]$ of an exponential distribution equals $1/λ$. So $λ=2$. That makes the probability density function: $f(x) = 2e^{-2x}$ I also know that $\mathbb{E}[e^{-2x}]$ equals the integral of $e^{2x} \cdot f(x)$. But when I solve this equation I get $(-1/2)\cdot e^{-4x}$. Can I get feedback to get the final solution? Ter
We are told $$X \sim \text{Exp}(\lambda)$$ Therefore, $$\mathrm{E}[X]=\frac{1}{\lambda}$$ For justification on this, see [here].(< Then, since we are told that $\mathrm{E}[X]=\frac{1}{2}$, we conclude $\lambda=2$. So $$f_X(x)=2e^{-2x}.$$ Then, using LOTUS, $$\mathrm{E}[e^{-2X}]=\int_{0}^{\infty}{2e^{-2x}\cdot 2e^{-2x}\mathrm{d}x}=1.$$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "probability, probability distributions, expected value" }
Pygame quitting to gameOver screen New to python, making a snake game but Pygame keeps quitting to the screen but i basically want to be able to quit the game with the X(window's x)button anytime i want to. I've tried debugging this but for some reason i always get not responding when debugging it in PyCharm the gameOver screen is only suppose to run when the bool is set to true but it is somehow clashing with my game pause code. Would really appreciate some help! This is the code: <
In gameOver screen you run second `gameloop()` so when you quit you return from second `gameloop()` to first `gameloop()` (or from third to second, etc).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, python 2.7, pygame" }
It is possible to create a click button in VBA Excel that opens the VBA editor? I was just wondering: It is possible to create a click button in VBA Excel that opens the VBA editor when the button is clicked? **UPDATE:** The point that I was looking for was achieved by @pgSystemTester. In this, I don't have to disable the trust settings, as suggested by another answers pasted here below. Very better way.
In response to the comments, it seems hard to envision a situation where it's a good idea to be directing "inexperienced users" to the visual basic editor. Similarly, lowering these same users' systems' defenses against malicious code seems unwise. With that said, you could just try to teach your users to type: `alt L V` I don't like keystroke macros, but this actually seems to work for me: Sub OpenVBE() Application.SendKeys ("%lv") End Sub This appears to work without lowering the users' trust settings also.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -3, "tags": "excel, vba" }
"the" with knowledge Can I use article “the” with the word “knowledge” as shown in following 2 cases: 1. XX, (20005) use **the knowledge** about the human body **for the segmenting** of anatomical structures from medical image. 2. The aim is to solve these tasks by using **the knowledge** about the information of anatomical structures into the segmentation process.
Since you are talking of a specific knowledge, the article is correct. If you were talking of knowledge in abstract, then you would not use the article, as in "a thirst for knowledge" or "the transmission of knowledge."
stackexchange-ell
{ "answer_score": 2, "question_score": 4, "tags": "definite article" }
Multiple types of build for different build triggers I have a setup where our code builds to dev every 5 hours on a schedule trigger. This works great, but the downside that the code could sit in teamcity for hours before it triggers and alerts us to a build error. Is there a way to have a VCS trigger also run the build as soon as its checked in, but passing something to our NANT script to say "just build, don't deploy"? I know I must be missing something.. is there any way to achieve this? The only way I could think of was to have an entirely separate build configuration, but that seemed rather wasteful
You can setup a new build with a VCS trigger and then have that build have a env/system variable set that your build script can read to determine whether or not to deploy to dev. See TeamCity Docs for information around this. I've used something like this in setting up builds before and it works well.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "teamcity" }
Property [bId] does not exist on this collection instance I have a pages controller.I wanna get some information stored in my db when /myshopping requested. This is my controller code : public function myshopping() { $Buylist=DB::table('orders')->where('id','=',Auth::user()->id)->orderBy('oId','desc')->get(); $Bookinfo=DB::table('books')->where('bId','=',$Buylist->bId)->first(); return view('shop.myshopping',compact('Buylist','Bookinfo')); } Thank you very much.
Using`->get()` on a `QueryBuilder` returns a `Collection` (fancy wrapper for PHP arrays), so `$Buylist` is a group of records from your `orders` table, as opposed to a single record. If you change your logic to use `->first()`: $Buylist=DB::table('orders')->where('id','=',Auth::user()->id)->orderBy('oId','desc')->first(); Then you can access `$BuyList->bId` without issue (unless `$BuyList` returns `null`, but that's a different issue).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, laravel" }
Too many method within method? In my `Main()` I call `MethodA()` from `ClassA`, which will then call `MethodB()` from `ClassB`, and so on and so forth. This goes for about 5 layers before it finally returns the value I want back to `Main()`. There is an object that is being passed round and processed in each methods. Is this a good practice? Is there another approach for this situation?
Yes, it is a good practice. And 5 levels is still very close to nothing. At 500 you might pause to think about it, at 5000 it gets worrisome. > There is an object that is being passed round and processed in each methods. It will be passed by reference, so no overhead there.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, function, methods" }
How to Open File at Windows startup (when I turn on laptop) when i turn on my laptop a dialog box opens ![enter image description here]( asking me to how to open the file. It comes after logging into my wn10 user account. It comes before i start any programs. At first i was ignoring this but wen i select notepad from the list and viewed it this was shown. ![enter image description here]( I dont know what it is or y it is happenining, i have done nothing related to this. how to stop this?
Normally is when a file named with your username is created. You need just to delete it and it'll be ok. It is located in your Users folder. Follow one of these links if you don't find its location: first link and second link.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "windows, startup, setx" }
Oraciones causales y el modo subjuntivo > (1) _Y como yo **permaneciera** en silencio_, él también continuó mudo y inmóvil. > > (2) _Como no **volviese** para alimentar a su hijo_, su marido fue a buscarla. ¿Me podríais por favor explicar por qué se usa el subjuntivo en estas dos oraciones causales? En ambas oraciones se refiere a algo que ya ha ocurrido y entonces se considera como algo ya conocido. Además la oración principal no es en forma negativa. Pues ¿por qué van con el subjuntivo? Muchas gracias
Me parece bastante que el uso del subjuntivo en este caso se debe a la sustitución con el _pretérito pluscuamperfecto_ , que se usaba antiguamente. Reemplazando quedaría: > 1. _Y como yo **había permanecido** en silencio..._ > 2. _Como no **había vuelto** para..._ >
stackexchange-spanish
{ "answer_score": 2, "question_score": 3, "tags": "subjuntivo" }
Selenium chromedriver doesn't open an existing profile even when told to Recently I've been trying to get selenium webdriver to connect to an already existing profile. I've got the code below. from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("user-data-dir=C:\\Users\\me\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 19") driver = webdriver.Chrome(executable_path=r'path\to\chromedriver.exe', options = options) Now what this is supposed to do is launch an existing chrome user, which in my case I created just for this. But instead, it only launches a guest user. I've already tried it with the \Default user in which case it connects just fine, but instead it cannot navigate to any website. I'm appreciative of any help <3
According to Load Chrome Profile using Selenium WebDriver using java your profile should be put in another option: options.add_argument("user-data-dir=C:\\Users\\me\\AppData\\Local\\Google\\Chrome\\User Data") options.add_argument("profile-directory=Profile 19")
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, selenium, selenium webdriver" }
Ignore directory in SVN without affecting svn:ignore on server? I know about the svn:ignore property, but that doesn't solve my problem. I have a source directory. I want to create a directory inside it, called "build" that I will build inside. I don't want to put "build" in svn:ignore because other people using the same repository don't need it ignored, and I may want to have different names for this. The general problem is this: Given a working copy of a subversion directory, I want to make a subdirectory that will be ignored by svn without modifying anything on the server. If I could make a directory and stick an empty ".svn_ignore_this_directory" file inside it or something, that would be awesome. I think in git it would be something like making a .gitignore file with just "." in it, but maybe that's not right. Can svn do this?
You have a `.subversion` file that defines the configuration of your local machine (the location of this file will depend on your OS). Inside that file, use the `global-ignores` option to configure files or folders that you want your local Subversion to ignore. Changes made to this file will only affect your machine.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "svn, svnignore" }
Sharing variables in modules node.js I understand how exports works, but how can I create a variable in my main file, and then use that variable in my module? I tried passing my "global" variable to a function in my module, but it passed as a copy, not by reference and since its an array I'm passing that's no good. For example # main file var someObject = {}; var myModule = require('./whatever'); moModule.function_a(someObject); moModule.function_b(someObject); Even though someObject is an object it passes by copying, and if I change its value inside function_a or function_b, it wont change in the global scope, or in any other modules where I use it.
If you modify a passed argument, the argument will change outside the function. However, what you're probably doing that's making you think the object is being copied is you're reassigning the variable. What you should do: function foo(a) { a.bar = 42; } var o = {}; foo(o); console.log(o); // { bar: 42 } What not to do: function foo(a) { a = { bar: 42 }; } var o = {}; foo(o); console.log(o); // {}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "node.js, export" }
Changing Image on selected state of UITablView cell I have a created a custom cell and added one label and Image, I have 4 rows in my table each row has a different image and each row opens a different view controller, so, now what I need is on click of a particular row I want the image to change to do that I tried this, but its not working, so please help me out. if(indexPath.row == 0) { if(cell.selected == true) { UIImage *cellImage = [UIImage imageNamed:@"abc.png"]; cell.icon.image = cellImage; } else { UIImage *cellImage = [UIImage imageNamed:@"abc.png"]; cell.icon.image = cellImage; } } Regards Ranjit
Try to do following when creating your cell or in `tableView:willDisplayCell:forRowAtIndexPath:` method: cell.imageView.image = [UIImage imageNamed:@"abc.png"]; cell.imageView.highlightedImage = [UIImage imageNamed:@"abc.png"]; It will work for your `icon` property too if it is `UIImageView`
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "ios, ios5" }
Is there a program that automatically styles C files? I think the title is self-explanatory. Would be handy for large files with lots of style violations. Thanks guys :)
Indent is the standard.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c, coding style, indentation, pretty print" }
Ввести словарь через input() Пожалуйста помогите разбираться. Я не понимаю как работать с dict(input()). У меня появляется такая ошибка dict1 = dict(input()) print(dict1) Traceback (most recent call last): File "D:\Python\Dictionary.py", line 2, in <module> dict1 = dict(input()) ValueError: dictionary update sequence element #0 has length 1; 2 is required
Не совсем то, что я хотела, но тоже хорошо dict1 = {} key = int(input()) dict1[key] = input() print(dict1) 4 5 {4: '5'} Можно и так. Спасибо @andreymal. Просто так у меня и первая цифра и вторая идут как строки. А так как я написала, можно легко изменить. dict1 = dict([input().split()]) print(dict1)
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x" }
Simply text-box value emailed to me (JQuery & HTML) Im trying to find an ultra simple example that takes a single text box value, and emails it to an address that I specify when the user hits "submit" The form would be something like this: <form> <input type="text" name="emailAddy" value="Enter Your Email Address" size="25" /> <input type="submit" value="Get Notified" /> </form> On click, it should email the emalAddy field value to me... Any thoughts?
AFAIK, You can't use plain jQuery and HTML to send emails. You need some sort of server side code to mail. What you can do instead is, submit the form, extract the details on the server side and send the email. This question and links given there might be of help.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "jquery, html, email" }
How to prevent form from being resized in Delphi? How do I prevent my form from being resized? I don't want it to be maximized (which can be toggled via the property editor), but I don't want anyone to be able to drag-resize it. Am I missing something simple, or does this require a little bit of coding? I'm using Delphi 2007.
TForm has the property you need. Set BorderStyle to bsSingle so that the form doesn't appear to be sizable, and it has the added benefit of actually **_not_** being sizable. :-)
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 3, "tags": "delphi" }
Maple: How having f(z) create f'(z), where z is complex variable? So I have `f(z)`, `z:= a + I*b` I want to create f`(z) capable of working with my z. First time I tried `fd:= diff(f(z), z)` but my code fails with Error, (in `fd`) invalid input: diff received `a+I*b`, which is not valid for its 2nd argument. So only solution I found is to create f' in 2 steps. Calculate `diff(f(z), z)` into some variable and copy output by hand into `fd:= z-> ...copied stuff...` So what would be correct solution for such problem - how to get rid of manual copying?
I'm not 100% sure I understand what you want, but here's my suggestion for what I think you want: 1. Define f(z): `f := z -> whatever f does with z;` 2. Define the derivative df(z): `df := D(f);` Now, if `f := z -> z^2`, then `df(a + b*I)` will evaluate to `2*a + 2*b*I`. I hope this helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "maple" }
Number of triangles In a triangle $\bigtriangleup ABC$ is $\widehat A=30^{\circ}$, $|AB|=10$ and $|BC|\in\\{3,5,7,9,11\\}$. How many non-congruent trangles $\bigtriangleup ABC$ exist? The possible answers are $3,4,5,6$ and $7$. Is there a quick solution that doesn't require much writing?
**Hint:** Use the Sine Law: $$\frac{\sin C}{10}=\frac{\sin A}{k},$$ where $k$ is one of our numbers $3$, $5$, $7$, $9$, $11$. Since $\sin A=1/2$, one of our $k$ is problematical. Another yields a triangle we all know and love. For the others, we are dealing with possibly the "ambiguous" case. A couple of sketches will give the answer, or knowledge about when we really are in the ambiguous case.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "geometry, trigonometry" }
inner product space and orthonormal vectors Let (S,(f,g)) be an inner product space, and let $(v_n)_{n\in{\mathbb N}}$ be an orthonormal set of vectors. Show that, though ($v_n$) is a bounded sequence in norm, there is no subsequence which converges. Do I have to go about using the idea that this type of space is not compact? any ideas would help.
Just compute that if $n\ne m$, then $$\|v_n-v_m\|=\sqrt2.$$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "real analysis, linear algebra, functional analysis, measure theory" }
How to attach a file to a dataobject in silverstripe 3 I have a simple task that I can't seem to figure out. In SS3 how can I attach a file to my data object or in other words create a file upload field, and bind that file object to the data object. See example below: class myDataObject extends DataObject{ public static $db = array( 'Title' => 'Varchar', 'Desc' => 'Text', 'Help Text' => 'HTMLText', // 'File Upload (document)' => ??? ); }//class Note: For now I'd like to do a single file only, but later, on another object I'd like to do multiple files.
File cannot be set in $db but in $has_one, as it's a relation to another DataObject. So you'd need: private static $has_one = array( 'FileUpload' => 'File' ); I don't think spaces and brackets in the $db or $has_one keys are a good idea, as they are used for database fields. If you want to set a title for the scaffolded fields please use $field_labels. private static $field_labels = array( 'Title' => 'My fancy title', 'Desc' => 'Description', 'has_one_FileUpload' => 'File upload (document)' ); If you want mutliple files you'd need to define it as $has_many insetead of $has_one. See < for more information.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "object, file upload, silverstripe" }
Relaxed approach in/at/towards solving What is the difference between the following and are they correct? 1. He took a relaxed approach in solving the problem. 2. He took a relaxed approach at solving the problem. 3. He took a relaxed approach towards solving the problem. Cheers, Chris
Number 1 is valid but uncommon, and 2 would not normally be used in British English. Number 3 is perfectly fine but wouldn't be commonly used. The most commonly-used formation would be: > He took a relaxed approach to solving the problem.
stackexchange-english
{ "answer_score": 1, "question_score": 1, "tags": "grammar, prepositions" }
Identifying the start and end of functions in a C program I am currently programming in C to find the complexity of functions in a program based on the number of lines in the functions. I will have to fopen an existing C file and proceed with the calculation. I know that there maybe some builtin tools for finding it. But still I want it to be programmed manually. Is there any specific method to find the start and end of the various functions in a C file?
1. Run this through C preprocessor. This way you strip comments, unroll macros, include #includes etc. Unless you want complexity of the user-readable code, this will produce results much more true. 2. Remove fixed strings. Anything between `""` goes, note escaped quote `\"` doesn't close the string. 3. Scan the file. First `{` increases count of functions and begins scanning the body of a function. Observe depth. `{` increases depth, `}` decreases, as depth reaches 0 another `}` is the end of the function. Next `{` will be a new function, but as you scan the outside, if before reaching next `{` or `EOF` you encounter a `;` \- cancel any data collected on the last piece. That wasn't a function, it was a struct, an union or something like that.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c" }
UTF-8 Encoding in JSP & Tomcat I am working in jsp based application running on tomcat 7.0.50 The jsp are saved in utf-8 and every jsp has <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> I configured Tomcat connectors encoding to UTF-8 <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" /> In the bin/catalina.bat, I added the param: set JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF-8 But when I try to check the passed params in the http post from the form, i found that "Français" is passed as "Français". How to resolve this and force the http post encoding to utf-8? What is wrong with the config I am making?
I found the solution for this issue, before dealing with the request paramters, just insert: request.setCharacterEncoding("UTF-8"); And every thing will be ok Link where I found the solution
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jsp, http, tomcat, encoding, utf 8" }
Xcode 4.6 IPhone/IPad Copy Field, using setText "Incompatible pointer types" I am trying making a simple iphone app that copies text from one field to another when you press a button (text1 values into text2), but I am getting my some warnings "Attributes on method implementation and its declaration must match" and "Incompatible pointer types sending 'UITextField *' to parameter of type 'NSString *". Both text1 and 2 and declared as UITextField. The warnings are in the setText line. #import "APPViewController.h" @interface APPViewController () @end @implementation APPViewController -(IBAction)copy:(id)sender { [text2 setText:text1]; } @end
`text1` is a `UITextField *`, not an `NSString *`. You need to ask `text1` for its contents by sending it the `text` message. [text2 setText:[text1 text]]; You can also use “dot notation”, like this: text2.text = text1.text; The second form compiles into exactly the same executable code as the first form.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "iphone, ipad, pointers, xcode4.6" }
Flot bar chart highlight color per series I have a bar chart with a few series. How can I control what color the highlight color will be on a per series basis? (each of my series is a different colour so I need to highlight them each differently). I've seen how to do this for a single color throughout the entire chart but I'm needing it specific for each series.
You need to set the `highlightColor` option for each series in your data array: var data = [{ data: [ [1, 5], [2, 3] ], highlightColor: "#00FF00" }, { data: [ [1, 2], [2, 8] ], highlightColor: "#FF0000", }]; JSFiddle Example
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "flot" }
What did Aragorn plan to do after reaching Gondor? This question is based on _The Lord of the Rings_ books. In the books, Aragorn planned to go to Gondor and aid them in their fight against Mordor. Aragorn knew Denethor from his time at Gondor serving Ecthelion II. He might have known that he might not be welcome there. 1. Did he plan to take over as king or serve as he did previously? 2. Secondly why did Boromir agree to take Aragorn's help?
From Appendix A and the "Tale of Years", we know that Aragorn served Ecthelion II in disguise. This time, he intended to reveal his true identity, so we can be fairly sure he planned to become king. > His [Aragorn's] own plan, while Gandalf remained with them, had been to go with Boromir, and with his sword help to deliver Gondor. For he believed that the message of the dreams was a summons, and that the hour had come at last when the heir of Elendil should come forth and strive with Sauron for the mastery. > > ("Farewell to Lórien") Boromir accepted his help because he knew that Gondor was losing the war. > Yet we are hard pressed, and the Sword of Elendil would be a help beyond our hope — if such a thing could indeed return out of the shadows of the past. > > ("The Council of Elrond")
stackexchange-scifi
{ "answer_score": 18, "question_score": 7, "tags": "the lord of the rings, tolkiens legendarium" }
How to find an element in a container before a given starting position? I would like to find the **last** occurrence of an element in a container before some given starting position. For instance, if I'm trying to find the last space before a given character in a string 's', I believe the obvious approach would be something like: string::const_iterator b; b = i; // <-- 'i' specifies where to start looking while ((b != s.begin()) && (b[-1] != ' ')) b--; Is there a better way to do this using STL algorithms? * * * I've tried: b = find(string::const_reverse_iterator(i), string::const_reverse_iterator(s.begin()), " ").base(); But I'm not sure if this works as intended.
For generic purposes, I think I would use std::find_end with an adequate lambda function. The example on the page illustrates well the function's behavior.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c++, stl, containers" }
Create weighted igraph Graph from numpy summetric 2D array as adjacency matrix I am having a `numpy` 2D array, with the values representing the weights of edges between nodes. The matrix is symmetric, and I take the diagonal to be zero. I don't find an example of how to convert this matrix into igraph Graph object. I've tried the following approach, but it doesn't work: import numpy as np import igraph def symmetrize(a): return a + a.T - 2*np.diag(a.diagonal()) A = symmetrize(np.random.random((100,100))) G = igraph.Graph.Adjacency(A.tolist())
Use `Graph.Weighted_Adjacency()` if you want to preserve the original values in the matrix as weights. The weights will be attached as the `weight` edge attribute to the graph that igraph creates.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "python, arrays, numpy, matrix, igraph" }
SEO - List of links - Farmlinking? I'd like to know if listing a set of partner sites/blogs is useful for the pagerank growth. Does Google see it as an incorrect act? I read somewhere that if people exchange links, google seeks it and marks as a bad technique. If it doesn't matter, is the content of the linked site relevant?
That's called **Link farming** and it is a really bad SEO tecnique. If you link to another page for SEO purposes, **keep links relevant** and in a way that are interesting to the readers. An interesting article on Link Farming: The Tell-Tale Signs Of Link Farming
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "seo, pagerank" }
ImportError: No module named 'Crypto.HASH' but pycryto installed I am trying to load pycrypto module. When I do import Crypto I get no error but when I do from `Crypto.HASH import SHA256` , I am getting `ImportError` >>> import Crypto >>> hash = SHA256.new() Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> hash = SHA256.new() NameError: name 'SHA256' is not defined >>> from Crypto.HASH import SHA256 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> from Crypto.HASH import SHA256 ImportError: No module named 'Crypto.HASH' >>> OS : Windows 8 Python : 3.5 32 Bit Thank you.
You are misspelling it, the correct module name is `Crypto.Hash`: >>> from Crypto.Hash import SHA256 >>> h=SHA256.new() >>> h.update(b"Hello") >>> h.hexdigest() '185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969'
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python 3.x, pycrypto" }
How to install customer node.js binary module globally? So I've made my own module with C++ and node-gyp. Things go fine after `node-gyp configure build` and I've got under `build/Release` everything I need. Now, in my other project where I'm using this module, I don't want to add it like var a = require('../../mylib/build/Release/mylib'); but instead var a = require('mylib'); after defining dependencies in `package.json`. So how do I use npm or something else to achieve this?
You can add the entry point to your package to the `main` field in your package.json. This is what will be called when you do `require('yourpackage')`. See these links: 1. at end of section 8.1 < 2. under section `main` in <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js, node gyp" }
Programatically add Spring interceptor without application desciptor I have an interceptor that I would like to invoke on all requests. I would like to configure that interceptor without component-scan or adding it the `mvc:interceptors` element in the web.xml. Is it possible?
It is possible, if you use Java Configuration.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, spring, web applications, interceptor" }
Selection of feature class Currently, I would select a bunch of polylines in a fgdb, using Selection > Selection by Location. I will then be using a "AOI" (Area of Interest) polygon to help me select the polylines in a fgdb that are within AOI (usually, i will choose "are completely within" option), and these selected polylines will appear on one of my mxds. I would like to have a script that can help me do this: running the selection of polylines using AOI polygon as a reference. So, whenever i open up that mxd, i will be able to see the updated polylines on it. !enter image description here FYI, the feature class in fgdb will be updated monthly (names of fgdb and its dataset remain unchanged), and there might be a increase or decrease in the number of polylines every month (there are to be captured as long as there are within the AOI.
You can try to make a VBA script for ArcMap 9.3.1 Take a look at this post on esri forum as an example:
stackexchange-gis
{ "answer_score": 1, "question_score": 2, "tags": "arcgis 9.3" }
simple harmonic oscicalltor for real solution: just dont get it the general solution for $$\ddot{x}(t)+\omega^2 x(t)=0$$ can be expressed as $$x(t)=Ae^{i\omega t}+Be^{-i\omega t}$$ If $x(t)$ is real then $x(t)=\bar{x}(t)$. That's fine. But why does it imply that $B=\bar{A}$. I just can't see. Drives me mad. And please don't tell me because $e^{i\omega t}$ and $e^{-i \omega t}$ are orthonormal. I don't see how. If I picture these two vectors in the complex plane with e.g. $\omega t=30°$ they don't look perpendicular at all. Even if they were...that wouldn't help me anyway.
By constructing the complex conjugate we get $$\begin{align} \overline{x(t)}&=\overline{A\cdot e^{i\omega t}+B\cdot e^{-i\omega t}}\\\ &=\overline{A\cdot e^{i\omega t}}+\overline{B\cdot e^{-i\omega t}}\\\ &=\overline{A}\cdot e^{-i\omega t}+\overline{B}\cdot e^{i\omega t}\\\ &=\overline{B}\cdot e^{i\omega t}+\overline{A}\cdot e^{-i\omega t} \end{align}$$ Where the last equation only equals $x(t)=A\cdot e^{i\omega t}+B\cdot e^{-i\omega t}$ for $A=\overline{B}\Leftrightarrow \overline{A}=B$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "ordinary differential equations" }
Workflow error in VS2010 i m trying to run an example of microsoft workflow software. I get the following error in a line: wsh.Description.Behaviors.Add(new SqlWorkflowInstanceStoreBehavior(ApprovalProcessDBConnectionString)); WorkflowIdleBehavior wib = new WorkflowIdleBehavior(); wib.TimeToUnload = new TimeSpan(0, 0, 2); wsh.Description.Behaviors.Add(wib); wsh.Open(); <-- error: The InstanceStore could not be initialized. Can anyone help me?
Sounds like you need to run a couple of queries to set up an InstanceStore in your database. Look for: SqlWorkflowInstanceStoreSchema.sql SqlWorkflowInstanceStoreLogic.sql in the folder: %WINDIR%\Microsoft.NET\Framework\v4.xxx\SQL\EN Just run those two queries on whatever database you're connecting to via your ApprovalProcessDBConnectionString.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, visual studio 2010, workflow foundation 4" }
How to Pass HTML Content in Bootstrap 3 Popover Through data-content Attribute **Demo** I know we can pass HTML content in Bootstrap Popover by JavaScript but just wondering if there is a way to pass content through `data-content` without using JavaScript something like: var ecoloInfoTable = "<strong>Yes This is Data</strong>"; var data = '<button type="button" class="btn btn-success btn-xs" data-container="body" data-toggle="popover" data-placement="top" data-content="'+ecoloInfoTable+'"> <i class="fa fa-question"></i></button>'; $(".container").append(data); $("[data-toggle=popover]").popover(); Thanks
There is an option that enables HTML content in popover. This option can be passed via JavaScript e.g. $("[data-toggle=popover]").popover({ html: true }); or in HTML ( _which is what you are asking_ ) e.g. <div class="container"> <button type="button" class="btn btn-success btn-xs" data-container="body" data-toggle="popover" data-placement="top" data-content="In this title I have <b>bold</b> text" data-html="true"> <i class="fa fa-question"></i> </button> </div> <script> // Initializing popover without options $("[data-toggle=popover]").popover(); </script> As you can see in this demo, you can have HTML inside the `title` attribute and it an be shown properly in the popover.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery, html, twitter bootstrap, twitter bootstrap 3" }
Printing array in batch file using variable index, having trouble with delayed expansion All I am trying is to store a string in an array and then access them using variable as index. I have tried Delayed Expansion, but I don't know what is wrong with code. Please help. The test.cmd file contains @echo OFF @set i=1 echo ENTER Your First Name : setlocal enableDelayedExpansion set /p input_value[%i%]=%=% call:print endlocal @set i=2 setlocal enableDelayedExpansion echo ENTER Your Last Name : set /p input_value[%i%]=%=% call:print endlocal :print @echo !input_value[%i%]! GOTO:EOF Output: D:\backup_app\bat>test.cmd ENTER Your First Name : radhe radhe ENTER Your Last Name : kishan kishan !input_value[2]! The last line in the output is what that is troubling me.
You need to skip over the `:print` procedure (an you could enable delayed expansion only to necessary code snippet) as follows: @echo OFF setlocal enableExtensions @set i=1 echo ENTER Your First Name : set /p input_value[%i%]=%=% call:print @set i=2 echo ENTER Your Last Name : set /p input_value[%i%]=%=% call:print goto :next :print setlocal enableDelayedExpansion echo !input_value[%i%]! endlocal GOTO:EOF :next
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "arrays, windows, batch file, command" }
Auto resizing GtkScrolledWindow I have added three GtkHBox inside a GtkScrolledWindow. And set the size of each box as the size of the window. but, when exposed the size of the Scrolled window is resizing by itself. But, when i do the same with three Layouts ScrolledWindow size is maintained properly. What could be the reason for this.
`GtkHBox` doesn't have a scrolling interface. `GtkLayout` does. You can add a scrolling interface to something that doesn't have one, by putting it into a `GtkViewport` and then putting the `GtkViewport` into the `GtkScrolledWindow`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "gtk" }
swapping text and image order using CSS I need to swap the visual order of 2 elements using CSS HTML order: <div id="text-content"> .... </div> <div id="header-image"> .... </div> Visual order required: ______________________ | image | | (fixed height) | |______________________| ______________________ | text | | (variable height) | |______________________| I can't seem to get them to display properly. I have full access to XHTML and CSS, just need to swap the visual order for SEO purposes, while keeping the text as far up the code as possible. Cheers...
The best way to go, I think, is * giving the text div a `padding-top: xyz` to make space for the logo, where `xyz` is the height of the logo * and to `position: absolute; top: 0px; left: 0px` the logo. however, I can't really think of any SEO scenario where this would give any noticeable advantage.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, xhtml, seo" }
How to make exe/tar.bz2 from .o file in G++? Is there any way to make exe or tar.bz2 fiel from .o file in G++? Must I use nasm or any else program for making axe and tar.bz2, or it is possible in G++?
* To make an exe, use the linker: `g++ -o myprog myob1.o myob2.o` * To make a compressed archive, use tar: `tar cjf myarchive.tar.bz2 /path/to/all/my/files/` * To make an axe, use two sticks and three diamonds.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": -4, "tags": "c++, compiler construction, g++, exe, tar" }
mysql trigger not working on insert Table: items Create Table: CREATE TABLE `items` ( `ite_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `itemName` varchar(40) DEFAULT NULL, `itemNumber` int(10) unsigned NOT NULL, PRIMARY KEY (`ite_id`), UNIQUE KEY `itemName` (`itemName`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 delimiter | create trigger item_beforeinsert before insert on items for each row begin if new.itemNumber < 50 then set new.ite_id = null; end if; end; | now the following command doesn't cause a trigger insert items( itemname, itemnumber) values ( 'xyz', 1 ); any help would be very much appreciated, thanks!
Your ite_ID is not null and you want to set it null with your trigger, beside that it's auto increment, so you wont be able to 'control' all the values to assign to that field, I.E it wont overwrite values
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Visual "busy" indication in Primefaces I have a Primefaces-based application, in which there are some lengthy operations. When such operation is being executed, I want to indicate this somehow (like displaying an hourglass or a message, which appears at the center of the screen). What is the easiest way to do this in Primefaces/JSF?
I'd recommend doing it with `<p:blockUI>`. Here's an example: <h:form> <p:panel id="content" > ... <p:commandButton id="longOperation" value="Process" /> </p:panel> <p:blockUI block="content" trigger="longOperation"> <p>Here you can customize what appears as the overlay over the blocked content.</p> <p:graphicImage value="/images/ajax-loader.gif"/> </p:blockUI> </h:form> Take a look at < for more info.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 2, "tags": "java, jsf, jsf 2, primefaces" }
Where can I obtain the list of existing tag wikis? I'm not eligible yet to create one, but will be soon, and I'm very interested in contributing to the community in addition of answering questions.
A pretty roughly formatted list lives here: <
stackexchange-meta
{ "answer_score": 0, "question_score": 3, "tags": "support, tags, tag wiki, wiki" }
How can I get the type of a function that provides a const overload? Let's say I have the following class: class C { public: void f( int ) {} void f( int ) const {} }; The only difference between the two overloads of `f` is that one of them is `const`. I can't use `decltype( &C::f )` because there is still ambiguity. I want to get the function information by using a traits class, so I need to provide the function type.
You can force the non-`const` `C::f` overload to be chosen by passing `&C::f` to a function that expects a pointer to a non-`const` member function. To wit, template <class C, class Ret, class... Args> // trailing return type can be omitted in C++14 constexpr auto g(Ret (C::*p)(Args...)) -> decltype(p) { return p; } static_assert(std::is_same<void (C::*)(int), decltype(g(&C::f))>::value, "wrong overload"); (Note that additional work needs to be done if you want to support: C-style variadic functions, `volatile`-qualified functions, or ref-qualified functions.)
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "c++, templates" }
Need help writing recursive query I have a table in access with the following format:- ID | Name | Qty ----+--------+------ 1 | A1 | 10 2 | A2 | 20 3 | A1 | 30 4 | A2 | 40 5 | A1 | 50 ----+--------+------ I want to run a query which will return the sum of Qty for each row above it where the Name matches. So, the Output will be :- ID | Name | Output ----+--------+--------- 1 | A1 | 0 2 | A2 | 0 3 | A1 | 10 4 | A2 | 20 5 | A1 | 40 ----+--------+---------- I am not being able to write the query. I think I need some kind of recursive query, but I'm not very well versed in SQL/Databases.
Access does not support recursion. The following query should do what you want (i called your table NameQty): SELECT t1.Id,t1.name,sum(t2.Qty) FROM NameQty t1 LEFT JOIN NameQty t2 ON t1.name=t2.name AND t1.Id>t2.Id GROUP BY t1.Id,t1.name ORDER BY t1.Id I think you should also use some other column than ID for the definition of "above".
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "sql, database, ms access" }
Problem while creating a Left function in PostgreSQL I am trying to create a Left function in PostgreSQL as under CREATE OR REPLACE FUNCTION LEFT(text, integer) RETURNS text AS 'SELECT SUBSTR($1,$2);' LANGUAGE SQL IMMUTABLE; It got compiled fine. Now when I am invoking it as under select LEFT(',a,b,c',2) I am getting the output as `,a` when the expected output is `a,b,c` If I run `SELECT SUBSTR(',a,b,c' , 2)` it works as expected . Please help me out in identifying the mistake Thanks
`LEFT` function already exists in pg_catalog. So try a different function name or run SELECT public.LEFT(',a,b,c' , 2)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "postgresql" }
Are Javascript string arrays automatically separated by commas? After reading this discussion and this article, I still have this question. Let's say I have the following snippet: var arr = new Array(3); arr[0] = "Zero"; arr[1] = "One"; arr[2] = "Two"; document.write(arr.join(",")); If I replace the `document.write()` line with `document.write(arr);`, are they equivalent? Does the replacement statement automatically join array elements with a comma as the delimiter? Thanks in advance!
"But I couldn't figure out why" This is because everything has a `toString` function as part of its prototype. When you write it out, this function is invoked to get the string representation of whatever it is. For arrays, the default handling is the same as `join`. Array.prototype.toString.apply([1,2,3]) == Array.prototype.join.apply([1,2,3]) > true
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "javascript" }
GROUP-BY expression must contain at least one column that is not an outer reference i have this query: SELECT SolutionName -- Solution_NAM from Table_View Group By 1 where Table_View is of course a view. I am gettign this error message: Each GROUP BY expression must contain at least one column that is not an outer reference. Can you help me resolve this? It´s inside Ms SQL Server 2008
you cannot give Group by 1 try SELECT SolutionName -- Solution_NAM from Table_View Group By SolutionName
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "sql server, sql server 2008, tsql" }
How many examples exist of Lie groups that are 2-dimesional surfaces? It is relatively easy to show that $\mathbb{R}^2$ or $\mathbb{T}^2$ are 2-dimensional surfaces with a structure of Lie groups. I can not find other surface which are also a Lie group, there are more examples? Many thanks!
There's also a cylinder. That's it. You can prove this by fully classifying 2-dimensional Lie groups. It's much easier to classify 2-dimensional Lie algebras, of which there are two up to isomorphism, and hence 2 simply connected 2-dimensional Lie groups up to isomorphism: $\Bbb R^2$ and $\text{Aff}(1)$, the affine transformations of the line. Now one classifies their discrete closed normal subgroups. For $\Bbb R^2$, there are lattices, either isomorphic to $\Bbb Z$ or $\Bbb Z^2$, and the quotient is either a cylinder or a torus, depending. The only normal subgroups of $\text{Aff}(1)$ are translation groups, giving the same result.
stackexchange-math
{ "answer_score": 6, "question_score": 3, "tags": "differential geometry, lie groups, examples counterexamples, surfaces, smooth manifolds" }
ZF2 & Apigility - Correct way to setup GET and POST RPC services What is the correct way to setup GET and POST services in ApiGility? **Currently, if I am setting up a GET service, I will include the variable I require in my route:** > /api/verify/merchant[/:merchant_code] **And if I wish to setup a POST service, my route becomes:** > /api/verify/merchant > > And I add a **merchant_code** 'field' **And if I want my route to accept both POST and GET, I then do this:** > /api/verify/merchant[/:merchant_code] > > and add a merchant_code field as well... Is this the correct way to setup the routing for this?
In general you `POST` your new entities on the collection endpoint so in your case `/api/verify/merchant`. The server will respond with a new resource with a self href for the newly created `Merchant`. This href will be formatted like `/api/verify/merchant[/merchant_code]` where `merchant_code` will be the identifier for the newly added `Merchant` resource. Sending a `POST` request to `/api/verify/merchant[/merchant_code]` is not necessary/valid. You do `GET`, `PATCH`, `DELETE` or `PUT` requests on the endpoint of your Merchant resource depending on the action you want to perform (read, update, delete, replace).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, zend framework2, laminas api tools" }
Python and a JSON Array I am having problems with Python (Django) Framework. I at first attempted to send a Javascript Array straight to Django except it pulled only the last value. So I use now `JSON.stringify` which sends my JSON to Python. At Python it looks like this QueryDict: {u'[{"key:":"interface.dns","value:":192.168.0.1"}]':[u'']} And if I add more values it just adds to the first U. How can I make this so its a loop. e.g for each key value in the dictionary display it. Because it seams the JSON is being stored at position one in the Dictionary. Any Ideas
`QueryDict` objects implement the file interface. So you could decode the JSON simply with the standard JSON library: import json ... parsed_json = json.load(request.POST) # Or GET, depends on what you are using
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, python, django" }
What is $a: b: c$ if $a: b$ is $\frac ab$? I was teaching my younger brother the concept of ratios and proportions. I told him that a ratio can be expressed as a quotient of its constituents. For example if we have a ratio $a:b$, we can express it as $\displaystyle\frac ab$. The question he asked after this was really a thought-provoking question for me. He asked: > If $a:b$ means $\displaystyle\frac ab$, then what does $a:b:c$ mean? I know that in this case it can't be expressed as a quotient. So is there no other way to express the ratio $a:b:c$ just as we express $a:b$? What should I tell my brother?
Suppose $$a:b:c=x:y:z$$ Then , $$\frac{a}{b}=\frac{x}{y}$$ And $$\frac{b}{c}=\frac{y}{z}$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "soft question, fractions, ratio" }
How to access NFS shares from Windows 7? We have a group of users who run Windows and access files on a Linux box. Historically, they've been on XP and we run Samba on the Linux box. No problem. Now we're testing Windows 7 and finding interoperability to be a huge pain between the older version of Samba (the Linux box is running Ubuntu 8.04) and Windows 7. I'd like to use NFS instead, but the information out there on how to do this is confusing. Apparently you're supposed to install "Client for NFS" from Windows 7's "Turn Windows features on or off" dialog, but I don't see anything NFS related there. I've also seen guides which go into a huge amount of detail explaining how you need to map users between Windows and Linux, but then other places suggest that accessing NFS from Windows only requires a simple mount command or mapping a drive using server:/share syntax. Any pointers?
Under Services for NFS in windows features you need to check off client for NFS. I beleive this requires profesional or better (I don't have anything under enterprise available to verify)
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "windows 7, nfs" }
Is there any method to safe handle twice freeing memory by delete-expression? If in theory imagine a situation where, by chance or by mistake (either through carelessness, or due to lack of experience, etc.), the memory was freed twice using delete-exprssion (yes, a good developer will not allow this, in well-designed architectural solutions, but howewer) how to (can we, or is there any method to) safty handle the situation so that the application does not crash?
> so that the application does not crash This is just a side-effect, an implementation detail of the real problem. Double deleting causes undefined behavior according to the standard. There is no way to turn a program exhibiting undefined behavior back into one defined so no, there is no way to handle it safely. * * * Ideally you shouldn't be using `new` or `delete` at all.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "c++" }
Child window inform calling window when closed I have a parent window create a child window. When the child window closes, I want to have the parent window receive notification so that it can be refreshed. The child window cannot be modal. The user needs to be able to interact with the rest of the application.
In the parent window create a handler for the `Closed` event on the child window object. When the child window is closed, your handler will be called and the parent window will be notified.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "wpf, window" }
How do you use a list that was created in another function in Python? I have these two functions. def get_numbers(): phone_num = [] df = pd.read_csv('students.csv', names = ['name', 'phone number', 'class time', 'duration']) phone = df['phone number'].tolist() print(phone) for i in phone: phone_num.append(i) def use_num_list(): print(phone_num) I basically want to use the 'phone_num' list in another function. How would I go about doing that?
You need to return it from your function, and then pass it in to your other function. def get_numbers(): phone_num = [] df = pd.read_csv('students.csv', names = ['name', 'phone number', 'class time', 'duration']) phone = df['phone number'].tolist() print(phone) for i in phone: phone_num.append(i) return phone_num def use_num_list(phone_number): print(phone_number) numbers = get_numbers() use_num_list(numbers) Also, remember that the names of the objects only exist in their local scope. In other words, the variable name `phone_num` only exist in the function `get_numbers`. So when you call the function you have to assign the list to a new name, like `numbers = get_numbers()`. Now, `numbers` will contain the list and you'll be be able to access the list within the global scope. From here, you can pass it to other functions.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "python, list" }
How to show any convergent sequence is strongly discrete in Hausdorff space? Given a space $X$ and $C \subset X$, we say that $C$ is strongly discrete if there exists a disjoint family $\\{U_x: x\in C\\} $ of open sets in $X$ such that $x\in U_x$ for all $x\in C$. The question is this: > How to show any convergent sequence is strongly discrete in Hausdorff space? Thanks ahead.
We have to take $C$ which consists only of the terms of the sequence (not the limit $x_{\infty}$, otherwise it won't work). We can assume that $x_i\neq x_j$ if $i\neq j$. For $i,j\in\Bbb N\cup_{\infty}$, $i\neq j$, we can find disjoint open sets $O_{i,j}$ and $O'_{i,j}$ such that $x_i\in O_{i,j}$, $x_j\in O'_{i,j}$. For all $i\in\Bbb N$, we can find $N_i\in\Bbb N$ such that $x_j\notin O_{i,\infty}$ if $j\geq N_i$. We can assume $N_i>i$. Then take $U_i:=\bigcap_{k=1}^{N_i}O_{ik}$: it's an open set. These ones are disjoint.
stackexchange-math
{ "answer_score": 5, "question_score": 4, "tags": "general topology, proof writing" }
How to preserve custom configurations across reboots when using juju and maas? I've installed MAAS to get a set of Ubuntu 12.04 servers running and I used juju to install the hadoop charm on them, but I needed to change some of the configuration settings on one of the machines to make it work. I noticed that after rebooting the machine my changes were removed and the original settings were back. Is there a non-hacky way (custom shell script that runs on reboot) to define configurations that need to be reloaded? In my case I would like to simply define the file that should be reloaded on reboot. I believe this is an issue that goes beyond the hadoop charm specifically (hopefully). **System** * 12.04 Stock MAAS * 12.04 Stock juju (0.5bzr) * 12.04 Stock Hadoop charm (but my question is for the general case)
The system config will happen in two places: in the commissioning phase, when the 'OS is installed', and in the charms that get deployed, when configuration can happen. If the config your want is at the OS / hardware setup level, then look into commissioning scripts. If it's more related to the workload, look into a subordinate charm that you can deploy onto any machine to get the result you want.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 1, "tags": "configuration, juju, maas" }
Does EAV datamodels considered as advanced form of database normalization? i am confused when looking at databases designed with the EAV concept. EAV stands for entity, attribute and value. my question is: Does EAV datamodels considered as advanced form of database normalization ? is it a "must use" to be "up to date" ? to cut long things short: when to use EAV and when not?
No, they are considered to be an anti-pattern. They can be seen as taking normalization to an absurd level (I have seen people think that this is a good idea), causing one to lose all notion of easy ad-hock querying and causing havoc with the notion of proper indexing. EAV has a place when you have no idea what the schema will be (say for a client customizable "database").
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "database, normalization" }
How to specify the directory of archive to be extracted using jar command? I have C:\Program Files\Java\jdk1.8.0_20\bin\jar.exe D:\ounce\advanced\bank.zip Currently, my command shell is at D:\ounce\advanced> When I use this command: C:\Program Files\Java\jdk1.8.0_20\bin\jar xf D:\ounce\advanced\bank.zip to extract bank.zip, I get "illegal option: F" The same thing happens when I replace D:\ounce\advanced\bank.zip with just bank.zip I'm trying to do it the hard way without using environment variables. How can I do this right? Thank you for your help.
program files - has space in it you need to put the entire path in double quotes
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "java, shell, command line, jar" }
Convert comma separated string to datetime The Exchange webservice has a method that takes the DateTime in the format below appointment.Start = new DateTime(2014, 03, 04, 11, 30, 00); I have a string which is formed by concatenating various fields to form the date my string is as below: string date="2014,03,04,11,00,00" But if i try to to parse my string as the date it gives the error "String was not recognized as a valid DateTime". DateTime.Parse(date)
You can use `DateTime.ParseExact`: string date = "2014,03,04,11,00,00"; DateTime dateTime = DateTime.ParseExact(date, "yyyy,MM,dd,HH,mm,ss", CultureInfo.CurrentCulture);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, exchangewebservices" }
Duplicate values are inserted into table though @Id used for one of property in entity class in jpa Used @Id annotation for one field in entity class and inserted the same data twice using jpa persist method. Both the times data inserted successfully i.e duplicate data inserted. @Id represents primary key and primary key should be unique but here duplicates values are inserted. Note: i'm not specified the primary key constraint at DB side while creating table. Below is the entity class. `@Entity public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Id private BigDecimal employeeid; private String firstname;` private String lastname; private long salary; // getters and setters here } Please explain why jpa entity allowing duplicate records though @Id property used.
You need to specify primary key Generation strategy. This strategy will be used by the JPA to generate the Primary Key. The Generation strategy may vary, it depends on the database vendor you are using. e.g. for MYSQL server annotate primary key like this: @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private BigDecimal employeeId; This will generate an incremental primary key for the new entity. Answering to your question, ORM not gonna tell you about a duplicate entry for the same entity persisted twice. ORM depends on primary key for that. You should add Unique constraints in your columns. This will throw SQLIntegrityConstraintViolationException exception wrapped in avax.persistence.PersistenceException if you persist logical duplicate entity. Catch this exception and handle it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jpa" }
List all rows despite join I don't understand why what i am trying doesn't work. I have two tables Table1 id_tb1 | tb1field 1 aaa 2 bbb 3 ccc 4 ddd 5 eee Table2 id_stuff | id_tb1 1 1 1 4 1 5 2 1 3 1 What id need is to join tb1 and tb2 but also list all records from tb1. Something like this : Result id_tb1 | tb1field | tb2.id_stuff 1 aaa 1 2 bbb NULL 3 ccc NULL 4 ddd 1 5 eee 1 So I did this : SELECT t1.*, t2.id_stuff FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.id_tb1 = t1.id_tb1 WHERE t2.id_stuff = 1 But obviously, it's not the good solution. Someone has an an idea ? Thx.
if you add a condition on a LEFT JOINed table in the WHERE clause, this is just as if you where doing an INNER JOIN. Add that condition to the left join SELECT t1.*, t2.id_stuff FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.id_tb1 = t1.id_tb1 and t2.id_stuff = 1
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, sql" }
How to check if DNS is encrypted? I have installed DNSCrypt , its OpenDNS encrypted DNS patch for Ubuntu & other Linux users & it's working fine. How do I know if my DNS is encrypted? I have googled but didn't find anything. **Status** one@onezero:~$ status dnscrypt dnscrypt start/running, process 1013 one@onezero:~$ sudo netstat -atnlp Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.2:53 0.0.0.0:* LISTEN 1013/dnscrypt-proxy ### Updated Wireshark ### @Alvar !enter image description here !enter image description here !enter image description here !enter image description here # without DNSCrypt !enter image description here
You could check it with `Wireshark` by listening to your network card, just follow these steps: 1. `sudo apt-get install wireshark` (paste it into a terminal) 2. start it from a terminal with `sudo wireshark` (you need to be **sudo** to be able to listen to your network card.) 3. then **start listening** and filter out everything but your own ip. Now just check if the **dns** protocols are encrypted. 1. use the filter to only show `dns` 2. Stop the scan. 3. click on a list item that says **dns** and comes from your ip. 4. Now click on the transmission protocol to see if it's encrypted.
stackexchange-askubuntu
{ "answer_score": 5, "question_score": 14, "tags": "encryption, dns, dnscrypt proxy" }
How can I close running background apps except mine? When the user clicks on the "Close running Apps" Button then every application which is running in the background needs to be closed except my current application. How can I do this? Thank you
You could take a look at: How to kill all running applications in android? I think the answer there would really help you
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "android, sdk" }
What do I say to make a new line when using voice recognition? I've found I can make punctuation happen by saying "comma", or "period", but I can't find the word for new line. I tried "paragraph", and "line break", but it just prints those words.
I found that saying `period newline` gives you a new line, after putting a period on the current line. Also `period new paragraph` work.
stackexchange-android
{ "answer_score": 16, "question_score": 41, "tags": "voice recognition" }
Facebook Login Not Working on One Site, Exact same code works on my other My Facebook connect stopped working on TopTopGames.com for some reason. I have no idea why. Try contacting Facebook support and they practically did nothing for me. Since this issue, i tried to use Facebook code from the documentation on both sites (toptopgames.com, flashgratuit.com): < Here are the test files: < Only changes are the name. I tried playing with the code. Downright copying and paste the developers document ion code. I tried making new API keys. None of it worked for TopTopGames. I copied the script over to other sites and it worked fine.
Just a guess: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, facebook, web, facebook login" }
Get the map keys and not the map values I have some data like this: Map<Integer, String> foo Now I can get the corresponding `String` with `foo.get(1)` But is it also possible to get all the `Integer`s which have the `String` "abc"? Like this pseudo code: `Integer[] someMore = foo.getKeys("abc")`
Try: Set<Integer> myInts = new HashSet<Integer>(); for(Entry<Integer, String> entry : foo.entrySet()) { // go through the entries if(entry.getValue().equals("abc")) { // check the value myInts.add(entry.getKey()); // add the key } } // myInts now contains all the keys for which the value equals "abc"
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java" }