INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to program relative path from string in Java I have the following problem. I am writing a program that imitates Windows Command prompt. For example user enters: `cd C:\\Intel` and in my code I solve it like this: setCurrentPath(Paths.get(string)); where `setCurrentPath` is a method which sets the current path to the one which is entered (string). My problem is that, how can I set new path if the entered path is relative. For example, if I am currently in `C:\\Intel` and user wants to go to `C:\\Intel\\Logs` and enters: `cd Logs` (instead of `C:\\Intel\\Logs`). I suppose there are some methods build in Java which can help me out but I am learning Java only a few months so I am unaware of them. Be aware that I threat path as a string.
You could test if path from user is absolute or not and based on result either set it directly, or use `Path.resolve`. DEMO: Path currentPath = Paths.get("C:\\projects\\project1"); String pathFromUser = "..\\project2"; Path userPath = Paths.get(pathFromUser); if (userPath.isAbsolute()){ currentPath = userPath; }else{//is relative currentPath = currentPath.resolve(userPath).normalize(); } System.out.println(currentPath); Output: `C:\projects\project2`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, shell, path" }
Why does sed output all at once? I have a 500Mb file that I am trying to manipulate with sed. Everything works fine just I noticed it reads and processes all in memory and then outputs all at once. Is this natural behavior for a file this size? I was expecting it to output each line after finishing and continuing to the next.
on some version of sed you can use option `-u` to work in a stream version. AIX sed > -u > > load minimal amounts of data from the input files and flush the output buffers more often GNU sed > `-u' `\--unbuffered' > > > Buffer both input and output as minimally as practical. (This is > particularly useful if the input is coming from the likes of `tail > -f', and you wish to see the transformed output as soon as > possible.) >
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sed" }
SQL query into Hibernate query How do I write this SQL query as a Hibernate query? SELECT u.id, u.orderId, p.productName, u.key2, i.forsor_id FROM `ub_orders` u JOIN productInfo p ON p.productId=u.productId JOIN ir i ON u.key2=i.id WHERE p.productName LIKE '%OSS HOSTING FEE%' AND u.createdDate > 2014-02-1 AND forsor_id IS NULL ORDER BY u.key2;
I readily see two problems. The first is the use of backticks and the second is the need for single quotes around the date constant: SELECT u.id, u.orderId, p.productName, u.key2, i.forced_matrix_sponsor_id FROM ubercart_reseller_orders u join productInfo p on p.productId=u.productId join ir i on u.key2=i.id where p.productName like '%OSS HOSTING FEE%' and u.createdDate > '2014-02-1' and ----------------------^ forced_matrix_sponsor_id is null order by u.key2;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, hibernate" }
$211!$ or $106^{211}$:Which is greater? A BdMO question: > Let $a=211!$ and $b=106^{211}$. Show which is greater with proper logic. By matching term by term,it is pretty easy to note that $106!<106^{106}$ $106^{105}<107\cdot 108\cdot 109...........211$ However I am at a loss to see how this will help.The solution must something along the lines of this one but I am unable to see so.I also factorized 106 but it complicated matters further.A hint will be appreciated.
Use a trick similar to Gauss' famous trick for summation (although he probably wasn't the first, if at all, to discover it). Divide the $211!$ into pairs, $(1,211),(2,210),(3,209),\ldots(105,107)$. Now we can note that for every such pair can be written as $(106-k,106+k)$ and therefore: $$(106-k)(106+k)=106^2-k^2<106^2.$$ Now it's easy to finish. There are $105$ pairs and one additional $106$ to each side. Therefore $211!<106^{211}$.
stackexchange-math
{ "answer_score": 23, "question_score": 10, "tags": "algebra precalculus, inequality, contest math, factorial, number comparison" }
SQL many-to-one join using two foreign keys I have two tables (Table A & Table B) that I have in a database (SpatiaLite database). I would like to join all the entries in Table A with Table B using two foreign keys (TableA.Location & TableB.LSD, TableA.LICENCE_NO & TableB.Licence_No); however, there will be multiple INCIDEN_NO entries in Table A that match up with the joined rows in Table B. Since there will be many INCIDEN_NO entries associated with the Licence_No in Table B, I would like to evenly distribute the INCIDEN_NO entries among all the LIC_LI_NO entries in Table B that align with the foreign keys. The rows from Table A can be randomly assigned to each LIC_LI_NO in Table B randomly and in no particular order. I cannot seem to find a SQL expression for this operation, which has really stumped me for weeks. !picture of the join and potential output table
You could match the rows up randomly with something like this: with B as ( select row_number() over () as rn, lic_li_no from B ), A as ( select abs(random()) % cntb + 1 as randnum, a.* from A cross apply (select count(*) as cntb from B) b ) select * from A inner join B on A.randnum = B.rn; You could also generate the cross product and keep random rows. I tried this query out on SQLite but it didn't seem to work as I expected: select * from A cross join B where abs(random()) % 20 = 1 That said, I don't understand the purpose behind all this and it's certainly not a common thing to do in a database.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "sql, qgis, spatialite" }
Python - Создать массив 10 на 10 и заполнить его значениями по условию Я не понимаю ошибки list index out of range for i in range(n): for j in range(n): mass[i][j] = r mass
Вы обращаетесь к элементу массива, но он ещё не создан. Создайте его с помощью спискового включения (или иным образом) перед циклом. **_Пример:_** n = 10 li = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): li[i][j] = i + j # Some value print(li) **_stdout_** [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [8, 9, 10, 11, 12, 13, 14, 15, 16, 17], [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]]
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
what is the process of pushing csv file from Spark to database? I would like to understand if I am loading csv file to a DB table, am I suppose to create table and schema in the database before I do that? Or, can we create table, schema from spark through sqlcontext? If yes, then how ? any sample code that I can refer? I tried, but all I could understand that I need to create table, and schema in the DB before I load files from Spark... I have spark 1.6.1, and scala 2.10.5, sql server 2008 Thank you...!!
This answer may help you: Saving / exporting transformed DataFrame back to JDBC / MySQL In summary, yes you will need to have the table pre created. But from spark 2.0 you can create table while loading from csv.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "sql server, scala, apache spark" }
Rules for Dazed in Arcadia Quest What (and where) are the rules for Dazed heroes and monsters in basic Arcadia Quest? I know I've read them, but I can't seem to find them hunting through the rule book.
From the Arcadia Quest rulebook (accessed here), page 27: > DAZE > Some attacks are able to daze their target, leaving him open to future attacks. When a Character is dazed, lay its figure on its side to indicate his condition. A dazed Character is not allowed to roll any Defense dice against attacks. Other than that, he may act normally, moving and attacking as usual. When a dazed Hero Rests he recovers from the daze effect. Place his figure back up to indicate that. Incidentally, the rulebook has an index on page 35, which lists where you can find the rules for Daze.
stackexchange-boardgames
{ "answer_score": 2, "question_score": 0, "tags": "arcadia quest" }
Where can I find open source Android apps? I'm not an open source zealot, but I generally prefer to use open source applications over proprietary ones if they stack up. Are there any directory sites with reviews, ect that specialize on open source Android apps? The closest thing I've been able to find is Wikipedia's list.
You can install F-droid to get a market-style repository of Free and Open Source android apps: <
stackexchange-android
{ "answer_score": 20, "question_score": 36, "tags": "applications, open source" }
Fix Javascript Invalid regular expression: Invalid Group I am using a regular expression to separate elements of a url: < /(?:([\w\-\+]+(?<!domain\.com))\/?)?(?:([\w\-\+]+(?<!domain\.com))\/?)?(?:#([\w\-\+]+))?(?:\?([\w\-\+]+))?$/ Here would be the results of this match: $1 = page $2 = post $3 = fragment $4 = query I am getting this error: Invalid regular expression: /(?:([\w\-\+]+(?<!localhost))\/?)?(?:([\w\-\+]+(?<!localhost))\/?)?(?:#([\w\-\+]+))?(?:\?([\w\-\+]+))?$/: Invalid group
This part: `(?<!domain\.com))` is the problem since Javascript doesn't support `lookbehind`.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": -1, "tags": "javascript, regex, url, match" }
Calling a JavaScript functions whose name is saved in a string Is it possible to run a function whose name is saved in a string? For example: I have three functions: function nr1(p0, p1){ /* [...] */ } function nr2(p0, p1){ /* [...] */ } function nr3(p0, p1){ /* [...] */ } and I have a string whose content is a function name, for example: var a_string = "nr2(27, 42)"; Is it possible to execute the function whose name is stored in the string?
you can eval() it. Observe the following example... function something() { console.log('did'); } var str = 'something()' eval(str) // did As comments suggest, not the best idea to take and run with - though it works... To expand on that just a bit more, I found this blog post which shares some good pointers on the somewhat controversial usage of this technique: eval() isn’t evil, just misunderstood * * * JSFiddle \- simple demo
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
how to remove device udid from provisioning profile, i edit and remove them but they can install the new ipa I've developed an app and want to use it in some confirmed devices. But now I want some of the devices can not use this App any more. So I removed some devices' udid in the provisioning profile and compiled and signed again, but those removed devices still able to install the new ipa file which I compiled from the new provisioning profile. I couldn't find any clue for this. And then I removed the appid, create a new one and then create a new provisioning profile also, but still new ipa can be installed in those removed devices! Your suggestion is appreciated.Thanks.
Have you tried removing devices from developer.apple.com account then you need to regenerate provisioning by selecting devices , then it will work
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "ios" }
How to add found item to a QListView using Qt? I am trying to implement search option for my file browser application. I can get the item after taking an input from the user. Now, I want to add this item to my listview. Also after the search is over, the item should be clickable to open them. Here, is the piece of code... Any suggestions will be appreciated. void Browser::search() { QDirIterator it(path,QDir::AllDirs|QDir::Files|QDir::NoSymLinks|QDir::NoDotAndDotDot,QDirIterator::Subdirectories); while(it.hasNext()) { it.next(); if(it.fileInfo().completeBaseName().contains(content,Qt::CaseInsensitive)) { qDebug()<<"it.fileinfo = "<<it.fileInfo().fileName(); } } path.clear(); }
Instead of List View you can use List Widget and simply fill the list using method addItem or addItems. If your list is small/simple it doesn't in my opinion make sense to use Model-View paradigm. Look at QListWidget in documentation
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "search, qt4" }
Detachable Answer and Preview Section Can it be a good add-on to have the capability to undock/detach "Your Answer" and the underlying preview section in a separate `modal` so that an answer-er can flexibly use the size of the modal to frame the answer in an full page format? Right now, I agree we have the capability of extending the text-area height and I like it.
The idea of (at least) the preview section of the _Your Answer_ part of the page is to give you an idea about how your answer would _really_ look in the page. Meaning, whatever you see in the preview, is what you get in the answer (in terms of spaces, where lines end, markdown, etc). If you detach the "Your Answer" part into a separate "floating" module, you lose some of that (specifically the "where my line ends" one). That's why I disagree with this feature request.
stackexchange-meta
{ "answer_score": 3, "question_score": -1, "tags": "feature request, answers, addon" }
How do I add text to an empty element in Hpricot? If I have an empty tag: <tag/> How can I add text so that I end up with: <tag>Hello World!</tag> I can only seem to swap the whole tag with different content or add content before/after it.
Seems I just needed to use the call: my_node.inner_html my_content
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby, hpricot" }
How can I get the font cursor at top, text-align: top? If i set the css for textarea like this=> #id_content { padding: 0; width: 100%; height: 600px; } The height and width work. But if i type something on textarea texts are at the middle of the height of the textarea though the padding:0. Why is it happenning? How can i fix it? This is the html source=> <div id="id_div_content"> <form action="/createpost/" method="post"><div style='display:none'><input type='hidden' name='xxx' value='xxx' /></div> <p><label for="id_title">Title:</label> <input id="id_title" type="text" name="title" maxlength="100" /></p> <p><label for="id_content">Content:</label> <input type="text" name="content" id="id_content" /></p> <input type="submit" value="Submit" />
That happens if you are using the input tag in your html as such: <input type="textarea" id="id_content" /> If you are, use the textarea tag instead: <textarea id="id_content"> </textarea>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "html, css, fonts, textarea, height" }
Image attachment sends?? but doesnt apppear in email message Python smtp I am trying to send screenshots along with an email message.. The message gets through fine. In Windows Live mail it has the attachment icon. but no attachments are there. Online in outlook it has no attachment.. msg = MIMEMultipart('alternative') msg['Subject'] = client_name + " eBay Template " + date msg['From'] = sender_address msg['To'] = recipients_address msg.preamble = 'images' ... # attach screenshot iways_filename = dictstr['ItemID'] + "_i-ways" + '.png' ebay_filename = dictstr['ItemID'] + "_ebay" + '.png' # iways img_data = open(iways_filename, 'rb').read() image = MIMEImage(img_data, name=os.path.basename(iways_filename)) msg.attach(image) #ebay img_data2 = open(ebay_filename, 'rb').read() image = MIMEImage(img_data2, name=os.path.basename(ebay_filename)) msg.attach(image) I get no errors..
I found the solution.. msg = MIMEMultipart('alternative') msg['Subject'] = client_name + " eBay Template " + date msg['From'] = sender_address msg['To'] = recipients_address msg.preamble = 'images' Take away the 'alternative' and Voila! msg = MIMEMultipart() msg['Subject'] = client_name + " eBay Template " + date msg['From'] = sender_address msg['To'] = recipients_address msg.preamble = 'images'
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, smtp, attachment" }
$\mathbb Z$ is integrally closed in $\mathbb Q$? I understand that an integral domain $D$ is said to be integrally closed in $S$ if whenever an element $s \in S$ can be viewed as a root of a polynomial with coefficients in $D$, it must be in $D$. However, apparently $\mathbb Z$ is integrally closed in $\mathbb Q$, which I don't get, since surely given any $\frac{a}{b} (a, b \in \mathbb Z$), it is the root of the polynomial $bx - a$, and yet $\frac{a}{b}$ may not be in $\mathbb Z$. Where have I gone wrong here?
The polynomial $\frac{a}{b}$ satisfies is required to be monic, namely the coefficient of the highest degree term has to be $1$.
stackexchange-math
{ "answer_score": 8, "question_score": 6, "tags": "abstract algebra, commutative algebra, algebraic number theory" }
What is the brightest star (relative magnitude) in M31? I am wondering what the brightest individual star is in M31, the Andromeda Galaxy. Specifically, brightest as seen from Earth (so relative magnitude).
The Variable stars that Hubble studied in M31 when he showed that it was a galaxy are among the most luminous. They include Var-A1, a luminous blue variable, and magnitude about 16.5. Var A-1 is one of the most luminous stars known. Nasa has a catalog of stars in the m31 field, The brightest star in this catalog is an 11.4 magnitude star. But I think that database needs careful interpretation.
stackexchange-astronomy
{ "answer_score": 1, "question_score": 8, "tags": "star, apparent magnitude, magnitude, hypergiants, m31" }
Is moment of inertia cumulative? For example, on Wikipedia, I am given the formula $$I = (m/6)(P.P+P.Q+Q.Q) $$ to calculate the moment of inertia for a triangle with points origin, $P$, and $Q$. If I were to have two triangles bound together on origin and $P$ or $Q$, could I add the two moment of inertia together?
Shortly: Yes The reason is that to calculate the moment of inertia we take the sum of all **point** masses multiplied by the square of their respective distance from the axis of rotation. $$ I=\sum_{i=0}^N m_i r_i^2 $$ So the physics are the same if you have one, two or many such triangles (as long as you are rotating everything around the same axis. on a side note, to add moments of inertia of objects given for center of mass rotation when the rotation is not around the center of mass of the individual objects, use the Parallel Axis Theorem
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "rotational dynamics, moment of inertia, superposition" }
What is an IIS application pool? What exactly is an application pool? What is its purpose?
Application pools allow you to isolate your applications from one another, even if they are running on the same server. This way, if there is an error in one app, it won't take down other applications. Additionally, applications pools allow you to separate different apps which require different levels of security. Here's a good resource: IIS and ASP.NET: The Application Pool
stackexchange-stackoverflow
{ "answer_score": 303, "question_score": 282, "tags": "asp.net, iis, application pool" }
Flash player on Ubuntu 10 not working after Flex builder installation I've just installed Flash builder on my machine, which went ahead and installed the debug version of Flash on my machine as well. It appears now that this has broken Flash in my browsers or at least the browsers have no idea where flash is located on my machine. When I open a browser and navigate to a Flash page I get the message, "Alternate HTML content should be placed here. This content requires the Adobe Flash Player. Get Flash " This is from Google chrome but FF is also effected. How do I fix this to use my installed debug version of flash.
Download Debug Flash Player from Adobe page manually. Seems that you need this one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache flex, flash, ubuntu, flexbuilder" }
Set permanent Environment variable using Command Prompt i have an unzip.exe file. i want to register it to environment variable such that when ever user type unzip in his command prompt he/she can use unzip.exe file. I what to do this using Command prompt. how should i do this. Thanks in Advance
This is a quick and different method and will add unzip.exe to an existing part of the path. copy unzip.exe "%windir%"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "cmd, environment variables" }
Problem with determining currents in multi-source circuit I need to solve the circuit shown below: !schematic simulate this circuit - Schematic created using CircuitLab And here is my attempt. ![My attempt]( I'm sure my attempt is wrong here but I'm not really sure why. I've tried to use the mesh method to determine the currents in the cicuit. I've ended up with these equations for the currents: $$ i_A = i_1\\\ i_B = i_2 - i_1\\\ i_C = i_2 - i_3\\\ $$ And KVL: $$ 1:\; 9V - 10k * i_A + 20k*i_B - 10V = 0\\\ 2:\;10V - 20k * i_B - 30k * i_C + 12V = 0\\\ 3:\;12V + 40k * i_C - 30k * i_C = 0 $$ Based on these equations $$ i_A = -766\mu A\\\ i_B = -330\mu A\\\ i_C = -370\mu A $$ I've tested this cicuit in a simulator (falstad) and the current on R1 should be 420μA, which points to a really big mistake on my account. Any help or tip how to fix these equations would be welcomed.
You are doing the mesh method wrong, specifically the currents on it. To do it correctly: 1. Define the current meshes. You can select on each one does it flow clockwise or counter clockwise but as a beginner it's probably the easiest to use same rotation for all of them. ![enter image description here]( 2. Now do the equations, correct ones are below. If there is another current flowing on same wire, you need to take that to account! $$ \begin{cases} 10k \cdot Ia + 20k \cdot (Ia-Ib) + 10V - 9V = 0 \\\ 20k \cdot (Ib-Ia) + 30k\cdot (Ib-Ic) - 12V - 10V = 0 \\\ 30k \cdot (Ic-Ib) + 40k\cdot Ic + 12V = 0 \end{cases} $$ 3. Solve the equations with calculator (or by hand...) and you'll get the following results: $$ \begin{cases} Ia = 420μA \\\ Ib = 680μA \\\ Ic = 120μA \end{cases} $$ 4. Now you can get the real currents from pic: $$ \begin{cases} IR1 = Ia = 420μA \\\ IR2 = Ib - Ia = 260μA \\\ IR3 = Ib - Ic = 560μA \\\ IR4 = Ic = 120μA \end{cases} $$
stackexchange-electronics
{ "answer_score": 1, "question_score": 0, "tags": "circuit analysis, current, kirchhoffs laws" }
Show that $f$ has a unique fixed point. > Let $M$ be complete and let $f:M\to M$ be continuous .If $f^k$ is a strict contraction for some integer $k>1$ ,show that $f$ has a unique fixed point. **My try** : Let us fix $x_0$.Let $g=f^k$. Put $x_{n+1}=g^{n+1}(x_0)\implies d(x_{n+1},x_{n})=d(g^{n+1}(x_0),g^{n}(x_0))\le \alpha d(g^{n}(x_{0}),g^{n-1}(x_{0}))\le\ldots\le \alpha ^nd(g(x_0),(x_0)) $. where $0\le \alpha<1$ $d(x_n,x_m)\le d(x_n,x_{n-1})+d(x_{n-1},x_{n-2})+\ldots +d(x_{m+1},x_m)\le \\{\alpha^{n-1}+\alpha^{n-2}+\ldots \alpha ^{m}\\}d(g(x_0),(x_0))\to 0 $ as $n,m\to \infty$ So,$x_{n}$ is Cauchy $\implies y=\lim x_n$ for some $y$[Since $g$ is continuous] $\implies g(y)=\lim g(x_n)=\lim g^{n+1}(x_0)=\lim x_{n+1}=y\implies y$ is a fixed point of $g\implies f^k(y)=y$. If $f(y)\neq y\implies d(f(y),y)>0$ . I am having trouble proving $f(y)=y$. Will you please help me in doing it?
First: You proved the fix point theorem again, I do not think there is need of it, just apply it to $g := f^k$. Hence $f^k$ has an unique fixed point, say $y \in M$. It follows that $f$ cannot have a fixed point $x \ne y$, as $f(x) = x$ for some $x \in M$ implies $f^k(x) = x$ and hence $y = x$. Therefore, $f$ has at most one fixed point. To prove that $y$ is fixed by $f$, note that $f(y)$ is a fixed point of $g$, too: We have $$ g\bigl(f(y)\bigr) = f^{k+1}(y) = f\bigl(g(y)\bigr) = f(y) $$ As $g$ has only one fixed point, we must have $f(y) = y$.
stackexchange-math
{ "answer_score": 4, "question_score": 3, "tags": "real analysis, metric spaces, fixed point theorems" }
"Меньше (выше), чем". Нужна запятая? _В 2017 году объем переработки нефти на белорусских НПЗ составил 18,1 млн тонн, что на 2,6% меньше чем в 2016 году._ Нужна ли здесь запятая перед «чем»? _Это выше, чем **было** в провальном 2016 году, когда цены на черное золото буквально обрушились, однако ниже, чем **было** в 2014-2015 году, когда белорусы закупали около 23 млн тонн нефти._ Нужны ли здесь запятые перед словами «чем»? Если выкинуть слова «было», запятые перед «чем» нужны/не нужны будут?
Во всех приведенных предложениях запятая перед союзом ЧЕМ ставится, так как в них присутствует **сравнение или сопоставление.** Запятая не ставится в устойчивых выражениях при отсутствии сравнения или сопоставления. Розенталь Пунктуация. § 41. Цельные по смыслу выражения. / Справочник по русскому языку 4. **Внутри сочетаний (не) больше чем, (не) меньше чем, (не) раньше чем, (не) позже чем и т. п., если они не содержат сравнения, запятая не ставится:** Вы были для меня больше чем другом; Выпуск продукции увеличился больше чем вдвое; Расчёты оказались более чем приблизительными; Работу можно выполнить меньше чем за час; **Но (при наличии сравнения или сопоставления):** Работает не меньше, чем другие; Гостей оказалось меньше, чем ожидали; Страдали от холода больше, чем от голода; Вернулся раньше, чем ожидали; Эта комната выше, чем соседняя;
stackexchange-rus
{ "answer_score": 8, "question_score": 3, "tags": "пунктуация, запятые" }
How to split() string with brackets in Javascript i just want to make str = "a(bcde(dw)d)e" to arr = {"a", "(bcde)", "(dw)", "(d)", "e"} What regEx can i use in `str.split()`? PS: Explanations || helpful links welcome. Examples: s: "a(bcdefghijkl(mno)p)q" --> [ 'a', '(bcdefghijkl)', '(mno)', '(p)', 'q' ] s: "abc(cba)ab(bac)c" --> [ 'abc', '(cba)', 'ab', '(bac)', 'c' ]
Go through each parentheses using a counter: array = [], c = 0; 'abc(cba)ab(bac)c'.split(/([()])/).filter(Boolean).forEach(e => // Increase / decrease counter and push desired values to an array e == '(' ? c++ : e == ')' ? c-- : c > 0 ? array.push('(' + e + ')') : array.push(e) ); console.log(array)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, arrays, regex, string, split" }
What does underscore cursor (caret?) and half cursor (caret?) mean? I noticed different styles. But I cannot relate to what I typed, maybe because I have many missed key strokes.
Vim allows the cursor shape to be customized. Depending on your system, Vim changes the cursor shape according to the mode it is in. By default, some of these are * normal mode: a block cursor * insert mode: a vertical bar * operator pending mode: a "half cursor" * replace mode: a horizontal bar (or "underscore") To illustrate, Vim starts in normal mode. Hit `i`, and vim is now in insert mode. Now, any keypress gets inserted as text. Hit `<Esc>` to return to normal mode. Hit `d`, and vim is in operator pending mode, waiting for a motion to specify the text that this **d** elete operator will work on. etc. There are other modes too, such as visual, visualLine, to name a few. For more, see * `:help vim-modes`, * `:help mode-switching`, * `:help 'showmode'`. For the vscode vim extension, the list of modes can be found here.
stackexchange-vi
{ "answer_score": 3, "question_score": 2, "tags": "key bindings, vscode" }
Eclipse Stacktrace System.err problem All of a sudden my printStackTrace's stopped printing anything. When I give it a different output stream to print to it works (like e.printStackTrace(System.out)) but obviously I would like to get it figured out.
In your launch profile, on the common tab, check to make sure "Allocate console" is checked in the "Standard Input and Output" section.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, eclipse, error handling, printstacktrace" }
Click div to add padding to another div with jquery I am wondering if I can use jquery so that when I click on a fixed `div` it adds padding to another `div`. For the example below, I would like to add `40px` of padding to the top of `div2` once I click `div1`, and when clicked again I would like to revert to the original amount of padding `(20px)`. Here's a fiddle: < html: <div id="div1">The Pusher</div> <div id="div2">Push me down!</div> css: #div1{ position:fixed; background-color:red; color:white; width:100px; cursor:pointer; } #div2{ padding-top:20px; background-color:blue; color:white; width:100px } Thanks for your help!
Add this code in jquery $('#div1').on('click', function(){ var padding = $('#div2').css('padding-top'); var newPadding = (padding=='20px')?'40px':'20px'; $('#div2').css('padding-top',newPadding); }) **DEMO**
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -2, "tags": "javascript, jquery, html, css, onclick" }
Can I create a new partition from the free space inside my reiserfs-formatted /home partition? Ok, I have Ubuntu installed but I want to install Windows also (dual-boot). Problem is, I don't have a free partition. I have my root partition (15 GB), and my /home partition (300 GB). The home partition has about 50 GB free space, and it's formatted reiserfs. I've heard about tools like resize_reiserfs, and I even tried it yesterday - I shrunk my /home partition (it's on /dev/sda6) with the command: resize_reiserfs -s -20G /dev/sda6 After that gparted showed that the partition itself was 280 GB, but there was no way to create a new partition from the 20 GB. I ended up running resize_reiserfs -s +20G /dev/sda6 to restore my /home partition to its previous size.
`resize_reiserfs` shrinks the file-system only, not the partition itself. Quoting from here: > However shrinking a partition is probably more complicated: you should first use resize_reiserfs to shrink the filesystem (the on-disk data-structure) and then only use fdisk to shrink the partition (the space allocated on the disk). See here for an explanation. You can use gparted to combine both steps into one.
stackexchange-unix
{ "answer_score": 2, "question_score": 1, "tags": "filesystems, partition, size, reiserfs" }
Android maven dependency for API level 15 Is it possible to add dependency in my Android project with Maven support for API level 15 ? I have followed definition: <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>4.0.1.2</version> <scope>provided</scope> </dependency> where `4.0.1.2` is API level 14. next available is `4.1.1.4` which is API level 16.
I don't think you really need to downgrade to a previous api version via a dependency. Can't you just change the platform level in the **plugin config**? <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <configuration> <sdk> <platform>15</platform> </sdk> <undeployBeforeDeploy>true</undeployBeforeDeploy> </configuration> </plugin> And in **project.properties:** target=android-15
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, maven" }
Did BitGo terminate its "BitGO instant" service? Why? This is the launch announcement. < is a dead link now.
I can't say for sure, as I don't use the service, but the current page appears to be here: < . It's linked in the Solutions menu on the header of every page, so they're not hiding it.
stackexchange-bitcoin
{ "answer_score": 2, "question_score": 0, "tags": "bitgo" }
Which of the following statement is correct (concering integral)? I'm struggling figuring out how to tackle down this exercise. I don't know how to approach this question. I guess the answer needs to be $I > 0$, because D is alwasy greater or equal then 1. And because inside the integral all the variables are not related to A, so you can see them as constants. So a solution would be $A^2/2 + C$. But I have the feeling that this approach might be wrong. The exercise goes like this. Let $D=\\{(x,y) \in \mathbb{R}^2 |1 \leq x^2 +y^2 \leq3 \\}$ if $$I = \iint_D(|x+y|-x-y)dA$$ which of the following is true: $$I = 0$$ $$I > 0$$ $$I < 0$$ If you know the answer and would like to share it, it would be very much appreciated! Thanks in advance
$ \displaystyle I = \iint_D(|x+y|- (x+y)) \ dA$ $D=\\{(x,y) \in \mathbb{R}^2 |1 \leq x^2 +y^2 \leq3 \\}$ $D$ is region between two circles centered at the origin with radius $1$ and $\sqrt3$. Now in the given region, let's check the sign of the integrand $|x+y| - (x+y)$. Given the absolute term, it is simpler to check the sign in each quadrant separately. In first quadrant, $x, y \geq 0$ and so integrand is zero and so is the integral. In second quadrant, $x$ is negative and $y$ is positive. So we divide the region in two - i) when $y \geq |x|$, the integrand is zero. ii) when $y \leq |x|$, the integrand is $- 2(x+y)$, which is positive. So in second quadrant, integral is positive. Similarly, show that the integral is positive in quadrant $3$ and $4$ as well. So, $I \gt 0$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "calculus, definite integrals, education" }
How to remove horizontal scrollbar in dojo tree? Can someone please suggest me how can I remove the horizontal scroll-bar appearing at the bottom of the dojo tree structure ? I learnt there is a **.resize() function** in dojo which can help but exactly I don't know how to implement this in my tree structure to remove the horizontal scroll-bar.Can someone suggest me. Thanks and Regards
If your tree container has a fixed width, you could just use CSS to adjust it. Otherwise, you could manually resize your container like this, resize: function(d) { this.myContainer.resize(d); } If d is not of the proper size, you could use dojo getMarginBox(this.domNode) to get the size of your widget.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "dojo, dijit.tree" }
Postgres query issues I'm not sure why this structure is not working. This is my first time working with postgres and was hoping someone could help me. SELECT * FROM "friends" WHERE "from" = '1' OR "to" = '1' AND "status" = '1' It returns all values where from where "from" is = 1 and "to" = 1 rather than one or the other where "status" is = 1 I hope that isn't too confusing. Thanks.
OR operator has lower precedence than AND [[1]]( As a result, the expression is evaluated as follows: ( "from" = '1' ) OR ( "to" = '1' AND "status" = '1' ) What you probably want instead is: SELECT * FROM "friends" WHERE ("from" = '1' OR "to" = '1') AND "status" = '1'
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "postgresql" }
Setting default item in bound combobox I have an access form with a bound combobox, using a select query. When the form comes up, it is blank and the user has to select an item by clicking on the drop-down. The bound column is column 1 (ie the second column in the query). How can I get the combobox to display an initial value (hopefully the first record in the result set)?
You can set the Default Value for your unbound combo to one of the values of ImpTblDesc. Then the form should load with the matching combo row selected. If you want it to always be the first item in the combo's row source, instead of setting a fixed Default Value, you can use this at form load. Private Sub Form_Load() Me.cboNames = Me.cboNames.Column(1, 0) End Sub The Column property arguments are column Index, and Row. Both are zero-based. So that will refer to the second column (your "bound" column) in the first row.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ms access" }
Is it better to drive across a speed bump at a right angle or slightly skewed? I'm wondering if it is better for your suspension to drive across a speed bump at a right angle (so that the two front tires and the two rear tires hit the bump at the same time, respectively), or at a skewed angle so that only one tire at a time hits the bump? I've seen folks do both things and I'm wondering if there is a real significance to it or if it's just superstition.
Driving at a right angle will make the front and then the rear move further up and down than travelling over one wheel at a time, but that movement will be in one plane. Driving diagonally puts more stress on the chassis as it tries to twist first one corner then then next. The car will not move up and down so much, but will move sideways a lot more. So of the two options, the least stress on the car comes from driving straight.
stackexchange-mechanics
{ "answer_score": 15, "question_score": 13, "tags": "suspension" }
Distinct count of users with net balance > 0 My data looks like this. ![data and expected result]( I tried with below DAX but I am getting an error: Distinct Users = CALCULATE(DISTINCTCOUNT(MyList[User]),SUM(MyList[Balance]) > 0) > Error message: A function 'SUM' has been used in a True/False expression that is used as a table filter expression. This is not allowed.
You could do this by using a calculated column to evaluate the balance and then use that to calculate the measure: **Column:** Distinct Users Test = VAR User = MyList[User] RETURN CALCULATE(SUM(MyList[Balance]), FILTER(MyList,MyList[User]=User)) **Measure:** Distinct Users = CALCULATE(DISTINCTCOUNT(MyList[User]), MyList[Distinct Users Test]>0) Hope this helps. Edit: If you want it as a single measure, You can make use of summarize and calculatetable: Distinct Users New = COUNTX( CALCULATETABLE(SUMMARIZE(MyList,MyList[User], "Bal", SUM(MyList[Balance]))), [Bal]>0)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "powerbi, dax" }
mod_rewrite problem, with accessing files? i have this file that is on the root folder called sumbit.php and when i acesss a page like this for exmaple the new url is on firebug its saying its accessing ` when its meant to access ` my .htaccess code RewriteEngine On RewriteRule ^user/([^/]*)$ /viewprofile.php?user=$1 [L] RewriteRule ^topic/([^/]*)$ /viewtopic.php?topic=$1 [L] i dont seem to see what the problem is, p.s. the sumibit.php is from a form submit action
That's happening because the link to submit.php in your HTML is using relative paths. Relative paths depend on which directory you're currently in. So when you add slashes to your URL, it gets all messed up. You should fix your HTML to use absolute paths (`/submit.php`). If this is not possible, write a new rewrite rule that will map `^.*/submit.php$` to the correct path.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, url, .htaccess, mod rewrite" }
How do you install Boost on MacOS? How do you install Boost on MacOS? Right now I can't find bjam for the Mac.
Download MacPorts, and run the following command: sudo port install boost
stackexchange-stackoverflow
{ "answer_score": 163, "question_score": 204, "tags": "c++, macos, boost" }
How to get list of DNS servers for system resolver In Ruby I can get the list of DNS servers like this: require 'resolv' Resolv::DNS::Config.default_config_hash[:nameserver] How to do the same in Go?
The Resolver type in the `net` package lets you resolve DNS names but it doesn't seem to export the DNS servers it uses. Ruby parses `/etc/resolv.conf` so I guess you'll have to do that yourself or see if you can find a package that does it for you. _Update: I madea small library to do sort of the same as Ruby's DNS class. Hope it helps._
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "go" }
remove string element from javascript array can some one tell me how can i remove string element from an array i have google this and all i get is removing by index number my example : var myarray = ["xyz" , "abc" , "def"] ; var removeMe = "abc" ; myarray.remove(removeMe) ; consle.log(myarray) ; this is what i get from the console : Uncaught TypeError: Object xyz,abc,def has no method 'remove' ​ jsfiddle
From < Array.prototype.remove= function(){ var what, a= arguments, L= a.length, ax; while(L && this.length){ what= a[--L]; while((ax= this.indexOf(what))!= -1){ this.splice(ax, 1); } } return this; } var ary = ['three', 'seven', 'eleven']; ary.remove('seven') or, making it a global function: function removeA(arr){ var what, a= arguments, L= a.length, ax; while(L> 1 && arr.length){ what= a[--L]; while((ax= arr.indexOf(what))!= -1){ arr.splice(ax, 1); } } return arr; } var ary= ['three','seven','eleven']; removeA(ary,'seven') * * * You have to make a function yourself. You can either loop over the array and remove the element from there, or have this function do it for you. Either way, it is not a standard JS feature.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 11, "tags": "javascript, jquery, arrays" }
Logit transformation of target values in regression What sense would it make to logit transform a target variable that is a rate of something in a time series - Log(rate/1-rate). Does such a transformation have a theorethical purpose?
In what follows, I assume that the rate is bounded by 0 and 1. This would map the rate to the log odds space, wherein the argument (rate / (1-rate)) would not be constrained to the unit interval. This would permit using linear regression as opposed to Beta regression or logistic regression (though this benefit really only makes sense in the case where you don't have access to statistical software in my opinion).
stackexchange-stats
{ "answer_score": 2, "question_score": 0, "tags": "time series, logistic" }
Auto Updating Databinding I have a collection of objects (List) that is bound to a datagridview. How when I add or remove an object from the collection, can it refresh the datagridview without rebinding the control?
I also found the way I was thinking of in another question (This one to be specific)... guess I didn't search long enough. > The correct way is for the data-source to implement IBindingList, return true for SupportsChangeNotification, and issue ListChanged events. However, AFAIK, a DataView does this... by Marc Gravell
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, data binding, dataset" }
Check existence of a key in an array with multiple keys in Tcl Is there a way to check a key existence, in an array with multiple keys? i.e... set test_arr(n1_temp,x_cell) 3 #As you can see that `test_arr` contains two keys named `n1_temp` and `x_cell`, now I am wondering if I can check the existence of a key named `n1_temp` if {[info exists test_arr(n1_temp)] } { ## not working } Please help. -Regards, Shikha
> As you can see that test_arr cotains two keys named n1_temp and x_cell No, it has one key named `n1_temp,x_cell`. Use a `dict` instead, which supports actual multi dimensional structures: dict set test_dict n1_temp x_cell 3 if {[dict exists $test_dict n1_temp]} { # ... }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "arraylist, multidimensional array, tcl" }
PHP: Search multidimensional array => get array_keys What's the best/fastest way to get the keys of an array by a search of a value in the 2nd level arrays? $test = array( 'name_01' => array('yellow', 'red', 'blue', 'black', 'white', 'purple'), 'name_02' => array('red', 'blue', 'white', 'green'), 'name_03' => array('blue', 'pink', 'purple', 'blue'), 'name_04' => array('white', 'black', 'red'), 'name_05' => array('yellow', 'white', 'pink', 'black') ); For example the search by **pink** should return `array('name_03', 'name_05')`
A simple `foreach()` with `in_array()` is enough $search = 'pink'; foreach($test as $key=>$arr){ if(in_array($search,$arr)){ echo $key.PHP_EOL; } } Output : < _If you want array as an output :_ <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "php, arrays, multidimensional array, associative array" }
Entity Framework Query Nested Query I am new to the entity framework and am trying to convert the following query into the correct function calls. Select Distinct a.nodeId FROM (SELECT * FROM reportContents Where fitId = '29' and reportId = (select max(reportId) from reportContents where fitId = '29') ) a Where (a.nodeId IS NOT NULL) I know this query does what i want, however i'm not sure how to translate that into the entitiy framework! Here was my attempt. var prevSelectedNodes = db.reportContents.Where( f => f.fitId == id).Select( f => f.nodeId).Distinct().ToList(); I need to somehow put a .Select() in the where call. However that kind of thing dosen't seem possible Thank you in advance!
As you can't make two LINQ nested lambda expression. You can do it with two requests : var maxReportId = db.reportContents.Where(r => r.fitId = "29").Max(r => r.RepordId); var result = db.reportContents.Where(r => r.fitId == "29" && r.reportId == maxReportId && r.nodeId != null).Select(a => a.nodeId).Distinct().ToList() ;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, sql, entity framework" }
Decrease vertical thicknes of bars in Likert Chart R I making graph in R. I amusing likert chart. I want to decrease vertical thickness of bars. Does anyone have any idea. How to do that. Following is my script. require(likert) require(HH) Q2 <- c(11.76, 11.76, 17.65, 47.06, 11.76) Q3 <- c(0, 17.65, 23.53, 23.53, 35.29) Q4 <- c(5.88, 35.29, 23.53, 29.41, 5.88) Q <- data.frame(Q2, Q3, Q4) Q <- t(Q) PCWP <- c("#A8C2C0", "#C9E9E6", "#AAFFBB","#D0E39A", "#A3B37B") colnames(Q) <- c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly Agree") items <- list(c("Q2", "Q3", "Q4")) likert( Q, col=PCWP, main="projects", xlab="Percentage", ylab="Question", par.settings= list( layout.widths=list(axis.right=1, axis.key.padding=0, ylab.right=1, right.padding=1) ) ) Thanks!
See `?likert` (from `HH`). Use the `box.ratio` argument: likert( Q, col=PCWP, main="projects", xlab="Percentage", ylab="Question", box.ratio=0.5, par.settings= list( layout.widths=list(axis.right=1, axis.key.padding=0, ylab.right=1, right.padding=1) ) )
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "r, data visualization" }
Link print setting to a PDF document I have a PDF document and I want to know if there is a way that I can embed print setting into it - such as Page sizing to Actual size and print on both sides. So when people print the PDF they don't need to change the print settings manually.
Parts of this can be done with the "Viewer Preferences" dictionary (see PDF 1.7 specification section 12.2 for details): * PrintArea * PrintClip * PrintScaling * Duplex * PickTrayByPDFSize * PrintPageRange * NumCopies However, as usual this depends on the PDF viewer actually using these options. So you might wanna try this out with the PDF viewers your clients use.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "pdf, printing" }
How to define a field with a parameterized List using Javassist How can I define a parameterized List field using Javassist? I have tried the following code which does not complain with an unparameterized List class, but causes a CannotCompileException when given a parameter. ClassPool pool = ClassPool.getDefault(); pool.importPackage("java.util.List"); CtClass cc = pool.makeClass("Test"); CtField f = CtField.make("public List<String> p;", cc); // throws javassist.CannotCompileException: [source error] syntax error near "lic List<String> p;"
I'd guess the language compliance level of the compiler javassist is using internally is set to Java 1.4, which would explain why it doesn't understand generics (they were introduced in 1.4)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "java, javassist" }
Помогите разобраться с WPF binding В разметке указываю <Window /*xmlns definition*/ Width={Binding ElementName=W, Path=Text}> <Grid> <TextBox Name="W"> </Grid> </Window> Но при изменении значения в TextBox, ширина окна не изменяется. Никогда не работал с WPF, Видимо, чего-то не понимаю. Помогите разобраться.
Надо указать Mode=TwoWay <Window x:Class="WpfApplication1.MainWindow" xmlns=" xmlns:x=" Title="Window" Height="300" Width="{Binding ElementName=W, Path=Text, Mode=TwoWay}"> <Grid> <TextBox Name="W" Text="300" /> </Grid>
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "wpf, binding" }
configure MSMQ cluster failover on an azure vm (windows server 2016) I want to create a Failover cluster for MSMQ for two vm's in azure. I created two VM's in azure and have them domain joined. I can create the failover cluster with both nodes. However when i try to add a role for MSMQ i need an cluster shared disk. I tried to create a new managed disk in azure and attach it to the vm's but it still wasn't able to find the disk. Also tried fileshare-sync, but still not working. I found out i need iSCSI disk, there was this article < . But it is end of life next year. So i am wondering if it is possible to setup a failover cluster for msmq on azure and if so how can i do it? Kind regards,
You should be able to create a Cluster Shared Volume using Storage Spaces Direct across a cluster of Azure VMs. Here are instructions for a SQL failover cluster. I assume this should work for MSMQ, but I haven't set up MSMQ in over 10 years and I don't' know if requirements are different.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "windows, azure, msmq" }
How do I access a variable in a one C file from another? I have two C files. I want to declare a variable in one, then be able to access it from another C file. My definition of the _example_ string might not be perfect, but you get the idea. //file1.c char *hello="hello"; * * * //file2.c printf("%s",hello);
// file1.h #ifndef FILE1_H #define FILE1_H extern char* hello; #endif // file1.c // as before // file2.c #include "file1.h" // the rest as before
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "c, file, variables" }
Handsontable: ReadOnly-Cells not working I am so new to HOT, I've not even started using it! I'm just trying to go through the examples to see if I might be able to use it as a grid-control in my app. But when I look at examples like this one, it doesn't behave as readonly: I am able to overwrite every cell in the "Nissan"-Example as well as selecting the whole table and press `<Del>`. Does the "readonly" only imply that no data will be changed in the returned object or is me being able to edit everything considered a bug?
After asking support, it turned out this was unintended behaviour and will be fixed. Problem was only in the way the demo was coded - it was not adjusted to latest changes in HOT.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "handsontable, readonly attribute" }
MS Access 2007 renaming shortcuts in custom groups to change the names of the objects In Access 2007 I create a lot of custom groups to organise the large number of queries and tables in a single database. There are lots of individual sub queries that link up to larger queries. In development, I find it necessary to frequently rename some of the queries permanently after they have been added to a custom group. But Access only renames the shortcut that is in the group and not the actual object. This causes broken references. So I now have to remove an object from the group, rename it, then add back to the group. This adds further problems if you have lots of queries and tables. Is there any way to configure Access to rename the actual object and not just the shortcut from within a custom group? Thanks
Unfortunately, you cannot do this in Access. That's the idea of _shortcuts_. Actually, it is the same as in Windows (you can rename the shortcut but the object itself stays intact).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ms access, ms access 2007, grouping, shortcut" }
Двусвязный список на java public class Node { private int element; private Node next; public int getElement(){ return element; } public void setElement(int e){ element = e; } public Node getNext() { return next; } public void setNext(Node n) { next = n; } }
1. Читать матчасть тут. Структуры данных в картинках. LinkedList. 2. Смотреть исходник, т.е. ваше задание тут. LinkedList.java.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java" }
knife bootstrap ip-10-185-211-254.ec2.internal -x ubuntu -i JP_Key.pem —sudo -r “role[webserver]” I have created a cookbook and signed a role. When I do knife bootstrap ip-10-185-211-254.ec2.internal -x ubuntu -i JP_Key.pem —sudo -r "role[webserver]" I'm getting the following error: ERROR: Network Error: getaddrinfo: Temporary failure in name resolution Check your knife configuration and network settings Do I need to add the access key and secret key in `knife.rb`?
The error hints at the reason, that the IP of the server name you gave (`ip-10-185-211-254.ec2.internal`) couldn't be resolved by your local DNS resolver. This is probably because you tried to use the internal hostname and IP of your EC2 VM which is not accessible from outside of the EC2 internal network. You should use the external IP and hostname instead.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "amazon ec2, chef infra, knife, cookbook" }
Default attribute is nil for Chef Apache2 cookbook I'm trying to provision an Ubuntu 13.04 box with Chef-solo (11.4.4), however the apache2 cookbook gives an error: undefined method `[]' for nil:NilClass 20: package "apache2" do 21>> package_name node['apache']['package'] 22: end My guess is that the default attributes for the cookbook are not loaded, i.e. node['apache'] is nil, but I have no clue how to solve this... case platform when "debian", "ubuntu" default['apache']['package'] = "apache2" I know there have been some changes to Chef v11 regarding attributes and previously with Chef v10 it simply works, but I don't have enough Chef knowledge to know what to change. Any help is appreciated!
Apparently, in Chef 11, cookbooks need a `metadata.rb` in which dependencies are specified. These dependencies are used to autoload cookbooks. Adding `depends "apache2"` to the `metadata.rb` file solves the above problem.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "apache, chef infra, cookbook" }
Is *Lacks sufficient information* really a close reason? There are many questions which lack sufficient information to be answered. However, this can be remedied by asking the OP to add data/information/log/code. All that information should be included in the original post, but I feel that marking for closure for that reason does not work. I find it is a complex/long/difficult/obscure process to close a question for lack of information, then get the user to edit it, then open it again, all that with the question having had a bunch of downvotes in the process, and it is not a surprise the users create new questions instead. But may be it is also a protection against users who will not make any effort.
# Questions aren't reopened That's because they aren't improved. If instead the new user creates a new question (obviously prohibited, if they bother read the FAQ linked everywhere), it will (rightfully) be received poorly and may lead to a question-ban (hooray). # But 10 people must be involved… So? There's no backlog on the reopen queue, questions are improved so rarely. # So, people aren't being told to edit No. The close reason and FAQ tell users to edit. Also, common sense.
stackexchange-meta_stackoverflow
{ "answer_score": 2, "question_score": -16, "tags": "discussion, close reasons" }
Is it possible to download a bash script and execute it from a preseed file? I'd like to prepare an iso for unattended installation. So I generated a preeseed file to run through the installer automatically. Is it possible to download a bash script with `wget` and run it with bash directly in the first user's homedir (where the first user is the user account created by the installer)? What would the commands in the preseed file look like?
Here is how: d-i preseed/late_command string in-target wget -P /tmp/ $server/script.sh; in-target chmod $+x /tmp/script.sh; in-target /tmp/script.sh` Put this line into a preseed file and you can do everything in your system you are familiar with bash. You have to replace `$server` with a webhost or a local ip of course.
stackexchange-askubuntu
{ "answer_score": 12, "question_score": 11, "tags": "system installation, debconf, debian installer" }
will I get android updates on Moto G after Cyanogenmod 11 I'm about to flash Cynogenmod 11 on my Moto G XT1033. I was wondering that, will I still get android OTA updates even after installing CM11? If anyone have an answer then please tell me.
CyanogenMod has its own OTA Updater. You will not get the official Android updates, but the CM updates.
stackexchange-android
{ "answer_score": 6, "question_score": 1, "tags": "cyanogenmod, ota update, android versions, motorola moto g" }
Ring with Z as its group of units? Is there a ring with $\mathbb{Z}$ as its group of units? More generally, does anyone know of a sufficient condition for a group to be the group of units for some ring?
The example provided by Noam answers the first question. The second question is very old and, indeed, too general. See e.g. the notes to Chapter XVIII (page 324) of the book "László Fuchs: Pure and applied mathematics, Volume 2; Volume 36". In particular, rings with cyclic groups of units have been studied by RW Gilmer [Finite rings having a cyclic multiplicative group of units, Amer. J. Math 85 (1963), 447-452], by K. E. Eldridge, I. Fischer [D.C.C. rings with a cyclic group of units, Duke Math. J. 34 (1967), 243-248] and by KR Pearson and JE Schneider [J. Algebra 16 (1970) 243-251].
stackexchange-mathoverflow_net_7z
{ "answer_score": 18, "question_score": 19, "tags": "ra.rings and algebras, gr.group theory" }
How to test that a Jar is in a classpath in windows? I have the classic : java.lang.NoClassDefFoundError: org/python/util/jython Even if the jar jython.jar exist in the environment variable PATH for my user **and** system wide path. How can I quickly test that I am not crazy and it is indeed in the path?
Java doesn't use the `PATH` variable. To specify the classpath when running a java application use the `-cp` parameter for the `java` command. Inside your batch file (the .cmd file) find the `java` command and add the needed jar file: java -cp somefile.jar;\path\to\jython.jar someclass.MainMethod Please don't use the deprecated `CLASSPATH` any more. For more details, please see the Java documentation: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, windows, classpath" }
Meaning difference between 夜は明ける and 夜が明ける? In this song lyrics, is the name of the song, but until the end of the song is used. This sounds like there is a distinct meaning difference between the two forms. I read about the difference between and , but I could not understand it in this concept.
**** is so-called "a neutral description" or ; basically it's a vivid description of the event this person is currently experiencing. On the other hand, **** is a description of a fact which is "known" to the speaker. Therefore is more like "(I'm seeing) this night is dawning", whereas is more like "Nights (always) dawn". See the following articles: * Can someone explain me the use of and in this sentence? * Why does sound more adversarial than ?
stackexchange-japanese
{ "answer_score": 3, "question_score": 2, "tags": "meaning, word choice" }
c# Unicode Null Representation code character array I am creating a character array.Is there a unicode code for null? For example if I need to put a null in the character array?And also when I use the unicode table < which is the code I should use since there is HTML-code,Unicode number... I'm confused. char[] specialSymb= new char[] { ' ', ',', '.','?','!'};
According to Microsoft's documentation on Character literals (Which is what you are asking for) these are the following types of **null** encoding: **Escape sequence** \0 **Unicode encoding** 0x0000 EDIT: **For HTML Unicodes** %00 or &#0; Source: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, unicode" }
CompletableFuture from Callable? Today I experimented with the "new" `CompletableFuture` from Java 8 and found myself confused when I didn't find a `runAsync(Callable)` method. I can do it myself like shown below, but why is this (to me very obvious and useful utility method) missing? Am _I_ missing something? public static <T> CompletableFuture<T> asFuture(Callable<? extends T> callable, Executor executor) { CompletableFuture<T> future = new CompletableFuture<>(); executor.execute(() -> { try { future.complete(callable.call()); } catch (Throwable t) { future.completeExceptionally(t); } }); return future; }
You are supposed to use `supplyAsync(Supplier<U>)` In general, lambdas and checked exceptions do not work very well together, and `CompletableFuture` avoids checked exceptions by design. Though in your case it should be no problem.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 26, "tags": "java, concurrency, java 8, java.util.concurrent" }
Golang auto completion nsf package I have installed sublime and go. Tried the autocompletion feature offered by < It works perfectly for standard packages. But not working for external packages like the ones fetched from github. Any help on this appreciated. Thanks.
It will only work if you build and install those external packages. if you just `go get` their sources, the completion won't work, even said sources are in the `GOPATH/src/...`. Those packages need to be at least compiled (`GOPATH/pkg`). As mentioned in "How does Go update third-party packages?", a `go get -u all` can help.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "autocomplete, go" }
How to include source instead of a library in C# / Visual Studio? I come from a long Java background and very new to C#. I was trying to run one of the starter kit applications from Windows phone and I am getting this error. A first chance exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.WindowsPhone.dll I am finding it hard to debug this because I am directly referring to the dll file under References pointing to Newtonsoft.Json.WindowsPhone. In Java, I would have searched for the library and downloaded the source to step into the exact location during debugging. If that is possible, how would I do it in C# (as in how would i refer the library source for my project to pick up at run-time)? I am using the Visual studio 2010 Express Edition as the IDE.
1. Download the third party library you are dealing with 2. Add this library's project into your solution 3. In your project, remove the reference to the 3rd party library 4. Add a project dependency into your project, make it depend on the 3rd party library project you have just added to your solution 5. Compile and run, happy debugging
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "c#, json, windows phone 7, json.net" }
File deleted from App Bundle in Xcode still readable I have a bunch of Audio Files in my App Bundle, I was reading using [[NSBundle mainBundle] pathForResource:aaa ofType:m4a] I found that even if I delete the aaa.m4a by moving to trash my app is can read and play the audio file (using AVAudioPlayer). I checked by search in the Xcode project's directory, that it doesn't exist. I checked also from Build Phrases - Copy Bundle Resources, that aaa.m4a is not there. Anybody has any ideas why?
File is kept somewhere during build & run process. * In Xcode Go to Organizer > Projects > Your project > Remove Derived Data * On your device Delete app Run on device and you should be fine.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ios, xcode, nsbundle" }
Access Angular variable within script tag I am making a web app:front-end in Angular and backend in Rails. I am using LinkedIn's member profile plugin which shows person's profile based on URL being passed. Here is the code for this plugin. <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="IN/MemberProfile" data-id="(Your LinkedIn URL)" data-format="inline" data-related="false"></script> I want to make data-id part dynamic. Basically, I will let my users to write their linkedin address in text box and save it to Angular's variable. When the value changes, I want that value gets assigned to `data-id`. But I'm not sure whether `data-id` can access a variable in Angular.
Quite simple. Create your app along with a global controller that will be initialised on your `html` tag like so: <html ng-app="app" ng-controller="myctrl"> <head> <script type="IN/MemberProfile" data-id="{{myId}}" data-format="inline" data-related="false"></script> </head> </html> And have this as your controller and app initialisation, or something similar: var app = angular.module('app', []); app.controller('myctrl', ['$scope', function($scope){ $scope.myId = 123; }]); To break it down, `$scope.myId` will be assigned the LinkedIn ID, and it is output on the page inside the `head` tag (I'm guessing that's where you want it) within the `data-id` attribute on the `script` tag. **WORKING EXAMPLE**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, ruby on rails, angularjs" }
How to redirect Kentico to CMS admin page by default We're using Kentico 11 along with a single MVC website, both hosted as Azure app services. Our company's URL looks like www.mycorp.com and Kentico CMS URL looks like kentico.mycorp.com When someone goes to kentico.mycorp.com, it shows a blank page. We need to type kentico.mycorp.com/admin to get to the CMS. Is there a way a redirect can be set up without adding any new DNS entry or a web app in IIS?
Try the following in your CMS web.config: <configuration> .. <system.webServer> <rewrite> <rules> <rule name="AdminRedirect" stopProcessing="true"> <match url="^$" /> <action type="Redirect" url="/admin" /> </rule> </rules> </rewrite> </system.webServer> .. </configuration>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "kentico, kentico mvc" }
How to explain the equation? Confusion about the notation "gcd$(a,b)$" We know that the greatest common divisor (GCD) of a and b is generally denoted gcd$(a, b)$ or $(a,b)$. However in **integral domains** , the greatest common divisor is often not unique. So what does the notation "$(a,b)$" stand for in this case? For example, look at the following equation (from here): > **the GCD Distributive Law** $ (ax,bx)=(a,b)x $ Is "$(a,b)$" an arbitrary gcd of a and b? If so, it is difficult to interpret the equal sign "$=$". If "$(a,b)$" represents all the gcds of a and b, which means $(a,b)$ is a set, it is hard to interpret the multiplication “$(a,b)x$”. So I am confused. Could anyone clarify this? Thanks!
It means that every greatest common divisor of $ax$ and $bx$ can be written as greatest common divisor of $a$ and $b$ times $x$ and also that if you multiply a greatest common divisor of $a$ and $b$ by $x$, then what you get is a greatest common divisor of $ax$ and $bx$.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "abstract algebra, gcd and lcm, integral domain" }
importance of IDE when developing enterprise application what is the importance of the IDE(Integrated development environment) when we develop enterprise applications. Thank in advance!
An IDE brings together a number of different applications that are needed for rapid development, some IDEs provide more facilities than others. * Text/Code editor * Compiler integration * Debugger integration * Code completion/snippets * GUI editor * Test suite integration * Source control integration This is important not only for enterprise application development, but is useful for a single developer as well.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "visual studio, ide, netbeans" }
How can I build a shared library that will be used for different g++ version? I want to compile a shared library to other developers, but without shipping source code. The .so file I built against g++ 4.6, but they used g++ 4.4. When they linked with my .so file, g++ reported: undefined reference to 'memcpy@GLIBC_2.14'. I think there are two possible solutions: 1. I rebuild my shared library which do not depends on specified GLIBC version. 2. Tell them a simple way to link with my shared library with some compiler options to make it work. I have no idea in both methods, how can I achieve these solutions or one of them? Thanks. **Edit:** I found a link flag: -static-libgcc Does that help if I build my shared library with this option? Any drawback?
Finally, I add these options to make it without depends on any shared libraries. -static-libgcc -static-libstdc++ -nodefaultlibs -shared -fPIC The ldd reports 'static linked', and no any required .so files. This might be useful for anyone who want to ship portable shared library.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "g++, version, shared, glibc" }
How do I know if I will get an HWND when embedding an ActiveX control in HTML? I have a simple ATL ActiveX Control, implemented in C++. If I embed the control in a web page with something like: <object id="api" classid="CLSID:<guid here>" height=400 width=800></object> I know I can get an HWND from the control in `m_hWnd` if I set `m_bWindowOnly = true;` in my coclass constructor. This works ok. If I were to try to instantiate this ActiveX control from Javascript, the process looks like: var object = new ActiveXObject("registeredControlString"); But I don't get an HWND, and I am not sure how I might insert this into the DOM. My Question: In what situations will I get an HWND that I can reference from the control?
You won't get hwnd by constructing from new ActiveXObject since your CComControl::CreateControlWindow() is only called during in-place activation, and javascript simply does not have the type system to support the COM interfaces required for in-place activation. If your control is going to be used as a UI-less COM server (like here in your script) design your ActiveX to work without a window handle.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c++, visual c++, atl, win32ole" }
Oracle PL/SQL block succeeds with hard coded value but not with variable The following PL/SQL successfully executes as expected: declare myCount number; begin select count(*) into myCount from myTable where id = 1; end; However, the following does not and instead throws this error: > ORA-01422: exact fetch returns more than requested number of rows declare myCount number; myId number := 1; begin select count(*) into myCount from myTable where id = myId; end; Conceptually, I understand what the error means, but I don't know how it applies to my situation. All I've done is moved the hardcoded value to a variable in the `declare` block. Why would that affect the results of the `select` when it's the exact same number? Version is `Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production`.
There is something going on in your system that you haven't reproduced in this question. If I create a table `myTable` in my local system, your code runs without error SQL> create table myTable( id number ); Table created. SQL> declare 2 myCount number; 3 myId number := 1; 4 begin 5 select count(*) 6 into myCount 7 from myTable 8 where id = myId; 9 end; 10 / PL/SQL procedure successfully completed. Is it possible that there is some difference between the code you've posted and the code that you're actually running?
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "oracle, plsql" }
2 cluster of zookeper servers in hadoop+kafka cluster - is it posible? We have Kafka cluster with the following details 3 kafka machines 3 zookeeper servers We also have Hadoop cluster that includes datanode machines And all application are using the zookeeper servers, including the kafka machines Now We want to do the following changes We want to add additional 3 zookeeper servers that will be in a separate cluster And only kafka machine will use this additional zookeeper servers **Is it possible ?**
Editing the `ha.zookeeper.quorum` in Hadoop configurations to be separate from `zookeeper.connect` in Kafka configurations, such that you have two individual Zookeeper clusters, can be achieved, yes. However, I don't think Ambari or Cloudera Manager, for example, allow you to view or configure more than one Zookeeper cluster at a time.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache kafka, apache zookeeper" }
Adding to Cart with Querystring - Takes me to homepage? I'm trying to add a product to my cart via query string based on the information on the Magento website. I've tried the following: * /checkout/cart/add/product/3887/1/ * /checkout/cart/add/product/3887/1/e8JDefUuLcGdLE1Q (Added Form Key) * /checkout/cart/add?product=3887&qty=1 The Product ID here is 3887 and it's a Simple product, with no special or custom options. I'm trying to send it through Ajax but it doesn't get put in the cart and then when I attempt to enter the URL directly I just get redirected to the homepage. I'm getting the Product ID from a custom page where customers will be able to enter a list of SKU's into 10 input boxes (Quickshop page) Thanks in advance! **SOLUTION for others:** URL **must** follow this: /checkout/cart/add/product/PRODUCTID/qty/NUMBER/form_key/WSFiE69HmvU854G2
The url for adding needs to include a form_key. /checkout/cart/add/product/554/form_key/QOTCSV8HqoLA0K3T/
stackexchange-magento
{ "answer_score": 3, "question_score": 0, "tags": "magento 1.8, cart, php, query" }
I push my project to gitlab to test git ci,but it built fail These are my information of error Running with gitlab-ci-multi-runner 1.5.3 (fb49c47) Using Shell executor... Running on luckyxmobiledeMac-mini-2.local... Fetching changes... HEAD is now at e56d7ac Update README.md Checking out e56d7ace as master... bash: line 4: shell_session_update: command not found ERROR: Build failed: exit status 127 These are content of my .gitlab-ci.yml:= stages: - build build_project: stage: build script: - xcodebuild clean -project ProjectName.xcodeproj -scheme SchemeName | xcpretty - xcodebuild test -project ProjectName.xcodeproj -scheme SchemeName -destination 'platform=iOS Simulator,name=iPhone 6s,OS=9.2' | xcpretty -s tags: - ios_9-2 - osx_10-11
Based on this question on Super User, this seems to be an issue with the `rvm` package on the server. You can go read that question and answer for a full explanation of what the issue is, but their solution is to update `rvm` to version 1.26.11 or greater. To update to the most recent stable version do this: rvm get stable
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "git, gitlab, gitlab ci runner" }
Copying a pointer I'm sending some data through the network from the client <> server. I'm reading a packet without any issues, though I can not copy a `SimpleTestPacket` pointer for some reason. I have tried using `memset` where I am getting a segmentation fault. Code: typedef struct simpleTestPacket_t { uint32_t type; uint8_t point; int32_t value; } SimpleTestPacket; void onReceivePacket(uint8_t header, const char* data, size_t count) { const SimpleTestPacket* packet = reinterpret_cast<const SimpleTestPacket*> (data); SimpleTestPacket* independentPacket = nullptr; memset(independentPacket, packet, sizeof(SimpleTestPacket) * count); } How can I copy the `packet` pointer to the `independentPacket` variable so I could store it for a later-use? Would it be possible to make a copy without allocating a `new` memory which I would have to `delete` later?
Just drop the unnecessary pointer business, make a local copy and deal with that: const SimpleTestPacket* packet = reinterpret_cast<const SimpleTestPacket*> (data); auto independentPacket = *packet; Now `independentPacket` is a local copy of `packet` with automatic storage duration.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "c++, c++11, pointers" }
php script that deletes itself after completion There's a problem that I'm currently investigating: after a coworker left, one night some files that he created, basicly all his work on a completed project that the boss hasn't payed him for, got deleted. From what I know all access credentials have been changed. Is it possible to do this by setting up a file to do the deletion task and then delete the file in question? Or something similar that would change the code after the task has been done? Is this untraceable? (i'm thinking he could have cleverly disguised the request as a normal request, and i have skimmed through the code base and through the raw access logs and found nothing).
It's impossible to tell whether this is what actually happened or not, but setting up a mechanism that deletes files is trivial. This works for me: <? // index.php unlink("index.php"); it would be a piece of cake to set up a script that, if given a certain GET variable for example, would delete itself and a number of other files. Except for the server access logs, I'm not aware of a way to trace this - however, depending on your OS and file system, an undelete utility may be able to recover the files. It has already been said in the comments how to prevent this - using centralized source control, and backups. (And of course paying your developers - although this kind of stuff can happen to anyone.)
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "php, file io" }
vsubst in batch file In my office they every day double click on the program vsubst to assign a partition of the space on the computer as a drive. I want to make a batch file out of it so they do not have to do this every day. It takes 5 seconds, but 5 people times 5 seconds times 250 working days is 6250 seconds a year! Can anyone help me out here? This shouldnt be to difficult. I run a windows machine and could put it in the windows task manager. I guess its something like: Start ....vsubst.exe param param1
Ok. Trial and error got me there. Fill the following line in and place the batch file in your startup programs and you're done :D start path\VSubst.exe NEWDRIVE FOLDERPATH exit
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "windows, batch file" }
Loop to sum observation of a time serie in R I'm sure this is very obvious but i'm a begginer in R and i spent a good part of the afternoon trying to solve this... I'm trying to create a loop to sum observation in my time serie in steps of five. for example : input: 1 2 3 4 5 5 6 6 7 4 5 5 4 4 5 6 5 6 4 4 output: 15 28 23 25 My time serie as only one variable, and 7825 obserbations. The finality of the loop is to calculate the weekly realized volatility. My observations are squared returns. Once i'll have my loop, i'll be able to extract the square root and have my weekly realized volatility. Thank you very much in advance for any help you can provide. H.
We can create a grouping variable with `gl` and use that to get the `sum` in `tapply` tapply(input, as.integer(gl(length(input), 5, length(input))), FUN = sum, na.rm = TRUE) # 1 2 3 4 # 15 28 23 25 ### data input <- scan(text = "1 2 3 4 5 5 6 6 7 4 5 5 4 4 5 6 5 6 4 4", what = numeric())
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "r, loops, time series, regression, finance" }
Is this Python code thread safe? import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count = 0 def run(self): while self.count<9: self.work() def skip(self): self.doSkip = True def work(self): self.count+=1 time.sleep(1) if(self.doSkip): print "skipped" self.doSkip = False return print self.count t = test() t.start() while t.count<9: time.sleep(2) t.skip()
Thread-safe in which way? I don't see any part you might want to protect here. skip may reset the `doSkip` at any time, so there's not much point in locking it. You don't have any resources that are accessed at the same time - so IMHO nothing can be corrupted / unsafe in this code. The only part that might run differently depending on locking / counting is how many "skip"s do you expect on every call to `.skip()`. If you want to ensure that every skip results in a skipped call to `.work()`, you should change `doSkip` into a counter that is protected by a lock on both increment and compare/decrement. Currently one thread might turn `doSkip` on after the check, but before the `doSkip` reset. It doesn't matter in this example, but in some real situation (with more code) it might make a difference.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, multithreading" }
Selenium get elements by location I'm trying to perform a click into an element using SeleniumQuery but every time that I execute the click it says that there is another element at the same location. Is there any way to get all the elements that are at the same location?
I never saw any case like this, but I would check if the `element is clickable`(Selenium WebDriver - determine if element is clickable (i.e. not obscured by dojo modal lightbox)) and do the click on the one that is indeed clickable. So, get the two elements and click the one that is clickable
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "selenium, testing, selenium webdriver, automated tests" }
PNGs on a plane I am trying to make a chain link fence using planes and a .png image as the texture, I am importing the whole environment from blender however this problem keeps on appearing, the plane gets the .png file and you can see through the fence only on one side, if you turn to the other side then the plane disappears completely. However this doesn't happen in blender when I render the image. I have tried importing the .blend file to unity and using an .fbx file however it still appears that way. Any idea on how to fix this problem?
I think you actually mean a quad. A quad consists of 2 triangles, even if blender doesnt show that. A triangle - and with that - a quad, has a normal. Consider it to be the front of the quad. Usually, we dont draw the back of a quad because we don't need to. Rendering is roughly twice as fast when we dont draw the triangles that face the other way, and you usually dont see that we cull them, because they're normally occluded by other triangles. In this case, it is a little more difficult. We need to duplicate the quad, and make the copy face the other way. In blender, select your quad (or plane, if you want to keep calling it that). Shift-d to duplicate the vertices. Just move it slightly away to the side that you cant see in the other program. Press w. Click flip normals. Save and export. Im not sure if this is what the problem is but it sounds like it.
stackexchange-gamedev
{ "answer_score": 1, "question_score": 0, "tags": "materials, importing" }
How can I use regex to split a string by {} var string = '{user: Jack}{user: Dave}{user: John}{user: Hou}'; How can I use regex to split this string and save the result in an array like ['{user: Jack}','{user: Dave}','{user: John}','{user: Hou}'] ?
You can use that expression as param of the String.prototype.match() method. \{(.*?)\} This will make a thing like that: var str = '{user: Jack}{user: Dave}{user: John}{user: Hou}'; var res = str.match(/\{(.*?)\}/g); It will give you an array like you want it. If you have to use regex a lot, you can use this cool regex tester: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "javascript, regex" }
Email server: Remove rua from DMARC DNS entry or stop receiving DMARC reports I have the following DNS entry for one of my clients email servers: _dmarc IN TXT "v=DMARC1; p=none; rua=mailto:[email protected]" This is the only email server I'm administering, which has a DMARC DNS entry - in other cases SPF and DKIM was always sufficient for the email server to work fine. The annoying thing is that I receive multiple DMARC reports from Gmail, Yahoo, etc. ervery day and I don't need them. How can I stop receiving those DMARC reports? Should I just remove the `rua` part of the DNS entry?
Sure. Just remove it. "rua" is optional as per RFC. <
stackexchange-serverfault
{ "answer_score": 5, "question_score": 4, "tags": "email, email server, dmarc" }
配列の中にオブジェクト型が入っているインスタンス変数をWhere句で得られる結果と同じオブジェクト型に変換する方法は? PostWherePostPost @posts.where(state: 'published') pry> @posts => [#<Post id: 12, name: "1st post" state: "published", user_id: 4, created_at: "2015-06-05 08:03:09", updated_at: "2015-06-05 12:41:53">, #<Post id: 23, name: "14th post" state: "published", user_id: 3, created_at: "2015-06-15 18:30:08", updated_at: "2015-06-15 18:30:08">] pry> @posts.class => Post::ActiveRecord_Relation Post (@instance)Post pry> @instance => [#<Post id: 12, name: "1st post" state: "published", user_id: 4, created_at: "2015-06-05 08:03:09", updated_at: "2015-06-05 12:41:53">, #<Post id: 23, name: "14th post" state: "published", user_id: 3, created_at: "2015-06-15 18:30:08", updated_at: "2015-06-15 18:30:08">] pry> @instance.class => Array Post `NoMethodError - undefined method 'search' for #<Array:` Post
instance @posts = Post.where(state: 'published') @instance = @posts.to_a `@posts` Post.where(id: @instance) idDB
stackexchange-ja_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, ruby, rails activerecord" }
how to open a link field in new window in view In views,for image field, I have selected "output this field as link" and in link path, I wrote "node/[nid]". Link works and open in same window. How to open the link in a new window? I dont see any option in view. Thanks
1) Click your image field at your views 2) Click Rewrite results. Check Output this field as a link. Key in your URL in the Link Path ![enter image description here]( ) 3) At Target text field, key in this "_blank" !enter image description here
stackexchange-drupal
{ "answer_score": 3, "question_score": 1, "tags": "views" }
How can I read any CSV files in a folder and merge into the one CSV file I have a folder labeled ' **input** ' with multiple CSV files in it. They all have the same columns names but the data is different in each CSV file. How can I use Spark and Java to go to the folder labeled 'input', read all the CSV files in that folder, and merge those CSV files into one file. The files in the folder may change, e.g. might have 4 CSV files and another day have 6 and so on so forth. Dataset<Row> df = ( spark.read() .format("com.databricks.spark.csv") .option("header", "true") .load("/Users/input/*.csv") ); However, I don't get an output, Spark just shuts down. I don't want to list all the CSV files in the folder, I want the code to take any CSV files present in that folder and merge. Is this possible? From there I can use that one CSV file to convert into a data frame.
In your example, you may have used an older version of the data source. The new datasource ("csv") may work better: Dataset<Row> df = spark.read() .format("csv") .option("header", true) .load("/Users/input/*.csv"); df.show(); should work. You can find a complete example there: < and with multiple files there: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "java, dataframe, csv, apache spark" }
Input field text is white on white in some apps on OnePlus One After upgrading to Android 6 on an unrooted OnePlus One, some apps (eg. Aqua Mail, aCalendar) have their input fields nearly white text on white background. How can I change the color?
Changing to another theme in settings -> themes did the trick
stackexchange-android
{ "answer_score": 0, "question_score": 0, "tags": "6.0 marshmallow, oneplus one, text input, color" }
Unity3d - Attach to Unity not working I need to debug my scripts, but if I click "Attach to Unity" or "Attach to Unity and Play" then the button is just grayed out and after a few seconds it is clickable again, but nothing happens. ![Attach to Unity and Play \(green arrow\)]( ![Attach to Unity and Play \(gray arrow\)]( ![Attach to Unity and Play \(green arrow\)]( I already tried to restart visual studio, but it did not helped. I restarted unity, but this brings no success too.
Today everything just works fine. Thats so weird. Yesterday I had no chance but today everything is perfectly fine. What is the reason? Next time whenever I have a problem with software, I will just turn my computer off for some minutes and then turn it on again, sounds stupid? I know, but apparently it works.
stackexchange-gamedev
{ "answer_score": 0, "question_score": 1, "tags": "unity, visual studio" }
Should I differentiate parameters in my URLs? I think I read somewhere that it was a good practice to have certain "totally dynamic and irrelevant" parameters excluded from the nice URL rewriting techniques. Like here on the StackOverflow galaxy, when you login the URL is `/users/login?returnurl=parameter`. The reason would also have been that it kind of "prevents" search engines to follow those links, and could be a good idea for "transition pages" that change often and should not be indexed as is, but still followed, like `/news?page=5` where this page would be an index of the latest news, and by nature changes over time as old news are pushed down. Is there any sense to that? Would you agree, and if so maybe point to some resources? If not, what do you think of it, and what should be done with those pages that keep changing? Thanks for any thought!
There is really only one rule: **If the page content doesn't change when the parameter changes, then tell Google to ignore it.** Your `returnurl` example is a good one - I assume the page doesn't change at all, so tell Googlebot to ignore that parameters in Webmaster Tools. (Actually Google is pretty good at detecting these anyway.) But for `page` \- definitely do not ignore this! You need the search engines to parse all your pages to find the links to the content.
stackexchange-webmasters
{ "answer_score": 2, "question_score": 4, "tags": "seo, url rewriting" }
Collecting a list of all object keys that meet certain criteria I have a function `getActiveProp`: const getActiveProp = obj => Object.keys(obj).find(k => obj[k].active); But now, instead of finding the first item matching the criteria, I want to get an array of all of them. I know I could simply do something like this, and wrap it in a function: var arr = ['foo', 'bar', 'baz']; var arr2 = []; arr.forEach(k => arr2.push(k)); But I was just wondering if there was a one-line way to do it, creating the array within the `forEach` method itself, or using some similar array method to do it. Can that be done?
Use `Array#filter` in place of `Array#find`: let object = { inactiveProp1: { active: false }, activeProp1: { active: true }, activeProp2: { active: true } } const getActiveProps = o => Object.keys(o).filter(k => o[k].active) console.log(getActiveProps(object))
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, arrays" }
Unable to login to web app when using VSCode Chrome Debugger When I start a debugging session on VSCode, it opens a new Chrome window and loads my web app. My web app requires the user to sign-in via Google to use. When I try to sign in, I get an error saying "This browser or app may not be secure". There is no option that allows me to bypass this and sign in. Does anyone know a way around this?
Logged into the correct google account turning on "Less secure app access" on < should work From google support: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "javascript, vue.js, visual studio code, google chrome devtools" }
Can I change class types in a setter with an object-oriented language? Here is the problem statement: Calling a setter on the object should result in the object to change to an object of a different class, which language can support this? Ex. I have a class called "Man" (Parent Class), and two children namely "Toddler" and "Old Man", they are its children because they override a behaviour in Man called as walk. ( i.e Toddler sometimes walks using both his hands and legs kneeled down and the Old man uses a stick to support himself). The Man class has a attribute called age, I have a setter on Man, say `setAge(int ageValue)`. I have 3 objects, 2 toddlers, 1 old-Man. (The system is up and running, I guess when we say objects it is obvious). I will make this call, `toddler.setAge(80)`, I expect the toddler to change to an object of type Old Man. Is this possible? Please suggest. Thanks,
This sounds to me like the model is wrong. What you have is a `Person` whose relative temporal grouping and some specific behavior changes with age. Perhaps you need a method named `getAgeGroup()` which returns an appropriate Enum, depending on what the current age is. You also need an internal state object which encapsulates the state-specific behavior to which your `Person` delegates behavior which changes with age. That said, changing the type of an instantiated object dynamically will likely only be doable only with dynamically typed languages; certainly it's not doable in Java, and probably not doable in C# and most other statically typed languages.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "language agnostic, oop" }
object literal with arrays brackets positioning I made this object literal and I don't understand what is the right brackets positioning for the array that comes after `active`. Why am I getting missing brackets error? var players = { player1 : { active : true, [ { row : 1, square : 1 },{ row : 2, square : 1 },{ row : 3, square : 1 } ] } };
First off, that's not JSON, that's a JavaScript object initializer (sometimes called an "object literal"). The problem is the `[` here: active: true, [ You need a key before that value. The basic form is `key: value`, where the key is the name of the property (can be an identifier, a number, or a string in JavaScript; in JSON it would have to be a string, and in double quotes not single quotes) and the value is, well, the value. :-)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript" }
Is it possible to "pimp up your aircraft" with an audio system? Can aircraft be modified to have an enormous audio system, like the ones in cars? Has the FAA got any regulations on this (or maybe on in-cabin maximum noise volume?), would power be a limitation for the audio system?
Absolutely not, as it would not be in the sense of security. * It would block engine sounds (eg you won't be able to hear a rough engine) * It would block warning sounds, for example stall warnings * It would block any other abnormal sounds * You will have problems understanding ATC (and they will have even more problems understanding you) These are just some reasons out of my head. If you want to listen to music inflight, buy a good headset with an AUX-In socket, those normally reduce the volume as soon as a transmission is incoming. And apart from the audio volume, it would also put a high load on the battery / alternator, which are probably not able to handle such a high load.
stackexchange-aviation
{ "answer_score": 4, "question_score": 9, "tags": "faa regulations, aircraft design" }