INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to get websites actual HTML code by JS? I have a website with a form. The form is filled by user with data for example i show to user: <input type='text' value="" name="dsa" /> And he fills it with value of "3"; And he clicks button "save". Now i want to have the whole HTML of the website including values of fields. So i use: document.documentElement.innerHTML But i get: <input type='text' value="" name="dsa" /> But i want to get this: <input type='text' value="3" name="dsa" /> NOTICE I want to take the whole HTML of the website, not only one field. I dont know what fields will be on the website so i need a general solution.
AFAIK you can't get this from the HTML code, as the HTML code does not change when the user inputs something in a Input text field. What you could do is get all input fields on the page and get their values with something like this: var inputs, index; inputs = document.getElementsByTagName('input'); for (index = 0; index < inputs.length; ++index) { // deal with inputs[index] element. } The code is from this post: < I was too lazy to write it down my self :P
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "javascript, html, dom" }
How to stretch fields horizontally in jasperreport? I'm using JasperReports with Eclipse Plugin in a Java project. In JasperReports I'd like to stretch a field horizontally and move the next element to the right if the text field is too long. Even if I set all the elements with position float nothing happens. If I set the text field with `isStretchWithOverflow="true"` I get vertical stretch, like this. ![enter image description here]( What I'm looking for is something like this: 1 X 11111 Campo di Testo 1 X 12345678901234567890123456789012345678901234567890 Campo di Testo
As Amongalen says in their answer there is no property to stretch horizontally. # _but,_ you can concatenate multiple fields in same text field to achieve your desired result. ${field1} + " " + ${field2} **full jrxml for textField** <textField> <reportElement x="0" y="0" width="100" height="30" uuid="6757386c-10c7-451f-bb1a-97951697d782"/> <textFieldExpression><![CDATA[${field1} + " " + ${field2}]]></textFieldExpression> </textField>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "jasper reports" }
find image in div and place in an other div on top of page I have 2 divs. One at the top of the page and one all the down of the page. like so: <div class="collectionHeader"> <h1>Some title</h1> <div class="image"></div> </div> ...... a lot of html code .......... <div class="text"> <img width="558" height="100" src="stoelen.jpg" /> Lorem ipsum dolor sit amet etc.... </div> What i try to achieve is to select the image in the div called "text" and place this image in the div called "image" on the top of the page. I really don't have a clue on how to achieve this! Any help appreciated.
Use **.appendTo()** this will insert the element at the end of the target or you can also use **prependTo()** to insert it as the first element $(".text").find("img").appendTo(".image")
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
Observing NSPopupButton changes How can I get a method call when NSPopupButton changes? Thanks!
You just add an action method as with an `NSButton` or any other control.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "iphone, cocoa" }
How to explode BOM(Bill of Material) in excel What I Have in Microsoft Excel(2010) !This is What I have in excel What I want to see when I Click the (-) sign !Level 1 and Level 2 So to Conclude the (+) sign is to show all the Level 0.1-0.3 While the (-) sign could choose to either Show Level 0.1 and 0.2 or just purely Level 0.1 I hope to do this through VBA but if there is alternative I wouldn't mind trying.
You can do this using the "groups" function in Excel. If you haven't many rows and aren't interested in automation, you select the rows you want to hide/group (in your example, rows (3-5) and hit group.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "microsoft excel" }
windowPartitionBy and repartition in pyspark I have a small code in SparkR and I would like to transform it to pyspark. I am not familiar with this windowPartitionBy, and repartition. Could you please help me to learn what this code is doing? ws <- orderBy(windowPartitionBy('A'),'B') df1 <- df %>% select(df$A, df$B, df$D, SparkR::over(lead(df$C,1),ws)) df2 <- repartition(col = df1$D)
In pyspark it would be equivalent to: from pyspark.sql import functions as F, Window ws = Window.partitionBy('A').orderBy('B') df1 = df.select('A', 'B', 'D', F.lead('C', 1).over(ws)) df2 = df1.repartition('D') The code is selecting, from `df`, columns A, B, D and column C of the next row in the window `ws`, into `df1`. Then it repartitions `df1` using column D into `df2`. Basically partitioning means how your dataframe is distributed in the memory/storage, and has direct implications on how it is processed in parallel. If you want to know more about repartitioning dataframes, you can go to <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "apache spark, pyspark, apache spark sql, sparkr" }
Site aligned to left on mobile devices I have setup my dev site for desktop looks beautiful! but then when i go to mobile it is aligned to left with an empty space in the right. My first thought was because the logo at top is too big and that causes to have that empty space at the right so i reduce the width without solving my issue. < you can see my dev site here: < Thanks in advance
I think it is related to you specifying the viewport twice. You have: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> . . <meta name="viewport" content="width=device-width" /> Try removing that second viewport line, leaving just the first. It seems to be upsetting the page scaling, at least it was for me.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mobile, web, alignment, responsive" }
How to jump to any other controller in iOS? My storyboard structure is like: !enter image description here A is a navigation controller B is a tab bar controller C,D,E are view controllers F,G,H,I,J are a view controllers if now i am on I ,and there's a button the i pressed then I go back to C.How to do that? I tried make segue between I and C, but C has a back button, you pressed it,you back to I. I don't want that.when i came from I to C, i want C is as I first come to C from B. if i want to go to H from I,I want H have a back button that you pressed and you back to F not to I.
From I to C: do popViewController twice, or loop through the navigationcontroller's viewcontrollers and find C, pop to C. From H to I: Programmatically push to I. In storyboard set an storyboard ID for I, and you can create a I instance through [storyboard instantiateViewControllerWithIdentifier:ID];
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ios, uinavigationcontroller, uitabbarcontroller, segue" }
In Magento 2.3.4, Need to Merge CSS on Page wise Many of them using Custom Theme with multiple custom modules. In custom module, we calling particular module css on Layout xml file. When we enable **Merge CSS file** option under `admin -> Stores > Settings > Configuration > In the panel on the left under Advanced > choose Developer`. Currently, It merge all CSS in single file and loading the entire website. But, unwanted css (which not related to the page) also loading. I am looking to merge the CSS on page wise and working on it. If anyone have an idea about this please comment it.
I have analysed and noticed that by default Magento 2 version merging the CSS by Layout wise and with default (Theme Layout) xml file. In order to load page wise CSS, we need to separate the custom CSS (for particular Page css) and mentioned it in the respective Layout file. **For example:** In Product Page (Catalog product view) app / code / [companyname] / [modulename] / view / frontend / layout / catalog_product_view.xml Create the custom CSS files: app / code / [companyname] / [modulename] / view / frontend / web / css / productpage.css (custom CSS file) Add Custom CSS in the Layout File under head tag <head> <css src="[companyname]_[modulename]::css/productpage.css" /> </head> After merging, default theme css and productpage.css will merge and load it.
stackexchange-magento
{ "answer_score": 2, "question_score": 1, "tags": "magento2.3.4, magneto2.3" }
Apache2 redirect to another domain with ssl I have a no clue why this fails. I just want to redirect all domain to `www.maindomain.com` and also `http` to `https`, what am i missing? # redirect http to https RewriteCond %{HTTPS} off RewriteRule ^(.*)$ [L,R=301] # redirect without www to www RewriteCond %{http_host} ^maindomain.com [nc] RewriteRule ^(.*)$ [r=301,nc] # redirect another domain to www.maindomain.com RewriteCond %{HTTPS} off # this i was missing RewriteCond %{HTTP_HOST} ^(www\.)?anotherdomain.com [NC] RewriteRule ^(.*)$ [R=301,L] 1. ` to `https:/www.maindomain.com/` works 2. ` to `https:/www.maindomain.com/` works 3. ` to `https:/www.maindomain.com/` fails
The Http to Https redirection for Another domain failed because Your Rule is missing the following line : RewriteCond %{HTTPS} off Try : # redirect another domain to www.maindomain.com RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(www\.)?anotherdomain.com [NC] RewriteRule ^(.*)$ [R=301,L]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "apache, .htaccess, redirect, ssl" }
Connect smartphone to website I've come across this link a while ago: < I thought it was really cool, the ability to connect your phone to a website and let it control certain things. And just now I found this link: < it implements the phone connect option too (if you go to 'experience my work'). I'm considering of experimenting a little something with this for my portfolio website, but I have no idea where to start; can someone give me a push in the right direction? What is this 'function' called? Is it very hard? to be more specific what I want to use this for: I want the user to be able to drag along a screen and pan and rotate a 3D object that way (I'm a 3d artist).
Take a link at Hammerjs, this allows you to capture your phone's accelerometer and gyroscope data, it's fairly quick to get up and running. In terms of connecting up a phone to your desktop via a web app, it's a little more work, take a look at this article on establishing a connection with a node server as well at this article which goes into a little more detail and it should point you in the right direction.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "javascript, jquery, css, smartphone" }
Meaning of "guest" in file sharing One of the options in file sharing is whether to include "guest users." Does this mean the "guest account" on another Mac, or does it have some other meaning?
‘Allow guest users’ refers to connecting to the server without any authentication as a Guest, in comparison to using the Registered User option which requires a username and password. If you choose to not allow guest users, it's not possible to connect using the Guest option in Finder, or otherwise not providing credentials when using another tool. ![]( This is not related to the Guest account in macOS, but there is an option in Users & Groups to enable/disable guest access to shared folders here: ![](
stackexchange-apple
{ "answer_score": 0, "question_score": 1, "tags": "macos, file sharing, guest account" }
How use Prolog from Java? In the context of a Java/Eclipse application I would like to use Prolog for a particular task. What are the available solutions and tools to do that, and associated pro and cons ? I can launch an external Prolog interpreter generating the result in a file ? I can use a full Prolog Java Library (Prolog interpreter implemented in java) ? I can use a java library dedicated to the communication with an external Prolog interpreter ? Thanks in advance for your help, Manu
I would give GNU Prolog for Java a try. From the website: > GNU Prolog for Java is an implementation of ISO Prolog as a Java library
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 14, "tags": "java, prolog" }
Modeling an optimization problem as linear programming problem ![enter image description here]( ## Attempt: First, I call $x$ be the number of shafts produced per year and $y$ the number of frames produced per year. We have that each machine works at most $4500$ hours. we can place all of our data in the following table: ![enter image description here]( Thus, we want to maximize $f(x,y) = x+y$ subject to $$ 0.6 x + 0.8 y \leq 90 000 $$ $$ 0.3 x + 0 y \leq 22 500 $$ $$ 0.4 x + 0.6 y \leq 45 000 $$ $$ 0x + 0.2 y \leq 135 00 $$ $$ 0x + 0.3 y \leq 27 000 $$ and obviously $x \geq 0$ and $y \geq 0 $ Is this the correct formulation?
I suppose your model is not correct. Solving the model with an LP-solver yields the solution $x=75000$ and $y=25000$. I assume, however, that for every frame you also need a shaft. Hence, you need to add the following constraint: $$x=y$$ Solving the problem with the additional constraint yields the solution $x=y=45000$. Please note that luckily the number of shafts/frames in the solution is an integer. This need not happen always. Thus, you should also add the constraints $x\in \mathbb{Z}$ and $y \in \mathbb{Z}$ in general, even though these were not needed here.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "optimization, convex optimization, linear programming, mixed integer programming" }
Entity Framework , List and Lambda im working with EF codefirst and i need to sort the list of entries, i tried but could not find how to solve this task: Lets say we have expression thelist.orderby(p=> p.Name) Question is : **How to pass string instead of "p.Name" in case if i want to order list by p.Age for example** Because there are like 20 or more options to sort so im trying to shrink the code
Just install Dynamic LINQ (NuGet source), include `using System.Linq.Dynamic;` with your namespaces, and you'll be able to call: thelist.OrderBy("Name"); thelist.OrderByDescending(someStringParameter); etc.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "list, lambda, ef code first" }
Selenium WebDriver Report Generation using Allure Reporting tool I am new to Selenium WebDriver.I am currently using TestNg to generate reports .but i need to use Allure Reporting framework with TestNg to generate reports.I don't see any proper documentation for using Allure.Need help in installation and setting up Allure framework with TestNg.
Is there any specific reason for using Allure Reports. I am using Extent Reports for my test these are very easy and very good at the same time. Here is a sample extent report for selenium tests : Sample
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "selenium, selenium webdriver, allure" }
Call class member of c++ DLL from c# I already know how to call functions of a C++ DLL from C#, when the provided functions are not members of classes. But how would I call a class member like foo in the following code sample? class _declspec(dllexport) MyClass{ public: void foo(); }; Doing something like this doesn't work, because the c#-Compiler doesn't know which class to call. [DllImport("MyDLL", CallingConvention = CallingConvention.Cdecl)] private static extern void foo();
The only way to directly call methods on a C++ object from C# (and most other languages) is to create a full-fledged COM object out of it. An easier way with a level of indirection: Develop an API of purely static methods that reflect the object's operations. Then you can call that from .NET easily. C++: MyClass* WINAPI CreateMyClass() { return new MyClass(); } void WINAPI CallFoo(MyClass* o) { o->foo(); } C#: [DllImport("MyDLL")] private static IntPtr CreateMyClass(); [DllImport("MyDLL")] private static void CallFoo(IntPtr o);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, c++, dll, marshalling" }
Can IEEE, Elsevier, Springer detect multiple submissions to their journals? If one wants to submit one's manuscript to multiple journals of a publisher (IEEE, Elsevier, Springer etc.), is it possible for a publisher to detect it? I mean if any publisher keeps a database of submitted manuscripts to crosscheck newly submitted manuscripts with the existing ones.
Surprisingly enough, they probably can't. Modern Editorial Management Systems can detect multiple submissions to the same journal, even if the previous submission was years ago, but the EMS still only works for that one journal. Inter-journal sharing does happen, but as far as I'm aware, it's not common and even then it's often only the reviewer pool. The editors of one journal cannot see which manuscripts are submitted to the other journal. If you are detected by the publisher, the most likely reason is because one of the production staff handles both journals and noticed it. Alternatively, it's possible the editors of both journals invited the same reviewer who noticed it.
stackexchange-academia
{ "answer_score": 3, "question_score": 0, "tags": "paper submission" }
If we change the radius of spherical surface does electric field or flux change? > Suppose a point charge is located at the center of a spherical surface. The electric field at the surface of the sphere and the total flux through the sphere are determined. > > 1).What happens to the flux and the magnitude of The electric field if the radius of the sphere is halved? Our teacher said the flux decreases and the filed increases. But here: > A spherical gaussian surface surrounds a point charge $q$. Describe what happens to the: flux through the surface if > > 2) The radius of the sphere is doubled Our teacher said the electric flux will not change > 3) The shape of the surface is changed to that of a cube Also the electric flux will not change So why the electric flux changed in question 1 but in question 2 did not change? And when does the electric flux and electric field change?
From gauss law we have $$\Phi_E=\frac{q_i}{\epsilon_0}$$ $q_i$ represents total change inside a closed surface and is independent of surface area and radius of that closed surface. to the other end remember $$\Phi_E=\oint E.dA$$ where $$|E|=\frac{q}{4\pi\epsilon_0r^2}.$$ $\Phi_E$ is of course constant in your example (all questions including **Q.1**.) and the reason the electric flux changed in question 1 is you are misunderstood. Field will increase if $r$ decrease because $E\propto \frac{1}{r^2}$. **Q.3's** answer : (taken freom H.C verma concepts of physics chapter 30 exercise 5): Since the charge is placed at the centre of the cube. Hence the flux passing through each side = $q/6\epsilon_0$
stackexchange-physics
{ "answer_score": 3, "question_score": 2, "tags": "electrostatics, electric fields, gauss law" }
Вычислить сумму чисел Считать целые числа и вычислить: !alt text
Если элементарно закодить формулу, то: #include <iostream> using namespace std; int main() { int n = 50; double s = 0; for (int i = 1; i <= n; i++) { s += 1.0/(i * i * i); } cout << s << endl; } возникает только вопрос о чём речь в словах: > Read any int as input
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, ряды" }
Mouse thinks it is in a different tmux pane I am using tmux 3.0 in bash over ssh on CentOS 7. My tmux.conf is fairly simple. It has some bindings and set-option -g mouse on set -g focus-events on I have a fairly large tmux window with 3 vertical panes. When I move the mouse to the right side of the rightmost pane and do something (e.g. scroll with mouse wheel or click to select this pane). The action gets executed on the leftmost pane instead. This behavior persists if I detach from and reattach to the session. Any ideas what might be causing this and how to fix it?
Terminal emulators which do not support SGR mouse mode will not correctly report any mouse actions to the right of column 227. Is your terminal emulator window wider than this? Try using a different terminal emulator.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "tmux" }
presto - getting days interval (not date) How do I get the days interval for prestodb? I can convert to milliseconds and convert these to number of days but I am looking if there is any shorter way to do this. Example: I want to see how many days has it been since the first row inserted in a table. SELECT to_milliseconds(date(current_date) - min(created)) / (1000*60*60*24) as days_since_first_row FROM some_table What I am hoping to see: (Either 1 of below) SELECT to_days(date(current_date) - min(created)) / (1000*60*60*24) as days_since_first_row ,cast(date(current_date) - min(created)) as days) as days_since_first_row2 FROM some_table
Use subtraction to obtain an interval and then use `day` on the interval to get number of days elapsed. presto:default> select day(current_date - date '2018-07-01'); _col0 ------- 86 The documentation for this is at <
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "sql, presto" }
How do I get the url of uploaded file? I have uploaded an mp4 file as follows: import firebase_admin from firebase_admin import credentials from firebase_admin import storage cred = credentials.Certificate('my-app-service.json') firebase_admin.initialize_app(cred, { 'storageBucket': 'amy-app-name.appspot.com' }) bucket = storage.bucket() blob = bucket.blob('teamfk.mp4') blob.upload_from_filename('path/to/teamfk.mp4') Now I can't find the syntax to get a reference to the uploaded url ? * To add, I should be able to view/download from browser. * It need not be authenticated, public is fine.
As per Google Docs - Cloud Storage The public URL of the file can be retrieved with blob.make_public() blob.public_url
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python, google cloud storage, firebase storage, firebase admin" }
JavaScript function and return var Double = function(number) { return number * 2; }; var number = Double(12); console.log(number); //on code academy this will run and return the number doubled as its supposed to. I put this in debug and it will not run? //ultimately i am trying to write a function called double that takes in a number as the parameter, and returns that number doubled. //sorry if this is elementary but I am new to JavaScript and trying to teach myself //Just in case anyone else is having this issue I figured out the issue in JSfiddle <
The result page in jsfiddle renders html. The Javascript function 'console.log()' outputs information to the browser console, not to the Document Object Model (dom). You can view javascript console output in any browser console, I like to use Chrome Web Tools, or you can build your own HTML to see the results Rest assured, the function you wrote works, it just doesn't represent itself in the results part of jsfiddle. **Edit:** formatting **Edit 2:** If you just want the confidence your Javascript function is working, without other technical information, change `console.log(number)` to `alert(number)`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, function, return" }
Trigonometical identity proof I was given a proving sum: $\sec(x) + \tan (x) = p$, prove $\frac{p^2-1}{p^2+1} = \sin (x)$ I went head on and tried to directly do it by solving the LHS: $\sec(x) + \tan(x)$ = $\frac{1}{\cos(x)} + \frac{\sin (x)}{\cos (x)}$ =$\frac{\sin(x)+1}{\cos(x)}$ Squaring both sides now, = $(\sin(x)+1)^2 = p^2(\cos^2 (x))$ On further solving I am getting stuck. Can anyone point out how to proceed? I am curious to learn how to move beyond these steps. Also, easier answers (read: shorter steps) are always appreciated!
Just put the value of $p$ and simplify. Use the facts : $\sec^2 x-1=\tan^2 x$ in **numerator** and $1+\tan^2 x=\sec^2 x$ in **denominator**. $$\frac{p^2-1}{p^2+1}=\frac{2\tan x(\sec x+\tan x)}{2\sec x(\sec x+\tan x)}=\sin x$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "trigonometry, proof verification" }
How do I know that this sequence exists in the vector space? Let $(V_i, \|\cdot \|_i), i=1,2$ be normed vector spaces over $\mathbb{F}$ and let $T$ be a linear map from $V_1 \to V_2$, and assume that $T$ is not bounded. How do I know that there exists a seq. $(x_n)_n \in V_1$ s.t $\|x_n\| \leq 1$ and $\|Tx_n \| \geq n$ $\forall n \in \mathbb{N}$? I know that by def of bounded linear operator we have $\|T\| = \sup_{x \in V_1, \|x\| \leq 1} \|Tx\|_{V_1}$ but since $T$ is not bounded, this must fail. But why do we have $\geq n$? The claim is made in the solution in a problem Im working on.
"$T$ is bounded" means "There exists an $n\in \Bbb N$ (really $\in \Bbb R^+$, but it is the same in the end) such that for any $x\in V_1$ with $\|x\|\leq 1$, we have $\|Tx\|\leq n$". If you negate that definition, you get that "$T$ is not bounded" means "For any $n\in \Bbb N$ there is an $x\in V_1$ with $\|x\|\leq 1$ such that $\|Tx\|\not\leq n$".
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "functional analysis" }
How to disable iconified button in Menu bar in JFrame Window? How to disable iconified button in JFrame Window ? something like setResizable, but for minimize button
At First, you can use the method setUndecorated(boolean). It may disable the title bar and the border. In the end, you will create the icon label and close button at your frame top or the others position. But this way will lose the border look and feel for the frame. If you choose this way, you must create a lot of code. In fact, If you could not use JNI, this way may be the only.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, swing, button, jframe" }
How to download an attachment from mail via applescript and mail rules? I automatically receive a lot of vcards via email and I want to import them automatically into my contacts. I coded an AppleScript that will open the vcard file and import the contact. But first I need to download the file, right? But how can I download an attachment file from an email using AppleScript and rules in mail? Thank you. Cheers, Chris
The script bellow saves the files attached in a selection of emails into a destination folder. you can then use these files to add them in Address Book. set Dest to ((path to desktop folder) as string) & "FMail:" -- the folder to save attached files tell application "Mail" activate set ListMessage to selection -- take all emails selected repeat with aMessage in ListMessage -- loop through each message set AList to every mail attachment of aMessage repeat with aFile in AList --loop through each files attached to an email if (downloaded of aFile) then -- check if file is already downloaded set Filepath to Dest & (name of aFile) save aFile in Filepath as native format end if end repeat -- next file end repeat -- next message end tell I added many comments to make it clear. then you will be able to adapt it to your needs.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "email, applescript, macos sierra" }
Combinatorics: example where order matters for |E| but not seems to matter for |S| I was in a class where the following example problem for a probability question was given. The instructor could not give an explanation when pressed to explain why $|S|$ seemed to be the cardinality of an ordered set but $|E|$ seemed to be cardinality for an unordered set. > Roll a die 12 times. What is P(each number appears exactly twice)? > > $$ \frac{{12 \choose 2}{10 \choose 2}{8 \choose 2}{6 \choose 2}{4 \choose 2}{2 \choose 2}}{6^{12}} $$ If $|S|$ is $6^{12}$ , then $S$ must be an ordered set, so $E$ should be ordered as well, but doesn't the " _n choose k_ " paradigm do away with ordering (of the chosen elements)? I mean, isn't that the role of the $2!$ in the denominator of the following? $${12 \choose 2} = \frac{12!}{10!2!}$$
$12!$ is false! How can factorials be possibly related to dice rolls? In fact, you should have $6^{12}$ in the denominator. This is also an "ordered" realm (which you should deal with every time when you have a question about physical objects like dice and coins): Each $6$ is the number of different rolls of a corresponding die. But numerator is "ordered" as well. However, is does not count unordered random choices of some objects. Instead, it counts the number of ways in which you can assign rolls to dice: $12 \choose 2$ to assign the ones, $10 \choose 2$ for the twos etc.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "probability, combinatorics" }
Update a model's ID but save to old ID URL in Backbone I have a model with an ID of, for example, an ID of 3. So it's URL is '/items/3' on the server. What I need to do, is the save() the Model with a new ID but send the request to the URL '/items/3', but with ID in the request body of, for example, 4. How can one achieve this? At the moment, if I set a new ID on the Model, it tries to send a PUT request to the new ID's URL. How can I specify to make the request to the old ID, but keep the new ID set on the Model. On success() of the PUT, I will navigate the user to the new URL...
I think what you're searching for is the behavior or Model#save with the **wait flag** set to true: " _Pass {wait: true} if you'd like to wait for the server before setting the new attributes on the model._ ". It would send to the server the attributes updated, but will set them on the model only when the server answers.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "backbone.js" }
how to use the method each_with_index in ruby, I wanna change the index of a given array I wanna change the index of a given array: arr = ["cat", "tiger", "lion"] so lion-item will have the value of 5-index, tiger will have value of 4-index and 3 for cat-item is this possible? Thanks!
You could do that with a `Hash`: hash = { 3 => "cat", 4 => "tiger", 5 => "lion" } hash[4] #=> "tiger" If you want to convert from an Array to a Hash you can do this: arr = ["cat", "tiger", "lion"] hash = Hash[arr.each_with_index.map{|v,i| [i+3, v] }] #=> {"cat"=>3, "tiger"=>4, "lion"=>5}
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "ruby" }
How to convert a LiveCD into a vmlinuz and initrd to PXE Boot Load Slowly I need to make a emergency PXE bootloader for a LIVECD (not the ubuntu netboot small cd, but rather a desktop livecd to boot from the command line). Will this work: # Create a cpio archive of just the ISO and append it to the initrd image. ( echo "ubuntu-13.10-desktop-amd64.iso" | cpio -H newc --quiet -o ) | gzip -9 | cat ubuntu-13.10-desktop-amd64.iso_EXTRACTED/casper/initrd0.img - > tftpboot/initrd0.img # Kernel image. cp ubuntu-13.10-desktop-amd64.iso_EXTRACTED/isolinux/vmlinuz0 tftpboot/vmlinuz0 # pxelinux bootloader part: LABEL pxeboot KERNEL vmlinuz0 APPEND initrd=initrd0.img root=/ubuntu-13.10-desktop-amd64.iso rootfstype=iso9660 rootflags=loop ONERROR LOCALBOOT 0 What am i doing wrong?
That configuration loads the whole image through a slow protocol like TFTP. * Try other option using NFS protocol. apt-get install nfs-kernel-server mkdir /mnt/ubuntu mount -o loop ubuntu-13.10-desktop-amd64.iso /mnt/ubuntu-desktop-cd * Share it through NFS sudo nano /etc/exports Add this line /mnt/ubuntu-desktop-cd 192.168.0.0/24(ro,insecure,no_root_squash,async,no_subtree_check) * Start NFS service service nfs-kernel-server restart * In `APPEND` line, replace `root`, `rootfstype` and `rootfstype` with: netboot=nfs nfsroot=192.168.0.10:/mnt/ubuntu-desktop-cd **Note** : I used these IP's just as an example. 192.168.0.10 is IP of the NFS server 192.168.0.0/24 Is local network range. See <
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 3, "tags": "pxe" }
Name for celestial "Prime Meridian"? Is there name for the line that goes from celestial pole to pole at RA 0 degrees 0 minutes 0 seconds? On Earth we would call it the Prime Meridian. Is it called the "Celestial Meridian"?
That is correct, the line going through 0RA (and 12, actually) is the Celestial Meridian.
stackexchange-physics
{ "answer_score": 1, "question_score": 3, "tags": "astronomy, definition" }
One query that matches values with only one condition out of two, one query that matches values with both conditions I'm having some sort of a blank about how to do this in SQL. Consider this reprex in R set.seed(123) data.frame(ID = (sample(c(1:5), 10, replace = T)), status = (sample(c("yes", "no"), 10, replace = T)), amount = (sample(seq(1,50,0.01),10))) which gives out this table ID status amount 1 3 no 29.87 2 3 yes 26.66 3 2 yes 15.49 4 2 yes 18.89 5 3 yes 44.06 6 5 no 30.79 7 4 yes 17.13 8 1 yes 6.54 9 2 yes 45.68 10 3 yes 12.66 I need to find two SQL queries. One where I select the ID's that only have status of 'NO' meaning ID 5. and One where I select the ID's that match both conditions, meaning ID 3 I have a query for both but I'm almost sure it's not correct so any lead is more than welcome. Thanks
> One where I select the ID's that only have status of 'NO' meaning ID 5. select id from your_table where status='no' and id not in (select id from your_table where status='yes') > One where I select the ID's that match both conditions, meaning ID 3 select id from your_table where status='no' and id in (select id from your_table where status='yes') At last I think you are expecting ids which do not match these conditions. so `UNION` both queries and get ids of your table which not exists after `UNION` select id from your_table where id not in ( select id from your_table where status='no' and id not in (select id from your_table where status='yes') union all select id from your_table where status='no' and id in (select id from your_table where status='yes') )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, filter, amazon redshift" }
Show only 2 numbers after percentage I have a problem where when i run the following query I get "PercentageDifference" as 99.253731343283500 all i really want to show is 99.25 but no amount fiddling seems to get it any lower or results in an error: select PlannedMonthName , CountOfPlannedVisits , CountOfPlannedVisitsClosed , CONVERT( DECIMAL(12,2), nullif(CountOfPlannedVisitsClosed, 0) ) / CONVERT( DECIMAL(12,2), nullif(CountOfPlannedVisits, 0) ) * 100 AS PercentageDifference
You can use `round` function as follows: select PlannedMonthName , CountOfPlannedVisits , CountOfPlannedVisitsClosed , round( ( CONVERT( DECIMAL(12,2), nullif(CountOfPlannedVisitsClosed, 0) ) / CONVERT( DECIMAL(12,2), nullif(CountOfPlannedVisits, 0) ) * 100 ), 2) AS PercentageDifference **TRUNCATE(X,D)** can be used as well : It returns the number X, truncated to D decimal places. If D is 0, the result has no decimal point or fractional part. D can be negative to cause D digits left of the decimal point of the value X to become zero.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql" }
jQuery .data() append So this is my scenario: I have a few questions that the user answers and I want to store them so at the end of the questionnaire I can render a list of each question and the answer. Obviously I could go with a global variable but the problem is that there are other questionnaires on the site. My solution is to go with jQuery's `.data()`. My problem is that when I try to add similar data, it overwrites the previous. Here's a simple example: <div id="test"></div> $("#test").data({name:"foo",answer:"bar"}); $("#test").data({name:"john",answer:"doe"}); console.log($("#test").data()); //logs name:"john",answer:"doe" How can I get it to keep both values?
You are over writing the previous data, add both record in single call in array. **Live Demo** $("#test").data([{name:"foo",answer:"bar"}, {name:"john",answer:"doe"}]); Access data like array, alert($("#test").data()[0].name); alert($("#test").data()[1].name); **Edit** based on comments, if you want to add records to data one after other you can use key value pair. **Live Demo** $("#test").data("1", {name:"foo",answer:"bar"}); $("#test").data("2", {name:"john",answer:"doe"}); As @Heart pointed out if this data is important then storing on client is open for client and could be modified. Using ssl and posting it as you get it from user could save from data security being compormised.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, jquery data" }
can only concatenate str (not "NoneType") to str! What's wrong legth = 6 price = '' for i in range(legth): price += "{} ".format(i) print(price) line2 = "" board = [] for i in range(legth): board.append([" "]*legth) for k in range(legth): # if k == 0: # line2 += "str(k) +" line2 += "board[{}]".format(k)+ "[{}] + ' | ' +".format(k) line2 = line2[:-1] for k in range(legth): newline = str(k)+ '|' + exec(line2) #line2 = line2[:-1] print(newline + " "*5) # + line2) if i < legth: print(" +___+___+___+___+___+___+___+___+" ) Why does this return newline = str(k)+ '|' + exec(line2) TypeError: can only concatenate str (not "NoneType") to str
legth = 6 price = '' for i in range(legth): price += "{} ".format(i) print(price) line2 = "" board = [] for i in range(legth): board.append([" "]*legth) for k in range(legth): # if k == 0: # line2 += "str(k) +" line2 += "board[{}]".format(k)+ "[{}] + ' | ' +".format(k) line2 = line2[:-1] for k in range(legth): newline = str(k)+ '|' + str(eval(line2)) #line2 = line2[:-1] print(newline + " "*5) # + line2) if i < legth: print(" +___+___+___+___+___+___+___+___+" ) I don't know what you are trying to do but Try this exec returns None but eval returns something
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, pyzo" }
Can't chown 0 (root) in Cygwin This command: rm -f testfile && touch testfile && chown 0 testfile is failing in Cygwin with error: > > chown: changing ownership of 'testfile': Invalid argument > Why?
You cannot `chown` with `root` (0) account simply because there is no such thing in Cygwin.
stackexchange-unix
{ "answer_score": 7, "question_score": 5, "tags": "root, cygwin, chown" }
What is a good Python format style I've created a small python script to toggle between two files I'm using for testing. My question is, what is a good Python format style for the following code: import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) Or shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) Or tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) Or what? Also, what is the preferred way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"
For the conditional statement, I would probably go with: if filecmp.cmp(local, config_file): shutil.copyfile(remote, config_file) else: shutil.copyfile(local, config_file) There's little need to use the inline `y if x else z` in this case, since the surrounding code is simple enough.
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 2, "tags": "python, coding style" }
$\exp(-i \infty)$ is "Not a Number" according to MATLAB. Why? I ran into this problem while trying to understand the Laplace transform via MATLAB. exp(-i*Inf) > NaN + NaNi But, exp(-Inf) > 0 Furthermore, > syms t > fun= exp(-(0+i)*t) > answer=int(fun,0,Inf) returns > NaN But it is able to solve it if no limits are given. > answer = > exp(-t*1i)*1i Something about Infinity is not quite right with MATLAB. Any suggestions on how to make it right?
The reason is simple. The limit of $$e^{-i\phi}$$ as $\phi\to\infty$ simply doesn't exist. You see this since we have $$e^{-i\phi}=\cos\phi-i\sin\phi.$$ Letting $\phi$ become infinite, we cannot assign any definite value to the trigonometric functions on RHS. On the other hand, we have that $e^{-x}$ is vanishing when $x\to\infty$ since $e^{-x}=1/e^x.$
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "complex numbers, exponential function, matlab, floating point" }
Howto enable Quick diff with plus and minus in Eclipse? i had a eclipse workspace. I used Galileo and Subclipse. I got the workspace from a associate. The following function was enabled: There were signs shown to indicate differences to the svn state of the document, directly right beside the line numbers. If I added a line a "+" were shown. If I deleted a line a "-" were shown and a "~" when I edited a line. I think this is much easier than the colored quick diff. Now I had to install the hole system again. I installed Eclipse Galileo and Subclipse again. Now I can't find the settings to enable this feature anymore. How do I enable it? Is this called Quick Diff, too? Thanks in advance.
It is under the Accessibility preferences. General -> Editors -> Text Editors -> Accessibility -> Use Characters to show changes in the vertical ruler.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "eclipse, subclipse" }
Generate individuals from OWL class defintion I'm fairly new to ontologies and have the following situation: Given a class definition, I want to automatically generate individuals based on all possible combinations of a given restriction. For example: Let's say a "Pizza" class has the property "hasTopping" which is supposed to be linked to an individual of class "Topping". I want to generate an individual of the class Pizza for each individual existing for a Topping. If there are two Topping individuals, Tomato and Cheese, I want to create one Pizza individual with "hasTopping Tomato" and one with "hasTopping Cheese". Is there any general way to generate individuals in ontologies like this? (As an alternative to implement it myself.) Is this "violating" the intent/purpose of ontologies in general? Would this usually be handled in a different way? (I'm not completely familiar with ontologies yet.)
There's no standard method to do this, so I think you'll have to implement it yourself. The Leigh University Benchmark does something similar, so it might provide you with some ideas: < I don't think this violates the idea behind ontologies at all - seems quite straightforward. There is no best practice for it, so however you choose to implement it will probably be adequate.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "owl, ontology, inference" }
C Programming Command Line Argument #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int args, char *argv[]) { int i = 0; for (i = 0; i < args; i++) printf("\n%s", argv[i]); return 0; } As of now this program prints out whatever is written on the command line. How would I make it do this in reverse? For example, if I input "dog" it should say "god".
Try the following code: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { int i = 0; for (i = 1; i < argc; i++) { char *tmp = argv[i]; int len = strlen(argv[i]); for(int j = len-1; j > -1; --j) printf("%c",tmp[j]); printf("\n"); } return 0; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "c, arrays, string" }
Remove styling from an element if a certain element exists in the DOM higher up I have a fairly specific scenario where I'd like to remove a top-margin from an element named 'footer' if and only if I can determine the presence of another element in the DOM. The other element happens to be a DIV with a colored background, in which case the margin applied to the footer creates an unwanted empty white space. The other element is not a sibling of the footer, but is rather a fairly deep descendent of a a preceeding element in the DOM. An example would be : <main> <section> <wrapper> <div id="if-exists-remove-footer-styling"> <div> </wrapper> </section> </main>
Here's a non-jQuery solution: if (document.getElementById('if-exists-remove-footer-styling')) { document.getElementById('footer').style.marginTop = 0; } All this assumes is that your footer element has an id.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "css" }
What is the meaning of “erst vor knapp” in this sentence? The sentence: > Es lag etwas Verwirrendes im Ausdruck ihrer grünblauen Augen, wenn sie verliebt zu ihrem Freund aufblickte, der sie erst vor knapp einer halben Stunde unvermittelt gefragt hatte: ... I can’t seem to make sense of “erst vor knapp”
The whole expression you should be looking at, is: "erst vor knapp einer halben Stunde" This means, that he asked her _nearly half an hour ago_ or _just under half an hour ago_ , but not exactly thirty minutes ago. A similiar expression you might be coming across is "vor gut einer halben Stunde", which means something happened slightly over half an hour ago.
stackexchange-german
{ "answer_score": 1, "question_score": 0, "tags": "meaning" }
Unable to serve static file from flask server I have a index.html file, which has the absolute path 'c:\project\web\frontend\index.html' I am trying to return it using the following function @webserver.route('/') def home() return webserver.send_static_file(path) I have verified that the path is correct by accessing it directly in the browser. I have tried to replace '\' with '/' without any luck. It is running on a windows machine.
If you look at flask's documentation for send_static_file. You'll see that it says that it's used internally by flask framework to send a file to the browser. If you want to render an html, it's common to use render_template. You need to make sure that your index.html is in a folder called templates first. So I would do the following: @webserver.route('/') def home() return flask.render_template('index.html')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, flask" }
Template for front page (latest posts) I am having * * * index.php -> This renders the latest post with sidebar * * * page.php-> This renders the page layout : Templates are fullwidth,sidebarleft& sidebarright * * * single.php-> This renders the single post layout : Templates are fullwidth,sidebarleft& sidebarright * * * whether a template can be provided for index.php? How can i provide option for full width, sidebarleft& sidebarright options for index.php?
> whether a template can be provided for index.php? There's no built-in capability for selecting a custom template for archives. > How can i provide option for full width, sidebarleft& sidebarright options for index.php? You can add a generic Customizer control with options for which template to use for archives, then inside index.php you would just check the saved value of that control with `get_theme_mod()` and change the template accordingly, or include another template file, for example: switch ( get_theme_mod( 'layout' ) ) { case 'fullwidth': get_template_part( 'index', 'fullwidth' ); break; case 'sidebarleft': get_template_part( 'index', 'sidebarleft' ); break; case 'sidebarright': get_template_part( 'index', 'sidebarright' ); break; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, templates, page template" }
Should I show my six month old educational videos? My baby look excited when watching videos about addition and subtraction. I wonder if I should show video on counting first, then addition, and subtraction. Should I show him educational videos, like < for example? When I show him that he looks excited. I thought it's a good thing to teach him how to count from young.
Too many stimuli can be harmful to a baby. Here's a few articles 1, 2 \- or just google overstimulation and check for yourself. In general it is not recommended for children below 18 months to have any exposure to "screens" of any kind, be it smartphone or TV or console 3, 4. Google "screen time for children". Worrying about IQ at the age of 6 months is a mistake in my opinion. Your child right now requires care, peace, love and closeness. At around 12 months or so you may try to, very gently, encourage him to play creatively, build or invent - with blocks, duplos, etc. When he's over 2yo - then, maybe, you can start working on counting. Be warned thought, that while your 2+ yo child may learn to count to 10 or 20 quite easily, the abstract concept of addition or subtraction will still elude him for a while.
stackexchange-parenting
{ "answer_score": 41, "question_score": 12, "tags": "infant, screen time" }
Custom controller class name in Code Igniter How do make CodeIgniter correctly load controller classes if I want to name them [name]_Controller rather than just [name]?
You would have to write your own router-class, in the documentation is a great explanation for that task! This could be a good starting point: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "codeigniter" }
gnupg broken after power outage Recently I happend to experience a quite unpleasant power outage which caused my system to go down unexpectadly. After power came back the system came back as well and other than a fsck being required all seemed fine. The unedifying surprise hit me when I first tried to access my pass password store - it complained about gpg being broken; so I checked with plain gpg and got this: gpg: failed to create temporary file `/home/meUser/.gnupg/.#lk0x14368b8.meBox.13459': Not a directory gpg: keyblock resource `/home/meUser/.gnupg/secring.gpg': general error gpg: failed to create temporary file `/home/meUser/.gnupg/.#lk0x14379f0.meBox.13459': Not a directory gpg: keyblock resource `/home/meUser/.gnupg/pubring.gpg': general error Does this mean that gnupg is broken on my system now or is this something user specific? I guess my password store is gone, just wondering how to fix gpg to set up a new store.
Your folder `/home/meUser/.gnupg` is gone. You have to restore it from `lost+found` or backup.
stackexchange-unix
{ "answer_score": 2, "question_score": 0, "tags": "gpg" }
Where to save words file for Hangman game on android? I'm trying to make a simple Hangman game for android (without using any libraries like libGdx) and first problem I encountered was this. I don't know where should I put all the words that I made for my game. Should I make it a simple txt file or XML resource file? Should I put that file into new directory or into values directory? I'll need to read that data file and put all words to String array. File will not be modified during game. Any advice would be very welcome.
I think it would be best to make use of android's built in sqlite database. If you would use a text file you would have to parse all of the data into an array then pull out a random record to use for your game. If you use a database you are able to pull a random record from the database with a single query. Sqlite would make more efficient use of your resources.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, android, string, text, android resources" }
Extract regression summary() output in word document in a nicely formated resut Is there a way to extract the summary of a regression model in a nice latex format like the correlation table I attach below? The table should be exported using knitr in word document or at least saved in word document. ![enter image description here]( # install.packages("dplyr") # install.packages("kableExtra") library(dplyr) library(kableExtra) mlm1 <- lm(mpg ~ . , data = mtcars) summary(mlm1) summary(mlm1) %>% kbl(caption="Table 1: Summary Statistics of Financial Well-Being Score by Gender and Education", format= "html", align="r") %>% kable_classic(full_width = F, html_font = "helvetica")
you can use the `broom` package: library(dplyr) library(kableExtra) library(broom) mlm1 <- lm(mpg ~ . , data = mtcars) summary(mlm1) tidy(mlm1) %>% kbl(caption="Table 1: Summary Statistics of Financial Well-Being Score by Gender and Education", format= "html", align="r") %>% kable_classic(full_width = F, html_font = "helvetica") ![enter image description here]( Also, you can reports information about the entire model (i.e. R-squared, AIC, ...) via `broom::glance(mlm1)`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "r, regression, knitr, kable" }
How to set attribute to selected field? I am trying to create a temporary point layer in memory using the following python code. # create layer vl = QgsVectorLayer("Point", "temporary_points", "memory") pr = vl.dataProvider() # add fields pr.addAttributes([QgsField("Id", QVariant.Int), QgsField("Type", QVariant.String), QgsField("size", QVariant.Double)]) # add a feature fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(10,10))) fet.setAttributes(?) pr.addFeatures([fet]) I would like to set attributes to the label "size" and not for all. Is there any way to achieve this?
One solution would to assign `NULL` values for all fields except the field `size`. Searching for index of the `size` field, create an empty list and finally associate the value for the `size` field, this may be done by: ## get the index of the "size" field index = pr.fieldNameIndex("size") ## create an empty list-of-None attrMap = [None] * len(pr.fields()) ## I am assigning the value 10 to the size field attrMap[index] = 10 fet.setAttributes(attrMap)
stackexchange-gis
{ "answer_score": 1, "question_score": 0, "tags": "qgis, python 2.7" }
Who do the brewers of extra strong lager claim their target market is? I'm not sure about other countries, but in the UK we have various brands of 'extra strong' lager beers, the most famous of which is Carlsberg Special Brew (9%), but there are others. The perception a lot of people have is that these beers are favoured by Alcoholics and avoided by everyone else and that the brewers continue to produce the product regardless. Is this actually the case, or is there another, more legitimate market out there for extra strong lager?
You’re absolutely right about the perception. It’s similar in the US for people who buy Steel Reserve and other malt liquors: they’re a cheap means to an end. The reality, though, seems to be that a lot of people like the taste: > 'Of course, the most common question I get asked is: 'Isn't it just winos who drink it?' ' admits Katie Rawll, Carlsberg's senior brand manager responsible for Special Brew. 'But our researches show that the underneath-the-arches brigade accounts for only 2 per cent of its overall drinkers. They're certainly not consuming the volume.' From what I can tell, it’s a special occasion beer for the crowd that isn’t into good beer. They drink cheap lager year round, but if they want to reward themselves, celebrate an occasion, or make a party a bit more interesting, they’ll break out a strong lager. Much like breaking out a bottle of wine, but cheaper (and tastier if you don’t care for wine).
stackexchange-beer
{ "answer_score": 0, "question_score": 0, "tags": "breweries, specialty beers" }
Ransomware in virtual machines. Running Locky for testing security measures We have several binaries of the ransomware Locky. We tried to run it in a virtual machine, which has several storages like Samba, etc. attached, in order to see how the files are going to be encrypted. Basically it starts, spawns its process and then quits for no apparent reason. Nothing happens. What could cause such a behaviour?
Many instances of modern malware are VM-aware to make exactly such examinations more difficult. The malware will attempt to detect if it is running inside a VM as one of its first functions and then simply terminate if that is the case. This will be done prior to the remainder of the payload being decrypted in order to expose as little as possible to forensics examiners. I don't know about Locky in particular, but it would not be surprising in the least if Locky's authors were using this very common tactic. See here for a good overview of this phenomenon: <
stackexchange-security
{ "answer_score": 5, "question_score": 5, "tags": "ransomware" }
Optional argument to \item in enumitem list I'm trying to set up a list environment for typesetting a problem set. I'd like to be able to input something like the following: \begin{pset} \item First solution. \item[2.2] Second solution. \end{pset} and have it come out as: Problem 1. First solution. Problem 2 (2.2). Second solution with the optional argument to `\item` being typeset in parentheses if it's present. I assume I should be able to `\renewcommand{\makelabel}` somehow, but I can't figure out how to do it. I can't get anything like the following to work: \newcommand{\makepsetlabel}[1]{some if/then involving #1, checking if empty} \newlist{pset}{enumerate}{1} \setlist[pset]{ before={\renewcommand\makelabel[1]{\makepsetlabel{##1}} } What's the right way?
I would use a different command instead of `\item`: \documentclass{article} \usepackage{enumitem} \newlist{pset}{enumerate}{1} \setlist[pset]{ label=Problem \arabic*\protect\thispitem, ref=\arabic*, align=left } \newcommand{\pitem}[1][]{% \if\relax\detokenize{#1}\relax \def\thispitem{.}% \else \def\thispitem{ (#1).}% \fi \item} \begin{document} \begin{pset} \pitem First \pitem[2.2] Second \end{pset} \end{document} In the label I add a command `\thispitem` (with `\protect` so `enumitem` doesn't interpret it when setting up the environment). Then `\pitem` examines the presence of an optional argument and acts consequently: if none is specified, it just prints a period, otherwise a space, the parenthesized argument and the period. !enter image description here
stackexchange-tex
{ "answer_score": 6, "question_score": 6, "tags": "lists, enumitem" }
Create a sequence of sequences of different lengths I have to create a sequence of large number (> 10,000) of sequences of different lengths. I only know the lengths of these sequences in a vector form. length_v <- c(2,3,4,4,2,6,11,75...................) Each sequence starts from 1 and moves forward in steps of 1. And in the final sequence (combined one), each sequence has to appear one after the other, they can't be jumbled up. A small demonstrating example is below: I have say 4 sequences of length 2, 3, 4, 6 respectively. s1 <- seq(1, 2) # 1,2 s2 <- seq(1, 3) # 1,2,3 s3 <- seq(1, 4) # 1,2,3,4 s4 <- seq(1, 6) # 1,2,3,4,5,6 Final sequence will be final <- c(s1,s2,s3,s4) **# the order has to be this only. No compromise here.** I can't do this with > 10,000 sequences which would be very inefficient. Is there any simpler way of doing this?
We can use `sequence` sequence(length_v) #[1] 1 2 1 2 3 1 2 3 4 1 2 3 4 5 6 ### data length_v <- c(2,3,4,6)
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "r, sequence" }
How to add a force line-break in a draw2d TextFlow How do I add a forced line-break within a draw2d `TextFlow` figure. I build a `IFigure` by adding several different objects. Amongst other things I add a `FlowPage` containing a `TextFlow`. But I could not find an option to force line-breaks at specific locations. Figure fig = new Figure(); fig.setLayoutManager(new FreeformLayout()); FlowPage flow = new FlowPage(); flow.setSize(100,100); TextFlow text = new textFlow("A rather long text without any line-breaks. Lorem Ipsum dolor sit amet."); flow.add(text); fig.add(flow); fig.setSite(100,100);
The common LineFeed character `\n` solved this problem. Inserted somewhere inside the String it forces a line-break.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "swt, line breaks, draw2d, zest, textflow" }
How to read 2nd level sub-directory text file in vb.net I have a little program which is supposed to read text from a text file. The text file is contained in a sub-directory as follows: Customer > Sub-directory 1 > Sub- directory 2 > Text file The code I am using is: Dim ti = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Customers\" & TextBox1.Text)) Dim du As String = Path.Combine(ti.FullName, TextBox2.Text, TextBox3.Text + ".txt") Dim ObjectReader As New System.IO.StreamReader(du) Where: * TextBox1 = Name of the Customer * TextBox2 = Name of product * TextBox3 = Reference The error I am getting is: “Could not find a part of the path 'C:\Users\Mark\Desktop\Customers\Biscuits\Reference.txt”. Please how do I rectify this? I am using Visual Basic 2010 Express. Thank you.
Why not try: Dim ti2 = (Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Customers\" & TextBox1.Text)) Dim du = Path.Combine(ti2, TextBox1.Text, TextBox2.Text, TextBox3.Text + ".txt")
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "vb.net, text files" }
What does the 'Special Paste' menu item in Xcode do? In _Xcode_ 6.x, the `Edit -> Paste` and `Edit -> Paste and Preserve Formatting` menu items are self-evident. What does `Edit -> Special Paste` do? On my system it's disabled most of the times.
It's a fairly obscure and _hard to find official documentation covering it_ feature of the OS X pasteboard being capable of storing several presentations of object data on several pasteboards. Basically, you can have multiple items in a pasteboard and they are object oriented - so for image if you have copied an image - there is metadata that you could paste - especially when the image itself isn't passable into a plain text document. When you have a png image in your clipboard, the "special" is renamed: Paste Image Name I presume there are all sorts of items you could have "special" aspects of which to paste into an Xcode document in addition to the name of an image, especially if an UTI is defined for that object: < ![enter image description here](
stackexchange-apple
{ "answer_score": 2, "question_score": 3, "tags": "xcode, copy paste" }
Who adds the page to John's journal in Supernatural? In the episode, Wendigo, we see a page from John Winchester's journal about wendigos and on the opposite page a bunch of random symbols. Later on, in, I believe, Faith, Shadows, or Hell House (when they look up a symbol) they find that symbol on a scrap of paper attached to the page next to the wendigo page. They then look at each other, realising they've found the symbol, and their dad noted it down. Have they been organising the journal? Or is this an error? It seems a fairly rookie mistake to me, if it is such an error.
If you're saying that a piece of paper has been sandwiched between those pages in the journal, rather than a new (bound) page mysteriously appearing, why wouldn't we assume that the brothers just stuffed one there? I imagine that throughout most of the first few seasons they are constantly pouring through that, looking for answers. Even into season 3 or 4, Dean's not certain why his father warned him that he may have to kill Sam. And even without that, his journal is a strong reference for many types of monsters. I think it's fair to conclude that they are, if not organizing it intentionally, then at least they're reading it heavily. Why wouldn't something get stuffed in as a bookmark when they're hurrying off to lord knows where?
stackexchange-scifi
{ "answer_score": 1, "question_score": 4, "tags": "continuity, supernatural" }
How to split filesystem path in Java? If I have a string variable inside one class MainActivity.selectedFilePath which has a value like this /sdcard/images/mr.32.png and I want to print somewhere only the path up to that folder without the filename /sdcard/images/
You can do: File theFile = new File("/sdcard/images/mr.32.png"); String parent = theFile.getParent(); Or (less recommended) String path = "/sdcard/images/mr.32.png"; String parent = path.replaceAll("^(.*)/.*?$","$1"); **See it**
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 5, "tags": "java, string, path" }
Multiple DataFields in Asp CheckBoxList? I'm currently working on a small quiz type app that populates questions and answers from an SQL .mdf database. I've been looking for a control in Visual Studio 2012 that could hold the four answers (preferably `checkboxlist`). The only problem is I have the questions saved in different columns, `answer1`, `answer2` etc. The main question is, **is there a way to populate the`checkboxlist` control with multiple data fields rather than just one?** I tried using four separate `checkboxlists`, but this made validation extremely difficult (Only one option should be selected). Does anyone have any advice or suggest how I could insert the four columns into a control that I could validate? I read online about combining the answers using sql ie. `SELECT Answer1 + ' ' + Answer2`, this works but again I don't know how to integrate this into a combo box list.
there are two easy ways: on the database side you could use: SELECT convert(Char,[Answer1]) FROM [TABLE1] union ALL SELECT convert(char,[Answer2]) FROM [TABLE1] From the application side you could use Merge: dim dt as new datatable dt = SQLdataTable("SELECT [Answer1] FROM [TABLE1]") dt.Merge(SQLdataTable("SELECT [Answer2] FROM [TABLE1]").Copy)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "asp.net, sql, vb.net" }
How to use $routeProvider by javascript? Is there any possibility to call "dashboard.html" without using `<a href="#!dashboard">Some text</a>`? I wont to call "dashboard.html" from javascript. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl : 'loginRegister.html', controller : 'loginRegister' }) .when('/dashboard', { templateUrl : 'dashboard.html', controller : 'dashboard' }) }) app.controller('loginRegister', function($scope, $http) { $scope.showDashboard = function() { // CALL dashboard.html FROM HERE } })
You can use the location function < OR you can use the $window inside AngularJS controller $window.location.href = '/index.html'; It think you will have a complete response here How to redirect to another page using Angular JS?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angularjs, node.js, route provider" }
camel expression - simple expression with header value as an argument I am trying to set camel Header value using below Expression .setHeader("amqName").simple("${amqAddressMap.get(header.userTypeID)}", String.class) where amqAddressMap is an array list and passing header value as argument but it shows invalid expression error is there any way to execute the code without using using processor class
To access ArrayList inside exchange we need to set it as a property setProperty("amqAddressMap", constant(amqAddressMap)) So that we can access it using EL like ${exchangeProperty.amqAddressMap.get(${header.userTypeID})}
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "apache camel" }
Probability over a plane I raise this question following the reading of _Fifty challenging problems in probability with solutions_. One of the problem consists in computing the probability that the quadratic equation $x^2 + 2b x+c=0$ has complex roots. The "natural way" of doing it, is to suppose that the point $(b,c)$ is randomly chosen over a large square centered at the origin, with size $2B$. By following this path, the probability is equal to $0$ when $B$ approaches $+\infty$. However, if you compute the probability over the rectangle $[-\sqrt{B},\sqrt{B}] \times [-B,+B]$, it is equal to $\frac{1}{3}$ and therefore is also the limit when $B$ approaches to $+\infty$. I agree that the first way is "more natural". My question is: how to give more mathematical background to the "natural way"? Thanks for your support on this "not so mathematical question".
well, to find a "natural way" to distribute the coefficients $b,c$ in the plane, you could treat this problem as the special case $n=2$ of a classic problem in random-matrix theory: take an $n\times n$ real matrix $M$ with independent identical normal distributions of the matrix elements $M_{nm}$; what is the probability that all $n$ eigenvalues are real? for $n=2$ we would then identify ${\rm tr}\,M=2b$ and ${\rm det}\,M=c$. this probability is known exactly [1] for any $n$, it equals $2^{-n(n-1)/4}$; so for $n=2$ the probability of real roots is $1/\sqrt{2}$. [1] The circular law and the probability that a random matrix has k real eigenvalues, A. Edelman (1993). (Published in Journal of Multivariate Analysis 60 (1997) 203-232.)
stackexchange-mathoverflow_net_7z
{ "answer_score": 12, "question_score": 10, "tags": "pr.probability" }
how to merge values in a list of map in ruby say I have data structure like List< MAP< String, List>>, I only want to keep the List in map's value, Like, I want to convert following example: > x = [{"key1" => ["list1", "list1"]}, {"key2" => ["list2", "list2"]}, {"key3" => ["list3", "list3"]}] to: > y = [["list1", "list1"], ["list2", "list2"], ["list3", "list3"]] Is there any quick way to do this? Thanks
The quickest thing that comes to mind is to leverage `flat_map`. x = [ { "key1" => ["list1", "list1"] }, { "key2" => ["list2", "list2"] }, { "key3" => ["list3", "list3"] }] y = x.flat_map(&:values) => [["list1", "list1"], ["list2", "list2"], ["list3", "list3"]] `flat_map` is an instance method on Enumerable (< `values` is an instance method on Hash (<
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "arrays, ruby, hashmap" }
When to use 'npm start' and when to use 'ng serve'? > `ng serve` serves an Angular project via a development server > `npm start` runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js. It seems like `ng serve` starts the embedded server whereas `npm start` starts the Node servers. Can someone throw some light on it?
`npm start` will run whatever you have defined for the `start` command of the `scripts` object in your `package.json` file. So if it looks like this: "scripts": { "start": "ng serve" } Then `npm start` will run `ng serve`.
stackexchange-stackoverflow
{ "answer_score": 274, "question_score": 209, "tags": "angular, angular cli" }
Pattern matching cmd command in Net::Telnet I am trying to use cmd command from Net::Telnet @lines = $telnet -> cmd(String =>'show run', Prompt => "/patternA/ $/ /patternB/"); My intention is to capture something like patternA followed by new line(s) and then followed by pattern B. When i am using above cmd command, its giving bad match operator error. What is correct way to achieve it? Thanks!
The `-prompt` inside `cmd` just be a single pattern. You can try creating a multiline pattern, but I can't confirm if that will work: @lines = $telnet->cmd(String => 'show run', Prompt => '/patternA\npatternB $/'); Also, as stated in `Net::Telnet #What To Know Before Using` > When constructing the match operator argument for `prompt()` or `waitfor()`, always use single quotes instead of double quotes to avoid unexpected backslash interpretation (e.g. `'/bash\$ $/'`)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "regex, perl, perl module" }
Java streams: transforming map's values Having an instance of a `Map<A, Set<B>>` where `B` is a POJO with property `Integer price` (among others), how do I elegantly transform this map into a `Map<A, Integer>` where `Integer` denotes the sum of `prices` of a given set, for each key `A`?
You can use stream like this: Map<A, Integer> result = map.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, b -> b.getValue().stream() .mapToInt(B::getPrice) .sum() ));
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "java, dictionary, collections, java 8, stream" }
java thread sync between multiple objects I have a multi-thread multi-object system in which I have a `manager` and multiple `workers`. I need to synchronize the `workers` with the `manager`, like this: `manager` does sth, gives the order to the `workers`, and then let the `workers` run in parallel, independent of each other. When they finished this round, they must wait for the `manager` to give them the new task or order. The `manager` issues the new order only if all the `workers` have finished their previous job. I need to implement it using threads to avoid busy-waiting. However the synchronization is confusing. Any idea?
As @boristhespider suggested, I used CyclicBarrier for both `manager` and `workers`. After each `worker` finishes its task, it calls `barrier.await()`. Then for the `manager`, I check if `barrier.getNumberWaiting()==NumWorkers`. If it's `true`, it updates the tasks of each `worker` and then calls `barrier.await()`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, multithreading, synchronization" }
Importing python file in AWS Cloud9 Lambda I built a simple lambda function using AWS Cloud9. Now I want my lambda to do a bit more. So I created another python file with some functions and saved it in the same directory. myLambdaName - myLambdaName - lambda_function.py - other_function.py In my lambda function, I try to import this ( `import other_function`). If I run the function in the cloud9 terminal, no issues (`python3 lambda_function.py`). But when I go to test the lambda function locally, via AWS Resources tab > Run (local), I get the error that my new python file doesn't exist: > Unable to import module 'myLambdaName/lambda_function': No module named 'other_function' What am I missing here? How do I tell the lambda to pick up the file?
Add your function name to the import path, like import myLambdaName.other_function See screenshot below for example that I've just tested with `ApplicationName` being the application name, while `FunctionName` being the function name. ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, amazon web services, aws lambda, cloud9" }
reporting services expression avoid comma if the field value is null I have the following expression and displays the comma after each column. I do not want show the comma(,) after each field value, if the field value is null. I would appreciate any help. thank you. =Fields!address.Value &", "&Fields!city.Value &", "& Trim(Fields!zipcode.Value) &", "& Fields!state_code.Value
Use a stored procedure. Then you can say: SELECT COALESCE(address + ',', '') + COALESCE(city + ',', '') + ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server 2008, reporting services" }
Best way to create reusable templates for different web sites I have created application using TSQL and libraries. Right now I am generating clients content within libraries (hard-coded html with values) but I would like to keep only db logic there. What is the best way to create reusable .net components which would behave dynamically based on returned DB values? I have not found any normal way how to do it, just copy components across sites manually. Is there a way to create library which will handle templates, which will import data from db logic and return final result into clients side? So I dont have to hardcode html layout into libraries. Thanks.
I think what you're looking for are custom server controls. These are controls that you can put into a separate assembly and use in multiple projects. The learning curve is a bit steep, but it's definitely worth the time to learn. This should get you started: Developing Custom ASP.NET Server Controls
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": ".net, templates" }
Draw Custom View on specific position of screen - Android I have a custom component which consists of 2 text view and 4 toggle buttons. I want to draw this view at some specific position on the screen. How is that possible?
You could wrap the controls in a Layout, e.g. a LinearLayout, and add `android:paddingLeft` and `android:paddingTop` by some pixel value to that Layout to position it how you want. However I would advise that Android Layouts are better designed with relative positions rather than absolute positions. Different devices have different screen sizes, and unless you prohibit it your layouts can be switched between Portrait to Landscape ratios without warning. Layouts designed with relative positioning hold up much better under these conditions. The RelativeLayout container allows tricks like centering controls on the screen, and aligning them relative to other controls. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "android, android layout, android custom view" }
Move Windows hibernation file to a different drive Is it possible to move a Windows hibernation file to a different drive? For instance, if I have Windows installed on `C:`, I want its hibernate file be on `D:`. I wanted to about hibernation file (`hiberfil.sys`), not the page file.
Edit: Now I know how you got those pagefile-related answers! >smile< Sorry, but you can't relocate the HIBERFIL.SYS file to any partition other than the boot partition. This is because it's needed very early in to boot process to resume from hiberation and the boot loader (NTLDR) code, needing to be compact and optimized, doesn't have the ability to load the HIBERFIL.SYS from an arbitrary location. (Think about how much code it would take to do that... accounting for reparse points, software RAID sets, the potential that another installable filesystem driver might be needed besides NTFS. Somebody had to draw the line somewhere... _smile_ ) It would be nice if you could move it, but no such luck. Here's what people consider the "definitive" Microsoft statement on this issue: <
stackexchange-serverfault
{ "answer_score": 17, "question_score": 11, "tags": "windows xp, hibernate" }
ASP.NET getting viewstate in global.asax Is it possible to get at the viewstate in the global.asax file? I am having a problem with viewstate on some clients and I want to log what the viewstate is in the Application_Error event.
The ViewState is posted to the server in a hidden input form-field named "__VIEWSTATE". Therefore, you can probably access the serialized ViewState using this: Request.Form["__VIEWSTATE"] But if you look at the source code of one of your pages (in your browser), you can see that the ViewState is just a (long) encoded string: <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/2RkRMb2dvLnBuZ2Ag0PD..." /> I'm not sure if logging that string will help you find any errors.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "asp.net" }
SQL Select query where column like string with and without spaces I have a SQL Select query in PHP where i need to lookup rows in a table where a column is like a string with and without spaces for example, if my value in the database is `ABC 123` and i search for `ABC123` the query will be $sql = SELECT * from table where col_name LIKE '%ABC123%' "; but i need it to return the row where col_name equals ABC 123 and vice versa, for example, if the database value is `123ABC` and i search for `123 ABC` the query will be $sql = SELECT * from table where col_name LIKE '%123 ABC%' "; and i need it to return the row where col_name equals `123ABC`
$sql = SELECT * from table where REPLACE(col_name,' ','') LIKE '%ABC123%' ";
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "php, sql" }
Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange **Can anyone help me? I'm really bad at programming** Error :Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange * * * ## const xmlhttp = new XMLHttpRequest(); const url = '//url//'; xmlhttp.open('GET', url, true); xmlhttp.send(); xmlhttp.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ const datapoints = JSON.parse(this.responseText); //console.log(datapoints); const labelsboy = datapoints.data.map(function(item){ return item.boy; }); console.log(labelsboy); } } * * * ## file JSON API { "status": true, "row": 2, "data": { "boy": 10, "girl": 15 } }
`map` is an array function but `datapoints.data` is an object. It seems like you are just trying to get one value from the object so you can just access it directly. const labelsboy = datapoints.data.boy; console.log(labelsboy);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "xmlhttprequest, typeerror" }
Changing junction object name I have an existing junction object that is named poorly and is causing a lot of confusion. I wish to change the name of this object and move the changes to production. Can you please let me know what are the things that I have to keep in mind when making this change? I assume I will have to check all the Apex class/triggers/formula fields/validation fields etc for usage, deactivate them and change the name to refer to the new name accordingly. Where can I find all the existing references to the existing junction object? I also assume the code part of this must be tested for more than 75% to get deployed into production? Anything I am missing? Thanks
If it's confusing only for Internal Users then you can just update the Name of the SObject and you don't need to update code for it. If you want to make the name more developer-friendly then you need to update API Name. In order to check where this SObject is referenced, you can just try to rename it and you'll get the error with the list of all references. If you are using some IDE you can try to update everything in one step via API, since you can update references in APEX classes and SObject API Name itself in 1 API call. If not you can use a flow that you described - comment/disable, update, re-enable
stackexchange-salesforce
{ "answer_score": 0, "question_score": 0, "tags": "junction object" }
String as Id for Spring entity I am trying create entity with String id: @Entity @NoArgsConstructor @Getter @Setter public class Account { @Id private String username; private String password; public Account(String username, String password) { this(username, username + "pass"); } public Account(String username, String password) { this.username = username; this.password = password; } } But I can't save this entity: `accounts.save(new Account(name, pass));` Error: `org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save():` What's wrong?
If you want to assign ids automatically on save then you must annotate ID column with `@GeneratedValue(strategy=GenerationType.IDENTITY)`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, spring, spring data jpa" }
Why do Rangers need to win support of 7 of the other 11 clubs in the SPL? > Rangers were bought by Charles Green's consortium last week and it has formed a new company that will have to re-apply for SPL membership. But no date has yet been set for the vote, where Rangers need to win support of 7 of the other 11 clubs. Source: BBC Why do they need 7 votes from the 11 clubs, when 6 would be the majority?
Good question. The Scottish Premier League is still technically made up of twelve teams, including the interim "Club 12". As there are twelve clubs in the league, it is mandated that the majority is 7 and above, although "Club 12" will be a no-vote as it isn't currently certain that the newco Rangers will be that club. For good reading, here's an interesting article on how the other SPL clubs might vote.
stackexchange-sports
{ "answer_score": 5, "question_score": 9, "tags": "football" }
How do I stop TFS constantly trying to add nuget packages folder? Is there some sort of .gitignore for TFS? There's nothing in the context menus.
There has been a very detailed answer to solve this from _Pharylon_ in the question Get TFS to ignore my packages folder Moreover, **it's able to create a`.tfignore` file through file explorer.** You just need to rename a new .txt file with **".tfignore."** (make sure also delete txt) It will auto change to the right `.tfignore` file. You can also use the auto automatically generated `.tfignore` file, follow detailed steps from MSDN Link.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "tfs, visual studio 2015" }
How to stop Laravel from starting queues automatically? I use Forge for my laravel builds and I want to use Forge queues to manage my workers. However my problem is that Laravel automatically starts the queues when I restart server and I'm not sure what triggers them to start automatically. Could it be that redis server starts the queues?
I had supervisor setup /etc/supervisor/conf.d/ deleting worker files from the folder helped.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "laravel, forge, laravel queue" }
Transfer speed to network share drops I have an older HP Proliant ML350 G6 server with 1 x Xeon E5504 (2.0 ghz) and 8 gb ram. If I copy a large file (over 2 gb) to it from a windows 10 workstation, after about 1.5 gb the transfer speed drops from 112 megabytes per second to somewhere between 15 and 20 megabytes per second. I also have a Synology DS1815+ on the same network. Copying the same file to the Synology is transferred at about 112 megabytes per second all the way through. I have tried two different OS on the server, tried 3 different hard drives and the problem is identical in all scenarios. Any ideas what the issue might be? Sceendump of transfer speed with drop !Sceendump of transfer speed with drop
A cache drive on the server fixed it.. i forgot i was transfering from an ssd to a mechanical drive .. the buffer must have filled up is my guess
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "network share, hp proliant, file transfer, network speed" }
Pgadmin-insert rows into table from other table by procedure I have already created table `f_table` with columns `quarter` and `sums`. Showing error as: ERROR: syntax error at or near "SELECT". Function: CREATE OR REPLACE FUNCTION func4() RETURNS void AS $BODY$ BEGIN insert into f_table values ( SELECT tab1.quarter, sum(tab2.tot) FROM tab1 INNER JOIN tab2 ON tab1_key=tab2_key GROUP BY(tab1.quarter) order by (quarter) asc distributed by(quarter)); END; $BODY$ LANGUAGE plpgsql VOLATILE; Can anyone help me with this? Thanks in advance.
Its is solved no need of distributed by because its not a table creation, its jus an insert. after removing distributed by its working fine. Thanks for ur responses.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, postgresql, stored procedures" }
How can I access XMLSitemap links from external PHP script? I have an external PHP script that does a lot of back end processing for a website. I need for this PHP script to query, insert, and delete various links from the XML Sitemap. I want to use XMLSitemap's API instead of raw SQL so any additional functionality that needs to happen on inserts and deletes are called, like any alter hooks, etc. I don't want to bog down the website for this processing, hence why I need to do this from a back-end script.
You'll need to bootstrap the Drupal environment in your PHP script to do this. There are many ways to do this, probably the easiest is Drush's php-script command: drush php-script my_custom_script.php This will let you execute any arbitrary PHP script in a bootstrapped Drupal environment. Once you have your script running your Drupal environment, you can utilize the XMLSitemap API functions for all your CRUD operations.
stackexchange-drupal
{ "answer_score": 2, "question_score": 2, "tags": "7, xml sitemap" }
How to replace dialog header in jQuery UI? I want to remove dialog header in jQuery UI and add my close button. Close button is image, when user click image, dialog'll be closed. This my snippet: $("#dialog-model").dialog({ create: function (event, ui) { jQuery(".ui-dialog-titlebar").hide(); $("#dialog-model").css({ 'font-family': 'Helvetica', 'padding': '0', 'font-size': '12px' }); }, height: 500, width: 900, modal: true, }); I try to add image in scipt but it doesn't work
# UPDATE ANSWER Try this one? DEMO < Create a custom close button. $(document).ready(function(){ $("#dialog-model").dialog({ create: function (event, ui) { $('.ui-dialog-titlebar').css({'background':'none','border':'none'}); $(".ui-dialog-titlebar").html('<a href="#" role="button"><span class="myCloseIcon">close</span></a>'); $("#dialog-model").css({ 'font-family': 'Helvetica', 'padding': '0', 'font-size': '12px' }); }, width: 250, height: 150, modal: true, resizable: false }); $("span.myCloseIcon").click(function() { $( "#dialog-model" ).dialog( "close" ); }); });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "jquery, jquery ui" }
Law of total probability for conditional distributions For three random variables $X,Y,Z$, is it true that $$ p(Z \vert Y) = \sum_X p(X) p(Z \vert X, Y) $$ I believe this is untrue because you have to condition on the same events to meaningfully perform operations between distributions, but the following should hold? $$ p(Z \vert Y) = \sum_X p(X \vert Y) p(Z \vert X, Y) $$
The first is not correct in general, but the second one is. For the first one to be correct, you should have independence between $X$ and $Y$.
stackexchange-stats
{ "answer_score": 2, "question_score": 1, "tags": "probability" }
Error to deploy a silverlight application in IIS6: Invalid or malformed application: Check manifest Folks, I deploy a silverlight application on windows server 2008 (IIS7) and ran ok, no errors. I put this same application on another server with windows server 2003, IIS 6, with the mime types configured, asp.net 4, etc. But when I try to run it I get the error: Invalid or malformed application: Check manifest I checked on google, but the attempts were unsuccessful. Anyone out there have any idea what might be?
these links might help you < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "silverlight, deployment" }
String index out of range in Python So I am writing code to read a file and print out the content as (fileID, sentenceID, wordID, word). It keeps telling me `for word in line[0].split('ZZ'): IndexError: string index out of range`. So how do I fix this? Thanks. lineCount = 0 wordCount = 0 for line in file[0].split('ZZ'): lineCount +=1 for word in line[0].split('ZZ'): wordCount +=1 print fileNumber + '|' + str(lineCount) + '|' + str(wordCount) + word +'\n'
try with `for word in line.split('ZZ'):` instead of `for word in line[0].split('ZZ'):`. This `file[0].split('ZZ'):` returns list of strings, so `line` is one of those strings. `line.split('ZZ')` will return list of strings once again, but now `word` will be one of those strings. **EDIT** Here is example for your question in comment: line = "one-two threeZZfour five-six seven eight nineZZten" for word in line.split('ZZ') print word output>> one-two three four five-six seven eight nine ten for word in line.split('-') print word output>> one two threeZZfour five six seven eight nineZZten for word in line.split()# or split(' ') print word output>> one-two threeZZfour five-six seven eight nineZZten
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python, python 2.7, text extraction" }
How to put multiple textbox value into an array by a for loop I got several textbox object on designer interface, let's say txtF1_ZHTW, txtF2_ZHTW, txtF3_ZHTW. How to put the value of this 3 textbox into an array by a for loop? The syntax I used for now is the worst way: fieldName_TW[0] = txtF1_ZHTW.Text; fieldName_TW[1] = txtF2_ZHTW.Text; For what I want to proceed is something like... for(i=0;i<3;i++) { fieldName_TW[i] = txtF[i+1]_ZHTW.Text; } So, how can I modify the code to use a for loop to enter the value of multiple textbox to an array?
Put your textboxes in a collection, such as a `List<TextBox>`, so you can iterate it. var texboxes = new List<TextBox>() { txtF1_ZHTW, txtF2_ZHTW }; // ... foreach(var textbox in textboxes) // Assumes that fieldName_TW is large enough fieldName_TW[i] = textbox.Text
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, arrays, textbox" }
how to remove all [number] in text file (from wikipedia)? I am trying to remove all `[Numbers]` in a file. I am using notepad++. content of my file is from Wikipedia. for example : Part of the content of my file: * * * General features include: **[6]** Tabbed document interface **[7]** Source code editing features include: **[6]** Notepad++ supports syntax highlighting and code folding for over 50 programming, scripting, and markup languages. **[6][8]** how can I do ?
Do a regex replace Find: `\[[0-9]+\]` Replace with nothing
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "regex, notepad++" }
Why is a test statistic called a test statistic? I'm sure this is really basic -- but I want to understand the origins (etymology) of the term "test statistic".
I think this is pretty straightforward, at least at one level. "Test" because it's the result of a test, "statistic" because it comes from a sample, not a population. (A mnemonic: Populations have Parameters; Samples have Statistics). Or did you want something on the origin of the term "statistic"?
stackexchange-stats
{ "answer_score": 6, "question_score": 3, "tags": "hypothesis testing, terminology" }
Showing images along with their names in listview I am using C#.net with 3.5 frame work. I have a form having a listview and imagelist controls. i am adding images from a folder to imagelist and then from imagelist to listview. This is working fine and show images, However how can i show the image names too.
I guess you want to set the View property: `ListView.LargeIcon` for instance displays the image with a label below it. Also, if you're going to work with ListViews, I'd suggest you look into ObjectListView, it's very flexible and allows you to develop more beautiful listview controls.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, winforms, listview" }
Angular 2: How to provide interpolation with [routerLink] I have routing defined in routing.ts file in this way. const routesapp: Routes= [ {path:'user/id', component:UserComponent} ]; export const:routing ModuleWithProviders = RouterModule.forRoot(routesapp, {useHash:true}); and in HTML <li class ="Some class"> <a href= "#/user/{{id}}"> Link </a> </li> How do I convert this to work with [routerLink]? From previous posts I learnt that we cannot add interpolation with [routerLink], i.e [routerLink] = ['user/{{id}}'] I want to add interpolation in HTML only and I cannot add it in routing file. Also, How to override useHash of routing file in HTML?
try this <li class ="Some class"> <a [routerLink]="['user', idVariable]">Link </a> </li>
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 17, "tags": "angular, angular2 routing" }
retriving master key and salt from SIP SDP with Convert.FromBase64String I have an application to decrypt media packets. it require me to provide Master key and salt key. my SDP provide me (after negotiation ended) with AES_CM_128_HMAC_SHA1_80 inline:Fu8vxnU4x1fcCzbhNrtDV0eq4RnaK4n2/jarOigZ according to SDP rfc the string after the "inline:" is: "concatenated master key and salt, base64 encoded" when the master key is X bytes and the salt is Y bytes. I am tyring : byte[] masterAndSalt = Convert.FromBase64String("Fu8vxnU4x1fcCzbhNrtDV0eq4RnaK4n2/jarOigZ") and then get the first x bytes to the master and the other Y for salt. but my app says my keys are wrong, i don't understand - should i use some else than Convert.FromBase64String ?
OK, i got it right. on AES_CM_128_HMAC_SHA1_80 cipher the Master key is 16 byte, and the salt is 14 byte long. what should be done is to use Convert.FromBase64String on the key, which produced a 30 byte long array, take the first 16 as master, and the last 14 as salt. the decryption algorithm should produce the session key and salt from it (along with other info).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "encryption, base64, aes, sdp" }
Morita therapy - does it have a western counterpart? I have recently read interesting article about Morita therapy. I have a hard time finding articles,books or research on this subject, and how it works in the West since this therapy was developed and mostly applied in Japan. What is interesting about it : this therapy (or just Morita's philosophy) doesn't try to change person's feelings of fear/anxiety. It teaches person to understand his/her feelings and live with them. Doing things that need to be done despite fear/anxiety. Does Morita's idea have western counterpart? Any free reading on it ? (something I don't have to buy) And is there any research paper on it that is reliable and accessible? Any idea of something similar is welcome. :)
Reminds me a bit of existential therapy and humanistic psychology in general. Unconditional positive regard and motivational interviewing both insist on approaching undesirable feelings from the client's perspective without imposing fixes or changes on the person through pressure or blunt confrontationality. Existential theory even presumes major, inevitable negativity in life experience for which no individual _could_ be blamed. There are plenty of terrible realities for every individual to face and accept in the process of adjustment and maturation. The individual must do this freely, idiosyncratically, and earnestly for oneself, or so the theory goes. Focus is not on eliminating negativity but on finding meaning amidst it. I hope these Wikipedia pages give you plenty to read for starters, but I can try to find more if you like.
stackexchange-cogsci
{ "answer_score": 4, "question_score": 4, "tags": "clinical psychology, cross cultural psychology, anxiety, fear" }
Nested TinyMCE modal input controls not getting focused After failing to load 5 TinyMCE editors on one page, I decided to create "edit" buttons which then loads the editor inside a modal. <Modal.Body> <FormGroup className="mb-3"> <Editor name="text" label="Text" /> //My TinyMCE object </FormGroup> </Modal.Body> But when any of the TinyMCE features opens a modal of its own, none of its input controls are getting focused. Tried setting autoFocus to false on the Bootstrap Modal but still no use. I found this has been addressed in the past, as in this question. However, like the same, most responses are tailored for jQuery, which I'm not familiar with. Any React based solution?
Assuming you're using the react-bootstrap library, then you'd need to set the `enforceFocus` prop to `false` (instead of `autoFocus`). See < The reason this is needed is that bootstrap will try to ensure that the focus never leaves the modal dialog for accessibility purposes. This is normally fine, however in this case it conflicts with TinyMCE which itself needs to open new modal dialogs and focus the content inside (as you've already alluded to).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "reactjs, tinymce, bootstrap modal" }
Is there any benefit from installing 2 resistors in parallel instead of 1 resistor? I'm restoring an old tube radio. When looking into the schematics I noticed that they drew 2 resistors in parallel instead of 1 resistor, between the power transformer and the rectifier tube. Is there any benefit from installing 2 parallel resistors instead one resistor?
Two resistors have an increased ability to dissipate power/heat, up to twice the time one can, when mounted with enough space between them. Also for a few applications it is easier to find two standard value resistors that together form one resistor value that is not among the standards you already have in your BOM (or are available). Lastly for the gray beard hand chosen value resistor, it might have a higher yield to use two that are slightly off than to find the one that matches perfectly.
stackexchange-electronics
{ "answer_score": 17, "question_score": 11, "tags": "resistors, vacuum tube" }