INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What molecules can be eliminated in condensation polymerization? Is there any specific rule to what kind of molecules can be eliminated in condensation polymerization? From Wikipedia I found that "small molecules" like $\ce{H2O}$ can be eliminated. Is there a more accurate criteria to what these "small moecules" are?
As an abstract answer, to me it would be whatever is commercially viable to manufacture and sell. Commercial polymerisation processes eliminate ethylene glycol (in the manufacture of PET) which is probably recycled, methanol in transesterification reactions, ethene or propene in metathesis type, phenol (recycled) in the use of diphenylcarbonate with bisphenol A, etc. In home applications, acetoxysilicone sealant gives off acetic acid. So, anecdotally, it seems "simple" molecules of MW around 100 or less might meet your criteria.
stackexchange-chemistry
{ "answer_score": 2, "question_score": 1, "tags": "organic chemistry, polymers" }
Drupal 7. Hide exposed form after ajax submit How hide filter exposed form after success send? Form in block and work with ajax. Help pleace.
**Resolved! :)** (function ($) { Drupal.behaviors.betterExposedFilters = { attach: function(context, settings) { $(document).ajaxComplete(function(event, jqXHR, settings) { $('.view-filters').hide(); }); }} })(jQuery); Thanks Matoeil!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ajax, drupal 7, view, drupal exposed filter" }
NSUserDefaults dont persist even when using synchronize My `NSUserDefaults` work fine while the app is running or minimized. But if I kill the app and restart it, the object returned is `null`. Code: colorDefault = [NSUserDefaults standardUserDefaults]; [colorDefault setObject:myColor2 forKey:@"fieldKey"]; NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:myColor2, @"fieldKey", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; //[[NSUserDefaults standardUserDefaults] synchronize]; [colorDefault synchronize]; I call `[[NSUserDefaults standardUserDefaults] synchronize]` in my `applicationDidEnterBackground` and in the `applicationWillTerminate`, with no success. I _NSLogged_ both of those methods, and when I kill the app, I notice only the `DidEnterBackground` is being called.. Thanks for ANY help!
Mmmm... I think your code should be simpler. This is what I do to write NSUserDefault and to retrieve it: // write [[NSUserDefaults standardUserDefaults] setObject:@"aString" forKey:@"aKey"]; // read [[NSUserDefaults standardUserDefaults] objectForKey:@"aKey"]; setObject is not the only option: setBool, setFloat, setInteger and on the other side boolForKey, floatForKey, integerForKey are good as well. Do not forget to set `Settings.bundle` and `aKey` in your project: <dict> <key>Key</key> <string>aKey</string> <key>DefaultValue</key> <false/> </dict> Hope this helps...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, xcode, nsuserdefaults, synchronize" }
Как найти страницу где есть запись при OFFSET и LIMIT (постраничная навигация)? Есть таблица данных где выводятся записи по 10 строк на страницу (постраничная навигация). Нужно, зная id конкретной записи, узнать на какой странице находится эта запись. и запросить её. То есть какой OFFSET выставить чтобы эта запись точно попала в запрос. // При таком запросе получаю записи со смещением. Это страница 3 SELECT id,name FROM table1 ORDER BY DESC OFFSET 20 LIMIT 10 Вот как узнать номер страницы или смещения OFFSET для id=17 где в запрос попадёт эта запись с id 17? Запрос может быть с разными условиями WHERE.
Вижу два способа. Пусть `X` \- поле, по которому идет сортировка, тогда количество записей с X большими, чем в искомой записи, деленное на размер страницы даст нам номер этой страницы: SELECT count(1) / 10 FROM table1 WHERE X > (select X from Table1 where id=17) Или нумеруем все записи в нужном порядке сортировки и получаем номер требуемой записи, который так же делим на размер страницы select rn / 10 FROM ( SELECT id, row_number() over(OREDER BY X DESC) RN FROM Table1 .... ) X where id=17 Первый способ представляется мне более быстрым, при наличии индекса по полю `X`.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "postgresql" }
How disable IPv6 on Fedora Silverblue? I tried to create a file **/etc/sysctl.d/10-network-override.conf** then **sudo systemctl daemon-reload** net.ipv6.conf.all.disable_ipv6=1 net.ipv6.conf.default.disable_ipv6=1 net.ipv6.conf.lo.disable_ipv6=1 net.ipv6.conf.wls1.disable_ipv6=1 Also, tried creating **/etc/systemd/network/20-IpV6-disable.network** then **systemctl restart systemd-networkd** [Match] Name=wls1 [Network] DHCP=ipv4 LinkLocalAddressing=ipv4 IPv6AcceptRA=no Both solutions work temporarily and after rebooting I get IPv6 again.
I use just these two settings which are enough: net.ipv6.conf.all.disable_ipv6 = 1 net.ipv6.conf.default.disable_ipv6 = 1 You will continue to see IPv6 addresses assigned to your interfaces but that's OK because they are Link Local addresses and can only be used within your LAN. These addresses are not routable. If you want to go even further, you can simply disable the ipv6 kernel module, create a file e.g. `/etc/modprobe.d/disable-ipv6.conf` with this: blacklist ipv6 and reboot.
stackexchange-unix
{ "answer_score": 0, "question_score": 1, "tags": "fedora, systemd, systemd networkd" }
Create single object using two array I have two arrays of same length ids = [123, 456, 789, ...., 999]; names = ['foo', 'bar', ... , 'zzz']; I want to create an array like [ {id: 123, name: 'foo'}, {id: 123, name: 'bar'}, ..., {id: 999, name: 'zzz'} ] I am trying to avoid `forEach` if possible. Any suggestions?
Is `map` okay? ids = [123, 456, 789, 999]; names = ['foo', 'bar', 'baz', 'zzz']; result = ids.map(function(_, i) { return {id: ids[i], name: names[i]} }); console.log(result)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript" }
What is the web server of Meteor JS? I don't really understand what is the name of the web server from `meteor.js`. Because in `PHP` for example, by default, we are using `ngix` (or apache). In `python`, we are using `werkzeug` (it's not really a web server in this case, but a library but the objective is similar). In `rails`, we are using by default `Puma`. But impossible to know what we're using in Meteor. We don't have a specific web server ? we are only using Meteor ? I know the fact that `meteor` is a client/server framework built on top of `nodejs` (on the server side), but i don't find more precise detail about the name or the type of web server.
Node can serve up HTML pages, so unless you have some other situation going, it's the web server. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, meteor" }
How do I use Yarn's `.pnp.js` file? Using Yarn 2, the default installation method creates a `.pnp.js` file (Plug'n'Play) instead of a `node_modules` directory. How do I use this file to run my Node application?
To run a Node application with Yarn's Plug'n'Play you must preload the `.pnp.js` file using the `--require` flag. node --require ./.pnp.js foo.js **Note** : Make sure that the `--require` path starts with `./` or `../`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "yarnpkg, yarn v2" }
struts 1.0 logic tag choice - if/else logic What I have is a dropdown list. When the user selects a certain option, where each option represents a specific String on the Java server side. Right now, the Java server side able to check which option is selected, and the number to correspond. At the moment, I am able to output the value in Java backend, not on the JSP page. Is there an if/else tag for Struts 1.0? I am not sure which logic tag is the best to pass a Java value for frontend processing: **JSP page** if(value = 666) this textbox is readonly else this textbox row is active My research so far: Looking at `logic:equal`, it seems to pass a value on the JSP page using taglibs like below. This doesn't work for me, because I want to pass the value _FROM_ a Java class on the server side. <logic:equal name="name" property="name" value="<%= theNumber %>" >
<c:choose> <c:when test="${the number}"> Both are equal. </c:when> <c:otherwise> Both are not equal. </c:otherwise> </c:choose> this is jstl tag you need to use <%@taglib prefix="c" uri=" %>
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, jsp, struts" }
How do I get the value from a class property in Objective-C? I want to get variable value from an objective-c class, using reflection. company.h looks like @interface Company : NSObject { } @property (nonatomic, retain) NSString* phone; - (NSString*) getPropertyValueByName: (NSString*) paramName; company.m looks like @implementation Company @synthesize phone; - (NSString*) getPropertyValueByName: (NSString*) paramName { id me = self; value = [me objectForKey: paramName]; return value; } @end I am using this like: Company* comp = [Company new]; comp.phone = @"+30123456"; NSString* phone = comp.getPropertyValueByName(@"phone"); What I am getting is an exception: -[Company objectForKey:]: unrecognized selector sent to instance
That should be valueForKey instead of objectForKey. objectForKey is an NSDictionary instance method. Besides that there's a potentional mistake in your code. Your return type in the above method is string but you don't cast it to NSString before returning.Even if you're sure that it'll always return a string it's good practice to avoid any doubts. And when declaring an NSString property you should copy it rather than retaining it. And, what's the point in declaring a "me" variable if you can easily say: [self valueForkey:paramName];
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 10, "tags": "iphone, objective c, cocoa touch, reflection" }
Solve an ODE system There is a system $\dot x = x, \dot y = x+2y$. I got this answers $x=C_1\cdot e^t$ and $y=C_1\cdot e^{2t}-x/2-1/4$ but I find it wrong somehow. Will you explain the full solution to that?
$$\dot x = x, \\\ \dot y = x+2y$$ I got this: $$ x'=x \implies x=c_1e^t$$ And: $$y' = x+2y$$ $$y' = c_1e^t+2y$$ $$y'-2y=c_1e^t$$ $$(ye^{-2t})'=c_1e^{-t}$$ Integrate both sides: $$ye^{-2t}=-c_1e^{-t}+c_2$$ $$y=-{c_1}e^t+c_2e^{2t}$$ It's hard to tell you what mistakes you made without posting your full attempt.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "ordinary differential equations, systems of equations" }
Why I am getting an option to start a bounty for a question with accepted answer? Please check screen shot below: ! I am not the owner of the question and the owner has accepted an answer still when I am viewing this question **I am getting an option to start a bounty.** I am confused: 1. Why bounty option is there when answer has been accepted? 2. Why it showing to me as I am not the owner of the question? (Is it something related to points I have? If yes then why only on this question?)
Yes, bounties are not attached to accepted answers anymore, and anybody with enough reputation can throw bounties to any questions older than 2 days. > <
stackexchange-meta
{ "answer_score": 6, "question_score": 6, "tags": "support, status bydesign, bounties" }
Subfield of rational function fields Let $k\subset F\subseteq k(x_{1},x_{2},...,x_{n})$ where $k$ and $F$ are the fields and $x_{1},x_{2},...,x_{n}$ are transcendental over $k$. Can we express $F$ in terms of or function of $x_{1},x_{2},...,x_{n}$ ?. Thanks
The field extension $k(x_1,...,x_n)/k$ is finitely generated, hence so is $F/k$ (see $\S 11.4$ of these notes). That is, there are finitely many rational functions $f_1(x_1,\ldots,x_n),\ldots,f_m(x_1,\ldots,x_n)$ such that $F = k(f_1,\ldots,f_m)$. When $n = 1$ it is further the case that we may always take $m = 1$, and then $F = k(f)$ is again a rational function field: **Luroth's Theorem**. For $n > 1$ a subfield of a rational function field need not be rational, and I can't think of anything nice to say about the extension $F/k$ except that it is finitely generated -- at least not without bringing in some fairly sophisticated algebraic geometry.
stackexchange-math
{ "answer_score": 7, "question_score": 4, "tags": "field theory" }
Motorola EMDK sdk, barcode2 QRCode scanning returns E_SCN_BUFFERTOOSMALL I’m testing EMDK .Net SDK 2.5 on a ES400 device and have managed to get basic barcode scanning to work. When I try to scan QRCode’s, I allways get E_SCN_BUFFERTOOSMALL. The ScanData.Buffersize is 112 which probably is to small, but **where can I increase the buffersize**? The QRCode decoder is enabled. If I try the same QRCode with the DataWedge on the device, everything works fine. I have checked help files, samples etc without any luck. Any help or suggestions would be highly appreciated. Cheers!
I found a workaround!! By using **Symbol.Barcode2** assembly, instead of the **Symbol.Barcode2.DesingCF35** assembly, I am able to control the buffersize with the statement MyScanner.Config.ScanDataSize = 256; If you need more control, it looks as if you are better off looking at the “CS_Barcode2Sample” project as an inspiration instead of the “Barcode2ControlSample”. Good luck..
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "compact framework, barcode, motorola emdk" }
fatal: could not read Username for 'https://github.com': Invalid argument I am trying to deploy my react app on git pages and i get the following error. bash: /dev/tty: No such device or address error: failed to execute prompt script (exit code 1) fatal: could not read Username for '< Invalid argument I tried to setting origin url with my username and password but that does not help. Any pointer would be helpful.
It could be solved by adding user name in {project}/.git/config file. Just like this : [remote "origin"] url = ` Please note the single quotation and remove <> in original command. Alternatively, you should try to set global user name & pwd first
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "reactjs, github, npm, github pages" }
Confusion with $\lim_{x\to \infty} (e^x+x)^{\frac{1}{x}}$ I have this limit: $$\lim_{x\to \infty} (e^x+x)^{\frac{1}{x}}$$ At first I was stumped but then decided to use L'hospitals rule and logs so it turns to: $$\lim_{x\to \infty} \frac{\ln(e^x+x)}{x}$$ Then differentiating it twice turns to: $$\lim_{x\to \infty} \frac{e^x}{e^x+1}$$ But then this means $\lim_{x\to \infty} \frac{e^x}{e^x+1}=1$, but I know from trying values on my calculator that it should be equal to $e$. Am I wrong or am I getting mixed up with the L'Hospitals rule? Thank you!
... just a silly mistake. If $\ln L=1$ , then what do you think $L$ should be equal to?
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "limits" }
The first upvote on my answer is not recorded in achievements Prove constant exists such that a function is uniformly continuous For my answer to this question, I got an upvote after a few minutes. However I didn't see it until I checked because it didn't show up in the achievements. I did get reputation for it. The second upvote is recorded as one upvote on the achievements, +10.
Our rep recalculation has completed but our aggregator is still working through a big queue of items. The aggregator is what mirrors things to the network store and that's what the top bar is based on. Thanks for your patience!
stackexchange-meta
{ "answer_score": 11, "question_score": 3, "tags": "bug, achievements dialog" }
RPC Framework in C++ utilizing ZeroMQ I need to write a client-server application in C++ using ZeroMQ push-pull socket pattern. The client has to make RPC calls to the functions specified in the server interface. I wonder if there is an open source and commercially usable library/framework for this purpose primarily in C++. I made some googling and there seem to be things written in python but I prefer something in C++ that comes handy with ZeroMQ if possible. Any suggestion/guidance is appreciated. Thanks.
Google protobuf provides to generate client method wrappers and stubs for RPC services usable in C++. The user must explicitly define the transport mechanism used for this, ZeroMQ would be an appropriate choice for implementation IMHO (So this is other way round as you have asked, but makes no difference in the end). There's another SO question that provides some more details about the available alternatives: 'Which rpc/messaging framework would best fit this case?'
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "c++, client server, rpc, zeromq" }
How to debug Google Glass GDK application? It is easy to debug Android applications as most of them launch an activity and keeping breakpoint is all it takes. How to debug a GDK based google glass app as the service is triggered on voice and does not explictly launch an activity on install?
Same way any Android service is debugged. Just add the below line anywhere in the code and any breakpoint in the code after this can be used to stop the run. android.os.Debug.waitForDebugger(); Thanks to this - <
stackexchange-stackoverflow
{ "answer_score": 25, "question_score": 12, "tags": "android, google glass, google gdk" }
How do I pass literal variable templates to jq from within Make? I'm trying to use jq within a Makefile to generate a json file. Here is a sample Makefile foo.json: jq -n --arg x "bar" '{"foo": "$$x"}' > foo.json @cat foo.json @rm foo.json When I run this with GNU Make v4.3 and jq v1.6 I get the following make jq -n --arg x "bar" '{"foo": "$x"}' > foo.json { "foo": "$x" } Notice that `$x` shows up literally and doesn't get interpolated by jq. How do I achieve the following... make jq -n --arg x "bar" '{"foo": "$x"}' > foo.json { "foo": "bar" }
You simply don't need to wrap your variable in quotes: jq -n --arg x "bar" '{foo: $x}' Or use string interpolation: jq -n --arg x "bar" '{foo: "\($x)"}'
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "bash, makefile, interpolation, jq" }
Updating ProgressMonitor from non-plugin library in Eclipse I have a scenario where I have a Java project (`MyLibrary`), which is supposed to be a "pure" Java project with no reference to Eclipse SDK. I have another project (`MyPlugin`) which is a Plugin project and it uses `MyLibrary`. When calling `MyLibrary`, the plugin project utilises a `ProgressMonitor`. I am unable to pass the object from MyPlugin to MyLibrary as the latter doesn't have any reference to Eclipse. How can I update the progress from `MyLibrary`?
Add a progress monitor interface to your MyLibrary (`IMyProgressMonitor` for example) that the methods in your library expect to receive. Your plugin can then implement `IMyProgressMonitor` and just call the corresponding methods on the `IProgressMonitor` you have from Eclipse.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, eclipse, progress bar" }
How to modify the default location where the python script is trying to write the log There is a python script which I have to run in the background when performing some evaluations. However, the script tries saves some log throughout the process, and since I have to run it in a machine where I don't have sudo rights, the script doesn't get executed. I think the line which causes the problem is: parser.add_option("-L", "--logfile", dest="logfile", default=os.path.join(tempfile.gettempdir(), "log-name.log"), help="log messages to LOGFILE [default: %default]", metavar="LOGFILE") I think I need to change the default location: `default=os.path.join(tempfile.gettempdir(), "log-name.log")`. How do I make it the output path to be a folder within my home directory. There I would not get any issue related to priviledge escalation.
Extract your home directory from the environment: from os.path import expanduser homedir = expanduser("~") parser.add_option("-L", "--logfile", dest="logfile", default=os.path.join(homedir, "log-name.log"), help="log messages to LOGFILE [default: %default]", metavar="LOGFILE") Also, you can try adding a timestamp in your logfile's name so you don't overwrite existing logs by an accident.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, file io, output" }
Meaning of "The whole of eastern North America makes do with but one species" _Makes do with_ means accepting something less satisfactory because there is no alternative. In this case, it makes less sense for me why we use this phrase, and by using _but_ I think it accentuates the meaning of _only_. But I don't get the full meaning of this sentence. Can you tell me why they used the phrase _make do with_? What special meaning does it have, and what is the function of the word _but_?
The easier one first. "But" here means "only." "Make do with" is part of a personification of the eastern North American ecosystem, i.e., a metaphor that regards that ecosystem as a sentient being, one that can recognize what species it contains and can compare itself to other ecosystems. The sister ecosystem in western North America might have ten such species, but the eastern ecosystem just has to get by with nine fewer.
stackexchange-english
{ "answer_score": 2, "question_score": 0, "tags": "vocabulary" }
How to use switch with extern constants? Some code.cpp file contains extern const int v1; extern const int v2; extern const int v3; extern const int v4; int _tmain(int argc, _TCHAR* argv[]) { int aee = v1; switch (aee) { case v1: break; case v2: break; case v3: break; case v4: break; } return } Another file definition.cpp contains const int v1 = 1; const int v2 = 2; const int v3 = 3; const int v4 = 4; When I do compile I got error C2051: case expression not constant However when I remove extern everything is just fine. Is there any way to make it work with extern?
No. `switch` only works with fully defined integral type constants (including enum members and classes that unambiguously cast to integral type). here is a link to an old reference of MSDN, but what is says is still valid. This link that I provided in a comment to another answer explains what optimizations compilers may perform to assembly code. If this was delayed to the linking step, it would not be easily possible. You should therefore use `if`..`else if` in your case.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 12, "tags": "c++, constants, switch statement, extern" }
how to import data in neo4j via sql connection instead of csv? I am using a NEO4J graph database but my application data is stored in MySQL database. My need is I want to import data in NEO4J via SQL connection instead of Csv.
You'll need the APOC Procedures library for this one, and you'll also need the MySQL jdbc driver jar in your plugins folder as well. APOC Procedures Load JDBC documentation APOC Procedures Load JDBC example of usage
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, neo4j, spring data jpa, spring data neo4j" }
Is there any session objects in salesforce ? What i want to do is simply allow some users (non salesforce users) to view some specific records , so i have created for each user an email and a password for authentification purposes and once logged in ( the user enters the email and the pass in a authentification form that i can verify in the database) i need to keep track of this user as he navigates from one page to another in order to display only the records related to him the problem is that ,as far as I know, there is no sessions in salesforce as it is in php for example.So i want to know if there is a way to do that in order to simulate sessions functionality to keep track of these users. any help will be highly appreciated.
No, there is no session information or security for non-Salesforce User users. You should take a look into Community Cloud to meet your requirements. If you continue down your current path then you are likely to be in violation of the Master Subscription Agreement which you agreed to when purchasing your Salesforce licenses.
stackexchange-salesforce
{ "answer_score": 2, "question_score": 2, "tags": "session" }
Activate keyboard on activity in background I implemented an invisible click through activity in my application with setting the theme as: android:theme="@android:style/Theme.Translucent.NoTitleBar" And adding falgs as follows before super.onCreate() in my invisible activity getWindow().addFlags( WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); Now i can interact with the previous activity but the keyboard does not appear when needed (eg. login forms). Is there any possible solution to activate the keyboard while keeping the invisible activity running?
Try this to show the keyboard final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(field, InputMethodManager.SHOW_FORCED); And this to hide final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); You can perform it onResume() of your Activity.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android" }
C++ how to make a prototype of this kind of constructor? I am honestly not sure how to google this even, and as my attempts have failed to do so, can you tell me how to write a prototype of constructor so that I can use it this way? // MyClass.h class Object; class MyClass { Object a; Object b; std::string c; public: MyClass(int, int, std::string&); // I do not know how to declare this properly }; // so that I can write this: MyClass::MyClass(int a, int b, std::string& c = "uninstantialised") : a(a), b(b) { this->c = c; } // so that when I call the constructor like this: Object a(); Object b(); MyClass mc(a, b); // it doesn't produce an error when std::string argument is not specified. Thanks!
Default arguments need to be specified in the declaration, not in the implementation. Furthermore, you should take the string by value, not by reference, and move it into the `MyClass::c` member: public: MyClass(int a, int b, std::string c = "uninstantialised"); // ... MyClass::MyClass(int a, int b, std::string c) : a(a), b(b), c(std::move(c)) { } Taking by value and using `std::move()` is not required, but recommended as it can be more efficient since it avoids copying the string in some cases. I recommend renaming private data members to something that avoids the same name being used for something else. Here, `c` is both the private member as well as the constructor parameter. You should use something different for the members. Like `a_`, `b_` and `c_` for example. Appending an underscore is a popular way to name private data members.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c++, c++11" }
Run a SQL script programmatically > **Possible Duplicate:** > How to execute an .SQL script file using c# How would I programmatically run a SQL script that's in a file on the local disk?
Answer taken from here How to execute an .SQL script file using c# Put the command to execute the sql script into a batch file then run the below code string batchFileName = @"c:\batosql.bat"; string sqlFileName = @"c:\MySqlScripts.sql"; Process proc = new Process(); proc.StartInfo.FileName = batchFileName; proc.StartInfo.Arguments = sqlFileName; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.ErrorDialog = false; proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileName); proc.Start(); proc.WaitForExit(); if ( proc.ExitCode!= 0 ) in the batch file write something like this (sample for sql server) osql -E -i %1
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, c# 4.0" }
Conditional probability of a Poisson process The question is as follows: > Consider a Poisson process $\left \\{ N_{t} \right \\}_{t\geq 0}$ with $\lambda =3$ events per hour. What is the probability that $2$ events occur in the first hour and $2$ events occur in the second hour, given that $4$ events occur in the first $2$ hours? Since this deals with a conditional, I think that we can just view these as uniform and use a binomial distribution. Thus the probability becomes $$\binom{4}{2}\left ( \frac{1}{2} \right )^2\left ( \frac{1}{2} \right )^2=\frac{3}{8}.$$ However, I am not $\textit{too}$ sure about this. I thought the probability was $$\mathbb{P}(N_{1}=2,N_{2}=4 \mid N_{2}=4),$$ but I didn't really know how to go from here. It has been a while since I've dealt with the stuff. Can anyone provide me some feedback? Thanks in advance!
You are right. Verification:\begin{align}\mathbb{P}(N_{1}=2,N_{2}=4 \mid N_{2}=4) &= \mathbb{P}(N_{1}=2,N_{2}-N_1=2 \mid N_{2}=4)\\\ &= \frac{\left(\exp(-\lambda)\frac{\lambda^2}{2!}\right)^2}{\exp(-2\lambda)\frac{(2\lambda)^4}{4!}}\\\ &= \frac{\frac14}{\frac{2^4}{4!}}\\\ &= \frac{3!}{16}\\\ &= \frac{3}{8}\end{align}
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, stochastic processes, poisson process" }
Redirect to absolute URL in Ktor I'm learing how to work with ktor. For a special use case i need to redirect to a different domain from my ktor server. However i cant get it to work rigth now. As an simple example i have an Application.kt import io.ktor.application.* import io.ktor.http.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main(args: Array<String>) { val server = embeddedServer(Netty, port = 8080) { routing { get("/") { call.respondRedirect("www.google.com") }} } } server.start(wait = true) } What i except is that it redirects me to `www.google.com` however it redirects me to `localhost:8080/www.google.com`
Figured it out. You need to set also the protocol. This works call.respondRedirect("
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "kotlin, ktor" }
Getting current project's path How to get absolute path of current active project opened in qtCreator? Is there a way to do it anyway?
Qt only has support for `QDir::currentPath` which will point to where the executable is, as far as I'm aware it's got no hooks to be able to get information from Qt Creator. If your executable is being built in the same directory the project lives in `currentPath()` will return it. EDIT: I'll leave the part where I'm an idiot. Qt Creator has a set of API docs that point to `Core::FileManager::` and another for `Utils`. There's a number of functions in there for returning projects directory, what the current open file is, where it is and so on. There's no explicit 'what is the current absolute path' as far as a quick scan goes, but there's probably a way to query what's currently open. The API docs are here: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "qt, qt creator" }
Restangular: How to read cookie and add to Headers at each query I'm trying to read a token from a cookie and ad it to the headers at each query. I tried this: Restangular.setDefaultHeaders({ Authorization: "Token " + $cookieStore.get('token') }) It works, but the cookie only gets read once. At page load. Then if the value of the cookie changes, it keeps the first value instead of sending the updated value. Any idea how I can read the cookie each time?
You are passing a string, which is evaluated at the time the code is executed. It will never change as you have found out. Instead you will need to pass a function, like this - Restangular.setDefaultHeaders({ Authorization: function() { return "Token " + $cookieStore.get('token'); } }) Which will then be evaluated each time the value is actually used.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "angularjs, http headers, restangular" }
Rewrite field for a specific row? I see that in views the Rewrite the output of this field option affects all rows. Is there a way, using php or something, to rewrite the output of row #4 only?
Put this code in your theme's template.php file: function THEME_preprocess_views_view_fields($vars){ dpm($vars); if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] == 4){ $vars['fields']['title']->content = 'blahblah'; } } Clear the cache. Replace VIEWNAME, DISPLAY and 4 with your appropriate values. Then inspect the $vars['fields'] with dpm output and rewrite the output how you want for the field in question. You may use 'raw' value, but remember to sanitize.
stackexchange-drupal
{ "answer_score": 3, "question_score": 0, "tags": "7, views" }
Horizontal scroll bar in combo box in GXT I am working with GXT to develop a web application. But I am finding difficulty in adding the horizontal scroll bar in combo box. Some of the items of the combo box have large text and I can't see all the text when I see the combo box items. I am not finding a way to set a horizontal scroll bar to the combo box. When I searched in the net I found that we have to implement template for that, but nothing I have found useful. Can you help me in this regard?
Might not be super useful for you, but we found it tough to create a nice xtemplate for h-scroll. Instead we added tooltips for any items that are longer than the combo. I must say that it works nicely.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, gwt, gxt" }
How to inverse the function $\frac13e^x+\ln(3x+1)$ What would be the strategy and final result of inverting the function $$f(x) = \frac{1}{3}e^x+\ln(3x+1)$$
Almost impossible to find a nice formula, but simple to get a graph. Once you have graphed $y=f(x)$ you simply draw the symmetric wrt the line $y=x$. Hope this can be useful ![enter image description here](
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "logarithms, inverse function" }
I got an error when calling kmodes module in python When calling the kmodes package like this: # I have also tried # from kmodes.kmodes import KModes from kmodes.kprototypes import KPrototypes ModuleNotFoundError: No module named 'kmodes'
As suggested by @648trindade, all I had to do was install the package. That's not included in Anaconda by default.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, jupyter notebook" }
Zabbix-proxy on the same server that Zabbix-server I installed a zabbix-server and a zabbix-proxy on the same server, a debian 7.6 But I can't run zabbix-proxy on a passive mode, here is the issue : listener failed: zbx_tcp_listen() fatal error: unable to serve on any address [[-]:10051] Here is my netstat tcp 0 0 0.0.0.0:10050 0.0.0.0:* LISTEN 2142/zabbix_agentd tcp 0 0 0.0.0.0:10051 0.0.0.0:* LISTEN 55825/zabbix_server Because my zabbix-proxy need to be on a passive mode, I can not change his port. Any way to force this changing or any fix to handle this case ? Cheers,
Reconfigure `ListenPort` of Zabbix server and then just use that new Zabbix server port in other settings (agents, proxies, senders, ...). Doc: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "zabbix" }
How to edit a form in Yootheme Zoo? Today someone asked me about a problem with a form on their website. The form is made in Yootheme Zoo. But I can't find the form in the backend. The documentation on Yoothemes website is very narrow on this subject. And Google and Youtube couldn't help me either. According to the Yootheme site it should be simple to create forms, so I guess I'm crazy. But where in this extension can you create and modify forms?
The Form Builder is well hidden in Zoo. When you open Zoo click on right on the cogwheel. Now click on the app (Business Directory in my case). You can edit a form by hovering your mouse over a name (first column) or click on Submission in the next column(Template Layouts).
stackexchange-joomla
{ "answer_score": 1, "question_score": 1, "tags": "zoo" }
Can't get SignalR, CORS and Server-Sent Events to work together I have a SignalR 2.0 server hosted in IIS7 with a javascript client, targeting mainly Chrome browsers at the moment. Without cross-domain, the SignalR transport is Server Sent Events, which works very nicely and is efficient. I added CORS support to the server in the suggested fashion, using Microsoft.Owin.Cors -- that makes the server work with the client cross domain-- however, the SignalR transport is now long-polling; this is going to cause a much higher load on my servers, as the SignalR messages from the server to the client are quite frequent. I'd really like to get Server-Sent Events and CORS support working together, and from my understanding of the protocols I don't see a reason why it can't be done. Any suggestions? Anyone have any luck in the same scenario with other browsers?
SignalR currently doesn't try to establish cross-domain SSE connections by default. This decision was made before browsers had CORS compatible EventSource implementations, so it was seen as wasteful to even attempt establishing cross-domain SSE connections. Starting with SignalR 2.0.3, cross-domain SSE connections will be attempted by default. In the meantime you can manually specify which transports to try and what order to try them in: $.connection.hub.start({transport: ["webSockets", "serverSentEvents", "foreverFrame", "longPolling"]}); <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "google chrome, iis 7, signalr, cors, server sent events" }
How do I mock an IMAP server in Python, despite extreme laziness? I'm curious to know if there is an easy way to mock an IMAP server (a la the `imaplib` module) in Python, _without_ doing a lot of work. Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure. Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would _like_ to create a proper testing environment, but given that it might _not_ grow over time, I don't want to do much work to get the mock server running.
I found it quite easy to write an IMAP server in twisted last time I tried. It comes with support for writing IMAP servers and you have a huge amount of flexibility.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 11, "tags": "python, testing, imap, mocking" }
VB Macro to find duplicates between two ranges of text I don't know any VB so I am not able to even get started on this little macro for someone. What we want to happen is the macro would change the color of any cell in "Column A" if the cell text appears anywhere in "Column B". (Exactly the same text match) The cell values would be text and not numbers. If this can be done easily without a macro that would be great too. Anyone have any examples that I can easily edit to do what we are looking for or able to provide the code that would get me these results? Thanks.
You can do this with conditional formatting and a custom formula. Select column A and on 'Home, click 'Conditional Formatting' and create a new rule. Select 'Use formula to determine which cells to format' In the formula box, type the following formula: =ISNUMBER(MATCH(A1, B:B, 0)) Pick the format you want to have with the `Format...` button and hit `OK` an that should be it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel, vba" }
Find angles in a diagram. How to solve this? I think use umbrella theorum......... ![enter image description here](
![enter image description here]( Initial deductions:- (1):- $\angle BAC = 90^0$. (2):- $\angle MBC = \angle MCB = \angle BAM = = \angle MAC = 45^0$. (3):- (1) & (2) imply KLNA is a square. Next, express separately the ratios $\dfrac {CL}{LB}$ and $\dfrac {CN}{NA}$ in terms of x. Then, equating the two ratios, we have $\dfrac {135 + 0.5x^2}{60} = \dfrac {0.5x^2}{60 - 0.5x^2}$. From which, we get the value of $x^2$. Result follows.
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "geometry" }
Javascript Array join() returning blank string Sorry, I am new to javascript and i'm just trying to get my feet wet. I have used join()in the past without problems, but for some reason this join seems to return a blank string. The information in myArray seems to be formatted correctly. any help would be much appreciated. Thanks! function titleCase(str) { var splitArray = str.split(" "); var myArray = []; var joinArray = myArray.join(' '); for (var i in splitArray) { myArray.push(splitArray[i].charAt(0).toUpperCase() + splitArray[i].slice(1).toLowerCase()); } return joinArray; } titleCase("capitalize the first letter of each word in this string");
You're defining joinArray before myArray has been filled. Try moving var joinArray = myArray.join(' '); to the line before return joinArray;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Fourier transform and maximum Is there a way to compute efficiently the Fourier transform of the max of two functions (f,g), knowing their Fourier transform?
I doubt it. The Fourier transform of max(f, g) can be computed efficiently if and only if the Fourier transform of |f| can be computed efficiently. (Because max(f,g) = (f+g+|f-g|)/2.) But there seems to be no relationship between F{f} and F{|f|}...
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "algorithm, fft" }
Управление обновлением текущего местоположения. Google Maps. Android Я получаю данные о моём местоположении в активности. Исходя из этого значения я могу построить, например, маркеры на карте. Затем я нажимаю на кнопку и запускаю сервис, который будет считать пройденное расстояние (и в нём мне нужно будет тоже реализовать LocationListener). Я думал запускать 1 сервис (bind сразу в OnCreate() активности и stop в onDestroy() активности), который будет отдавать мне изменения местоположения и далее на основе этих значений считать пройденное расстояние. Но как поступить, если я не считаю ещё расстояние, то в onStop() нужно бы отписаться от обновлений моего местоположения. Возможно, есть совсем другой более рациональный способ решения этой задачки
Как вариант: 1\. Привязать сервис к активити с помощью `Binder` и запускать сервис при старте активити или по нажатию кнопки. 2\. Реализовать `LocationListener` в сервисе и отдавать данные в активити, например через `Intent`. 3\. В активити принимать данные и отображать на карте. 4\. Останавливать сервис когда нужно, тогда данные местоположение не будет определяться и т.д. **ИЛИ:** не реализовывать сервис вообще, тогда активити будет уходить в бекграунд при onStop() методе, результат будет тот же
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, google maps api, android service" }
How to disable upload button when there is no file selected in meteorjs? I had tried `slideForm.$invalid` , but it's not working.Can you suggest the best way? <form name="slideForm"> <div class="aboutFile"> <input type="file" name="file" fileread="vm.file" class="form-control" ng-model="vm.file"> <div class="create-component--perma-bg"> <i class="fa fa-plus-square-o" aria-hidden="true"></i> <span ng-if="!vm.file.name">Add File </span> <span ng-if="vm.file.name">{{vm.file.name}}</span> </div> <button type="button" class="btn btn-info bgChangeBtnInfo" ng- click="vm.upload(vm.file)" ng-disabled="slideForm.$invalid"> Upload</button> </div> </form>
I think You have to make it as required field like this <input type="file" name="file" fileread="vm.file" class="form-control" ng-model="vm.file" required>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angularjs, meteor, angular meteor, angularjs ng disabled" }
Convert linq query to Generic string array I know that I can cast my linq query to an array or list but this doesn't seem to help. Here is my query: var bracct = from DataRow x in _checkMasterFileNew.Rows select new {BranchAccount = string.Format("{0}{1}", x["Branch"], x["AccountNumber"])}; When I attempt to convert it to a list or array: List<string> tstx = bracct.ToList(); or this: string[] stx = bracct.ToArray(); If give me this: ![enter image description here]( I am assuming I need to change my query but I'm not sure the best way to hanlde it. How do I get it to a generic collection of strings?
Your query is creating an anonymous type with a single member `BranchAccount`. If you actually just want a `string`, then just select that instead: var bracct = from DataRow x in _checkMasterFileNew.Rows select string.Format("{0}{1}", x["Branch"], x["AccountNumber"]); And now your `ToList()` call will return `List<string>`: List<string> tstx = bracct.ToList();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, linq, generics" }
identity on integration's extremes. We have a continuous functions $f(x)$, variable $x,t\in \mathbb R$ and a real (positive) parameter $r$. Are true the following identity $$\int_0^t (f(r+x)-f(x))\, dx=\int_t^{t+r} f(x)\,dx-\int_0^r f(x) \, dx\text{ ?}$$
$$\begin{align}\int_0^t (f(r+x)-f(x))\, dx & = \int_0^tf(r+x)\, dx -\int_0^tf(x)\, dx \\\ & = \int_r^{r+t}f(x)\, dx-\int_0^tf(x)\, dx \\\ &= \int _0^{r+t}f(x)\, dx-\int_0^rf(x)\, dx-\int_0^tf(x)\, dx\\\&=\int_0^tf(x)\, dx+\int_t^{t+r}f(x)\, -\int_0^rf(x)\, dx-\int_0^tf(x)\, dx\\\ & =\int_t^{t+r}f(x)\, dx-\int_0^rf(x)\, dx\end{align}$$
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "integration" }
How do I click to select more than one face a a time? I went into face select mode and it will not let me keep the faces as I select more and more. In other words, it only lets me select one face at a time. How can I make it so I can select multiple faces at a time and make the edit I need?
Just hold the `Shift` key while selecting, easy as that.
stackexchange-blender
{ "answer_score": 4, "question_score": 1, "tags": "faces, selection tools" }
Is there a way to introspect a function in Lua? I am creating a game in love2d (LuaJIT) and I am creating a debug window for changing values at runtime. I was able to do that, however, I also now want to be able to call functions. For example, I traverse a table and there is a function in this table called "hello" which is written like this: self.hello = function(str, num) print(string.format("%s: %d", str, num)) end From the expression of `type(object.hello)` I only see `function`. If it had been a table, I could have traversed it and see the keys and values, but it is just a "function" and I have no idea how to properly call it, as I don't know what arguments does it take and how many. Is there a way to find this out at runtime in lua? Maybe this information is also stored in some table elsewhere?
> it is just a "function" and I have no idea how to properly call it Neither does Lua. As far as Lua is concerned, any Lua function can take any number of parameters and return any number of parameters. These parameters could be of any type, as could its return values. Lua itself does not store this information. Or at least, not in any way you could retrieve without doing some decompiling of its byte-code. And since you're using LuaJIT, that "decompiling" might require decompiling _assembly_.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "lua, introspection, luajit" }
Create a time table (hours by hours) in BigQuery? How can I generate the following table in BigQuery: +---------------------+ | mydate | +---------------------+ | 2010-01-01 00:00:00 | | 2010-01-01 01:00:00 | | 2010-01-01 02:00:00 | | 2010-01-01 03:00:00 | | 2010-01-01 04:00:00 | | 2010-01-01 05:00:00 | +---------------------+
Use below select ts from unnest(generate_timestamp_array('2010-01-01 00:00:00', '2010-01-01 05:00:00', interval 1 hour)) ts with output ![enter image description here]( Another option (based on @Daniel's comment and @Khilesh's answer) select timestamp('2010-01-01 00:00:00') + make_interval(hour => hours_to_add) from unnest(generate_array(0,5)) AS hours_to_add obviously with same output as above
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "google bigquery" }
Convergence of simple non-negative functions to a measurable function The question is from "Measure theory and probability theory (pag. 51)" by Krishna and Soumendra that lacks of a demonstration. Let $(\Omega, \mathcal{F}, \mu)$ be a measure space and $f:\Omega \rightarrow [0, \infty]$ a non-negative measurable function. Suppose $\\{\delta_n\\}$ to be a sequence of positive real numbers and $\\{N_n\\}$ a non-decreasing sequence of integers such that $\delta_n \rightarrow 0$, $N_n \rightarrow \infty$ and $\delta_n N_n \rightarrow \infty$ (for example $\delta_n=2^{-n}$ and $N_n=n2^n$). Define \begin{gather*} f_n(\omega)=\left\\{ \begin{array}{ll} j\delta_n \ \ \text{if} \ \ j\delta_n \le f(\omega) <(j+1)\delta_n \ \ j=0,\dots,N_n-1 \\\ \delta_nN_n \ \ \text{if} \ \ f(\omega) \ge \delta_nN_n \end{array} \right. \end{gather*} I need to prove that $\\{f_n\\}$ converges to $f$ pointwise and that each $f_n$ is measurable.
The preimages of $f_n$ are unions of sets of the form $\\{\omega : a \le f(\omega) < b\\}$ and $\\{\omega : f(\omega) \ge a\\}$, which are measurable sets because $f$ is measurable. For a fixed $\omega$, we want to check that $f_n(\omega) \to f_n(\omega)$. Because $\delta_n N_n \to \infty$, we have $f(\omega) < \delta_n N_n$ for all large $n$. By the definition of $f_n$, we have $f_n(\omega) = j\delta_n$ for some $j$, so $f_n(\omega) \le f(\omega) < f_n(\omega) + \delta_n$. Taking $\delta_n \to 0$ establishes the convergence.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "measure theory, lebesgue measure, measurable functions" }
Can I create support multiple database transactions on a single connection? I have created a HyperSQL Database. I was just wondering whether I could run multiple transactions on a single connection. I didn't want to spawn a new connection for each transaction due to the overhead associated with this. Looking at some similar questions the suggestion appeared to be to create a pool of database connections and then block waiting for one to become available. This is a workable, but not desirable solution. Background Info (if this is relevant to the answer). My application will create a new thread when some request comes in. This request will require a database transaction. Then some not insignificant time later this transaction will be committed. Any advice appreciated :)
You should be able to run multiple transactions over a single connection they will just have to be run one at a time so you'll have to queue or stack them and block as the transaction happens. You generally will not be able to run queries in parallel over a single connection.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "database, jdbc, database connection, hsqldb" }
Justify content start если строка не заполнена При работе с Flexbox наткнулся на такую проблему. Как-то не получается решить его без изобретения нового велосипеда. Вот сам пример. .flex { display: flex; justify-content: space-between; flex-wrap: wrap; } .child { width: 24%; height: 50px; background: red; margin-bottom: 20px; color: white; } <div class="flex"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child">last element</div> </div> Вот, в примере, последний элемент с надписью `last element` хочу чтобы был слева, там, где тот же элемент предыдущей строки. То есть если строка не заполнена, то элементы позиционировать слева. Может кто-то поможет разобраться с этой проблемой.
Если вы хотите, чтобы элементы шли один за другим с одинаковыми промежутками — не обязательно использовать `justify-content: space-between`. В вашем примере элементы, шириной `24%` расположены по 4 в ряд и равномерно распределены между границами flex-контейнера. Т.е. три отступа между ними — это 4% ширины контейнера. Дело за малым — добавить отступ справа у всех элементов, кроме каждого четвёртого. .flex { display: flex; flex-wrap: wrap; } .child { width: 24%; height: 50px; background: red; color: white; margin: 0 calc(4% / 3) 20px 0; } .child:nth-child(4n+4) { margin-right: 0; } <div class="flex"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child">last element</div> </div>
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "html, css, css3, вёрстка, flexbox" }
Multitasking how to make worker thread gain control after calling infinite loop function assume creating 3 worker threads by pthread_create, in these worker thread routine, each call a simple infinite loop function which do not have a return to do counting how to make worker thread gain control after calling infinite loop function and save the context of infinite loop function for calling in worker thread again?
Let me rephrase to see if I understood the problem. You have a master thread which spawns 3 worker threads which each do a long running (infinite) job. At a certain point you want to interrupt processing, save the state of all threads to resume where they left off at a later time. I think the best way of doing this is organize your threads work in transactionally bound chunks. When restarting, you check the last completed transaction, and go from there. But since I suspect this to be a homework assignment in low level thread plumbing, may i suggest a shared boolean which is checked on every time you go through the loop to exit and store the state afterwards. Aternatively "kill" the thread and catch the exception and store the state. The last option is messy.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "c, multithreading, pthreads" }
Find marginal probability density function without the joint density function or the other marginal pdf This is a question from exam review sheet. Please give me some guidance here. I do not know how can I find fY(y) without having information on f(x,y) or at least fX(x)? Consider a random variable Y generated as follows. First select a value of X = x at random (uniform) over the interval (0,1). Then select a value of Y = y at random (uniform) over the interval (0,x). Find the probability density function fY(y). Thank you.
You know $X\sim U(0,1)$. Further, you know conditional on $X=x$, that $Y\sim U(0,x)$. That is the conditional density of $Y$ given $X=x$ is $f(y|x)=\frac{1}{x} \mathbb{1}_{0<y<x}$. The unconditional density can then by found by the law of total probability, i.e. $$f_Y(y)=\int_0^1 f(y| x)f_X(x)dx,$$ Can you finish up from this?
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "probability, probability distributions" }
Is it possible to make nodejs execute some code after it has been launched Is it possible to make nodejs execute some code after it has been launched. After Node.js started, I hope it can loads some code interprets and executes them. Is there any module can do this? Your comment welcome
You might take a look at the child process in the Node API, specifically exec for an easy example of executing a command from within Node. Copied from the API doc: var exec = require('child_process').exec, child; child = exec('cat *.js bad_file | wc -l', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "node.js" }
ios split array into sections based on compare result I have an `array` of objects which I am currently sorting by `date` (the objects each have a `date` field on them). I want to be able to split up this array into multiple sections, where each section contains the objects that have the same date. Is there already a supported mechanism for this?
There seems to be no mechanism for this, other than the way I suggested in my comment: I create a `nsmutabledict`, then I iterate over my sorted list of objects. For each object, I check the date, and see if there exists a key in my `dict` pertaining to that date. If so, I retrieve that value from the `dict` and append this `object` to that array. If not, I create a new `list` and insert it into the `dict` with the key pertaining to the date.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, arrays, sorting" }
Question about the Fundamental Group as a notion Can the fundamental group of some surface have more than one path homotopy class? Maybe this is a dumb question, but I'm really struggling with this
Yes. The fundmental group of a torus is isomorphic to $\mathbb{Z} \oplus \mathbb{Z}$ so has infinitely many homotopy classes.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "general topology, algebraic topology, homotopy theory, fundamental groups" }
Execute code after some time without using sleep in Python? I am writing code for an LCD screen using `Python` and I want it to display a flashing 'Press SELECT' message until a button on the LCD is pressed. The problem is that while the program is in sleep, it does not register the user pressing the button, meaning that I have to press the button exactly when the message is being printed. How can I do this without using sleep? This is the code that I used: #lcd.is_pressed(LCD.SELECT) - checks if button is pressed #lcd.message - prints text on LCD #lcd.clear - removes all text from LCD while not lcd.is_pressed(LCD.SELECT): lcd.message ('Press Select') sleep(2) lcd.clear() sleep(2)
Split your time into smaller slices; this checks the button every hundredth of a second: i = 0 while not lcd.is_pressed(LCD.SELECT): i = (i + 1) % 400 if i == 0: lcd.message("Press Select") elif i == 200: lcd.clear() sleep(0.01)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, sleep, lcd" }
Only Selecting Cases for all Time Periods I have a longitudinal data set for a month in which there is some user attrition. I'd like to subset the data just for those **users who are active across all 30 days** , but I could not find an example of this type of subset. Here is an example of the data layout: date userID x 2001-11-08 1 20 2001-11-08 2 2 2001-11-08 3 10 2001-11-08 4 5 2001-11-08 5 1 2001-11-09 1 19 2001-11-09 3 4 2001-11-09 4 5 ... 2001-11-30 1 15
subset(dnow, ave(as.numeric(date), userID, FUN=function(x) length(unique(x)))==30)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "r" }
Como mostrar uma mensagem quando nenhum jradiobutton está selecionado? Estou fazendo um exercício em java swing que contem a seguinte tela com JRadioButtons: ![inserir a descrição da imagem aqui]( Quando o "java swing" está selecionado ele deve mostrar uma mensagem ao clicar no JButton e vice versa com a segunda opção. Porém como mostrar uma mensagem quando não houver nenhuma opção selecionada? private void clickEvento(java.awt.event.ActionEvent evt) { if (jrbJavaSwing.isSelected()) { JOptionPane.showMessageDialog(null, "Java Swing"); } if (jrbOutraLP.isSelected()) { JOptionPane.showMessageDialog(null, "Outra linguagem... Tem certeza?"); } JOptionPane.showMessageDialog(null, "Você não selecionou nada"); Pois dessa forma com este JOptionPane na última linha, ele fica retornando a mensagem sempre.
O método `isSelected` retorna um _boolean_ , ele retorna `false` caso não esteja selecionado, então: private void clickEvento(java.awt.event.ActionEvent evt) { if (jrbJavaSwing.isSelected()) { JOptionPane.showMessageDialog(null, "Java Swing"); } if (jrbOutraLP.isSelected()) { JOptionPane.showMessageDialog(null, "Outra linguagem... Tem certeza?"); } if (jrbJavaSwing.isSelected() == false && jrbOutraLP.isSelected() == false) { JOptionPane.showMessageDialog(null, "Você não selecionou nada"); } }
stackexchange-pt_stackoverflow
{ "answer_score": -1, "question_score": -1, "tags": "java, netbeans" }
C++ MFC CComboBox is empty i've a little comboBox, and i want to fill it with 6 entries... . i wrote this code: CComboBox* dropdownList = ((CComboBox*)GetDlgItem(IDC_PROGRAMDROPDOWN)); dropdownList->Clear(); dropdownList->AddString(L"test"); dropdownList->AddString(L"test2"); dropdownList->InsertString(2,L"test3"); dropdownList->InsertString(3,L"test4"); dropdownList->InsertString(4,L"test5"); As you can see I tried `AddString()`, and `InsertString()`. both with no effect. I also tried it just with `AddString()` which should be the correct way at initializing it. But, my combobox is empty. I already debugged it, and this lines are hit but with no effect. Do you have any idea?
thanks for all your answers. But it was an ugly Failure by my IDE -.-. I just recreated the UI-Element and it worked... I recreated it with the same properties (Copy & Paste)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c++, mfc, ccombobox" }
Why can verbs be omitted in this sentence? > Professor: Now when I mention the terms "boom and bust", what does that bring to mind? > > Student: The dot-com crash of the 90s. > > Professor: OK. **The boom in the late 1990s when all those new Internet companies sprang up and were then sold for huge amounts of money.** > > from TOFEL TPO6 Listening This is a part of a lecture in an economics class. The subject is 'The boom', but I can't find a verb. why? Can I use this sentence in writing? Or is it only used in speaking?
The "sentence" in question is grammatically just a noun phrase with no verb attached to it. In this context, however, it's correct, just as a noun or noun phrase is in this context: > Alice: Where are we going for lunch? > Bob: The Mexican place where the servers wear wrestling masks. Alice: The same place we went yesterday. Here, Alice asks a question, and the next two lines of dialogue are just noun phrases, not sentences, because in a dialogue, a noun phrase is a grammatically correct answer to a wh-question. This is almost only used in speaking. A writer who uses this style creates a conversational tone, usually with an imagined reader.
stackexchange-ell
{ "answer_score": 0, "question_score": 1, "tags": "sentence structure" }
Find $,,$ such that $(−, +, −1)=(4, 2, 3)$. I am stuck at this question can someone help me? I've been trying it all morning but I just cant quite get it going maybe one of the lads can help
We have the equations $(1) \quad x-y=4$ $(2) \quad x+y=2$ and $(3) \quad z-1=3.$ Equation $(3)$ gives $z=4.$ $(1)+(2)$ gives you an equation for $x$. Your turn !
stackexchange-math
{ "answer_score": 1, "question_score": -2, "tags": "algebra precalculus, vectors" }
How can I realize a missed call? I understand that the call log is off limits for developers for Windows Phone 8.1. However, what if I only want to know if a call was missed without any further details? I'm really looking for a "if (MissedCalls == true)" type of support. Any suggestions? Here's the app that I'm looking to implement this feature with.
Currently there is no API for that It will be added in future .Windows Feedback
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "windows phone 8, windows phone 8.1" }
What do the notifications say? Either due to the notifications being too long, or android not scrolling the notifications, but I can't see what most of the notifications say. The main reason for this question is One of your dwellers has been... but I'd also like to know all of the notifications that can appear.
All are prefixed by "Vault (x): " * One of your Dwellers has been out in the Wasteland for a while, you should check on them. * A baby is about to be born in your Vault! * One of your babies has grown into a healthy Dweller! * Something happened in your vault! * One of your production rooms is ready for collecting! * One of your Dwellers has been out in the Wasteland for a short while. Perhaps you should check on them.
stackexchange-gaming
{ "answer_score": 9, "question_score": 7, "tags": "fallout shelter" }
correct development flow when using vagrant and puppet I have done some googling however I couldn't quite find what I wanted. What I am trying to achieve is have a local, development staging and live all using vagrant and puppet/chef. Now I could be totally wrong and missing something but could I for example on my local development have the provider as virtualbox then for staging / development and live use AWS or DigitalOcean as the provider ? If I am totally wrong what is the correct process for letting puppet/chef manage all my environments, any links would be amazing.
> Now I could be totally wrong and missing something but could I for example on my local development have the provider as virtualbox then for staging / development and live use AWS or DigitalOcean as the provider ? Yes, that's how it works. Note that the `Vagrantfile` would need to have the information for your multiple environments, or you can simply have multiple `Vagrantfile`s
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "amazon web services, vagrant, puppet, digital ocean" }
Highcharts do not hold all the values of stacked columns chart with data time axes I got trouble, on right and left side of charts missing few series.More precisely 1,2,11,12 series. An even if they appear i need to set some padding for the most left and right columns. Here is my example: //jsfiddle.net/Hideon/d76zhmo0/10/
This problem is reported on Highcharts github: < and marked as a bug. To workaround manually set `pointRange`: plotOptions: { column: { stacking: 'normal', pointRange: 1000 * 60 * 60 * 24 } } Live demo: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "highcharts" }
Getting next Timestamp Value What is the proper solution in pandas to get the next timestamp value? I have the following timestamp: Timestamp('2017-11-01 00:00:00', freq='MS') I want to get this as the result for the next timestamp value: Timestamp('2017-12-01 00:00:00', freq='MS') **Edit:** I am working with multiple frequencies (1min, 5min, 15min, 60min, D, W-SUN, MS). Is there a generic command to get next value? Is the best approach to build a function that behaves accordingly to each one of the frequencies?
General solution is convert strings to `offset` and add to timestamp: L = ['1min', '5min', '15min', '60min', 'D', 'W-SUN', 'MS'] t = pd.Timestamp('2017-11-01 00:00:00', freq='MS') t1 = [t + pd.tseries.frequencies.to_offset(x) for x in L] print (t1) [Timestamp('2017-11-01 00:01:00', freq='MS'), Timestamp('2017-11-01 00:05:00', freq='MS'), Timestamp('2017-11-01 00:15:00', freq='MS'), Timestamp('2017-11-01 01:00:00', freq='MS'), Timestamp('2017-11-02 00:00:00', freq='MS'), Timestamp('2017-11-05 00:00:00'), Timestamp('2017-12-01 00:00:00')]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, pandas" }
How to get the name of child class from base class when an object of child class is created I want to get the name of my child class in the base class so that whenever an object of child class is created I get the name of the child class in my base class. Something like this: class Base_class { function __construct() { // Some code Here to get the name of the child class } } class Child_class extends Base_Class {} class Another_child_class extends Base_Class {} $object = new Child_Class; $object2 = new Another_child_class; When the `$object` is created I want the constructor to give me the name of the class from which the object was created.
You can use `get_class()` passing it the current object reference, like so: class Base_class { function __construct() { $calledClassName = get_class($this); } } Edit: You can find more info on `get_class()` in the PHP manual <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "php, oop" }
Changing Exception type to base class I have two projects. In one of them I use MailKit and it is responsible for all kinds of email. Here I could get `SmtpCommandExceptions` or `SmtpProtocolExceptions` that are derived of `CommandException` which is derived of the normal `System.Exception`. I want to give the exception to the other project without binding the complete MailKit into the other project. So I thought about getting the additional properties into strings, putting them together and send everything else back. Is there any way of extracting the exception out of the derived class and throw away all additional methods, properties, and so on?
The typical way to deal with this kind of problem is to wrap the exception in a custom exception class: public class MyWrappedException : Exception { public string MyProperty { get; } public MyWrappedException(string message, string myProperty, Exception innerException) : base(message, innerException) { MyProperty = myProperty; } } Called like: try { DoSomething(); } catch(InvalidOperationException ex) { throw new MyWrappedException("Oups", "tried doing X", ex); } This keeps the all the original exception information, but most of it will not be visible unless you use a debugger or it is included when converting to a string. You can select what properties you want to include in the wrapper. This lets you catch your wrapped exception without an direct dependency on mailkit.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, class, exception, derived class, mailkit" }
can not use "<?= ?>" in zend framework In coding i always write `<?= $this->description?>` _rather than_ `<?php echo $this->description ?>` it is little bit faster and easier. However, after i started using zend framework, i couldn't use that feature. so do you have any idea about it.
You need to enable the `short_open_tag` option in the configuration file php.ini. Short tags are disabled by default.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -1, "tags": "php, zend framework" }
The "Letter U" Rebus Here is a rebus I thought of again. Can you solve it? ![Rebus2](
Could be: > NOT FOR US; multiple Us OR > NOT FOR USE; another use of Us
stackexchange-puzzling
{ "answer_score": 11, "question_score": 1, "tags": "visual, rebus" }
SAML Configuration for BambooHR I'm trying to setup SAML to SSO into BambooHR, I'm using Auth0 as my IDP. BambooHR requests a SSO Login URL and x.509 Cert from my IDP (which I can easily provide), but I can't find where BambooHR provides the Audience URI and/or callback URI to enter into Auth0. Does anyone know where I can find this information? Thanks!
For future reference you can use the following for BambooHR's Callback URL and Audience: DOMAIN}.bamboohr.com/saml/consume.php
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "saml, auth0" }
How would I incorporate a JavaScript browser inside a JFrame It has become apparent to me that it isn't possible to include JavaScript with JEditorPane. Is there another way? I must include a website tab inside my JFrame's JScrollPane, but I cannot because there is no way within Java's means. Are there other solutions to achieve my objective. Perhaps with any libraries?
Problem solved with javaFX. It can be incorporated with JFXPanel. (I'll post an example up here later)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, browser, jframe" }
WooCommerce order created via REST - sending the date_created along So as the topic hints, I'm trying to get WooCommerce to accept my `date_created` that I'm sending along with the order I'm creating via REST: POST { (order_fields) ... "date_created": "05-12-2017 13:00:00" } The field is readonly sadly, so does anyone know if this is possible? The reason I need this, is the orders are created in an external system, and the dates need to be the same across both systems.
`date_created` is `read-only` value meaning that you cannot set it over the REST API. What you can do is: 1. Send creation time from your "external system" as `order meta data` (sample PHP code below) and then in WooCommerce trigger the action using custom plug-in which updates order `date_created` according to a meta value. > > $json_encode['meta_data'][0]['key'] = 'my_date_created'; > $json_encode['meta_data'][0]['value'] = '05-12-2017 13:00:00'; > 2. Update `date_created` in your "external system" with `date_created` from jSon returned by Woocommerce in order to have values synchronised. If you just want to pair order records do it over `order ID` returned in jSon by Woocommerce (Woocommerce returns a jSon when the order was created successfully). You will add `order ID` record to your "external system".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to modify a returned property without affecting the actual property in Neo4j? Is there a way to modify a returned property without affecting the actual property in Neo4j? I have tried to use SET Clause, but it modifies the actual property in the database. Take as an example this query for < match (n:Crew) //change n.name = "my_value" return n How can I get the output below without changing the actual name property? (0:Crew {name:"my_value"}) (1:Crew {name:"my_value"}) (2:Crew {name:"my_value"}) (3:Crew:Matrix {name:"my_value"})
You could use a map projection to return a map of all the properties of each node, with some of the properties being overridden, like this: MATCH (n:Crew) RETURN n {.*, name: 'my_value'} However, this will not generate a visualization, since the returned `n` would not be a node (it would just be a map). If you want to visualize the result, you should look into using virtual nodes and relationships. You should also use the Neo4j Browser instead of < as the latter may not properly visualize virtual nodes and relationships.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "neo4j, cypher" }
Screen not getting updated I know that Google engineers are taking some control in regards views layout and redrawing. But I can't understand way changing a view visibility doesn't update the screen. I have a peace of code that is strait forward: if (editMode) mView.setVisibility(View.VISIBLE); else mView.setVisibility(View.INVISIBLE); The "mView" is a TableLayout view that shows its cells when the Activity is in edit mode. And hides it when the Activity is in normal mode. I tried to call "invalidate()" in the "mView" instance and on its parent (that is a FrameLayout), nothing worked. I suspected that could have something to do with the drawing cache so, I disabled it in the parent view (FrameLayout), and in the "mView" instance. I got no changes. Why a View is so stuck like that? What could I possibly doing wrong that the screen doesn't get updated?
If by **screen doesn't get updated** you mean that there is an empty space where the view was once then that is because you made it invisible i.e. we can't see it but it's there. If want to remove that space then use `View.GONE`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "android" }
Is the hypercone contractible? I know the cone CX is contractible but was wondering if the 3 dimensional cone in 4-space was also contractible.
I'm assuming you are referring to the hypercone as described here. This is indeed contractible. One way to see this is that if $x,y,z,w$ satisfy $x^2+y^2+z^2-w^2=0$, then so do $(tx,ty,tz,tw)$ for any $t$. So there is a homotopy of the identity map $f(x,y,z,t)=(x,y,z,t)$ on the hypercone to the constant map at $0$ given by $f_t(x,y,z,w)=(1-t)(x,y,z,w)$. This is sufficient to show contractibility.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "general topology" }
Design patterns to ease migration of SQL code between vendors I am looking at ways which a developer can take advantage of implementation specific advanced features(T-SQL, PL-SQL etc) and at the same time makes it easy to migrate the ANSI compliant SQL code to a new database. By that I mean, how to efficiently abstract the ANSI compliant SQL code and move it across different databases?
I use the Mimer SQL validators: > Check Your SQL Against the SQL-92 Standard. Mimer SQL-92 Validator recognizes the standards Entry, Transitional, Intermediate and Full SQL-92, Persistent Stored Modules (PSM) SQL-99 and Database Triggers Copy and paste SQL text into the webpage and hit the 'Test SQL' button. ..though I'm not sure that is the kind of "efficient" process you are looking for, it may of some use.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql, database, data migration" }
Override WhatsApp contact image with the chosen Contact Image I dislike how people use full body pictures for their contact images when it's a small image. When I link the accounts in my Android, I chose a picture that looks good and helps me identify them easily. But in WhatsApp, when these people chose their profile picture, they override my selection. Is there a way to fix this?
For now there isn't, unless an add-ons for WhatsApp will enable this or they built it in themselves. It's comparable to Facebook, user set their own avatar and this can be seen by friends. This works unlike your contact list in which you control the content and other users have no say in adjusting the content.
stackexchange-android
{ "answer_score": 2, "question_score": 9, "tags": "images, profiles, whatsapp messenger" }
Ruby Programming: Predicate Methods I am new to Ruby and came across the `defined?` operator. I thought the `?` implied that the method returned `true`/`false` but `defined?` returns a description of the identifier if it is defined. I know that there is a `true`/`false` component in that the identifier is or is not defined but I thought that the `?` meant that the return value always had to be `true`/false`. Help?
It returns a "truthy" value that is either "truthy-true" or "truthy-false". In Ruby, there are _only_ two things that are truthy-false: * `false` (the singleton object) * `nil` (the singleton object) _Anything_ else is considered truthy-true. Tons of Ruby code leverages this fact for predicates. Checks for predicates, as such, should be: if list.empty? not: if list.empty? == true
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ruby" }
For which values of $x \in R$ does the series $\{x^\mathrm{k_n}\}^\infty_\mathrm{n=1}$ converge. Say that I have the sequence $\\{a_n\\}^\infty_\mathrm{n=1}$ that is a strictly increasing sequence of natural numbers. For which values of $x \in R$ does the series $\\{x^\mathrm{a_n}\\}^\infty_\mathrm{n=1}$ converge. I tried to work through comparisons for this and know that series $(x^n)$ converges in $(-1,1)$ and diverges elsewhere. Not sure how to approach this.
Note that the series $$ \sum x^n$$ converges exactlyif $|x|<1$, and thus it also converges absolutely. This means that $\sum x^{a_n}$ as a subseries has to converge as well. On the other hand if $|x|\geq 1$ then $|x^{a_n}|$ does not go to $0$. Thus the series cannot converge.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "real analysis, sequences and series" }
How to close a specific window with jQuery I open a window with jQuery. Then I want to close it but window.close or nameOfTheWindow.close does not work. How should I do it? I have the example here: < HTML: <a class="open" href=" target="_blank"> open window 1 </a> <br><br> <a class="close" href="#"> close window 1</a> JQUERY: $(function(){ //I give the window the name window1 and I open it: $('.open').click(function(e){ e.preventDefault(); window.open("","window1","width=400, height=400"); }); $('.close').click(function(){ // I tried and does not work: // window.close(); // window1.close(); }); })
Like this: $(function(){ var popup; $('.open').click(function(e){ e.preventDefault(); popup = window.open("","window1","width=400, height=400"); }); $('.close').click(function(){ if(popup) popup.close(); }); }); ## DEMO
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "jquery" }
How to add value from list into dictionary? dict={} i=["abc","def","ghi","jkl"] j=[["a","b","c","d"],["q","w","e","r"],["t","y","u","i"]] for item in i: dict[item]=[str(j[item])] print dict Output should be like dict={"abc":["a","b","c","d"], "def":["q","w","e","r"] ...} How can I add list into dictionary in python?
Use the `zip()` function to combine the two lists: dict(zip(i, j)) Demo: >>> i=["abc","def","ghi","jkl"] >>> j=[["a","b","c","d"],["q","w","e","r"],["t","y","u","i"]] >>> dict(zip(i, j)) {'abc': ['a', 'b', 'c', 'd'], 'ghi': ['t', 'y', 'u', 'i'], 'def': ['q', 'w', 'e', 'r']} `zip()` pairs up elements from lists into a sequence of tuples; the `dict()` constructor takes a sequence of tuples and interprets them as key-value pairs.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "python" }
Split Multiple Options in Single Attribute in Magento I have multiple options in an attributes in Magento and when I call the attribute, all of the options show in a string and I would like to show them on separate lines (p tags or li's). <?php echo $this->getChildHtml('spamodel') ?> The above is my code, I think i need to use explode but I'm a newbie at php. Thanks for any help.
<?php $spamodel = $this->getChildHtml('spamodel'); $spamodel_explode = explode(",",$spamodel); echo $spamodel_explode[0]; ?> Here you can go with this code. you can get single the names with `$spamodel_explode[0]` and if you want to get all the names than you can use **forloop**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, string, magento, attributes, explode" }
What is the key scan code of the Fn key for use in AutoHotkey (AHK)? I want to use `Fn`+`S` to emulate `Ctrl`+`S`, and so far this is my code: #InstallKeybdHook #Persistent SC126 & s:: Send ^{s} return My problem is that I don't know the `Fn` key's scan code. How can I find it?
The `Fn` key does not have a scan code. The keyboard driver does not expose the `Fn` key to the operating system, so basically your operating system (and therefore AutoHotkey) does not know that it exists. When you press the `Fn` key in combination with a supported key, the keyboard driver reports a single key press to the operating system with a different scan code. Basically, it tells the operating system that a different key was pressed.
stackexchange-stackoverflow
{ "answer_score": 40, "question_score": 17, "tags": "autohotkey" }
rotate a html element around a point How can I rotate a html element around an arbitrary point. I know there is css `rotate trasform` property that rotates the element around itself. but I want to rotate it in a way like a **clock needle**. !enter image description here
You can use transform origin: < as mentioned here: CSS rotation with respect to a reference point
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "javascript, jquery, html, css, rotation" }
uninstall wireshark Version 1.12.7 from ubuntu trusty tar I installed this version {version 1.12.7} of `Wireshark` and its not working as i want it. I compiled it as directed from the tutorial. 1. it works only as root user and the commands to change that doesn't work. I just want to uninstall it. DON'T WANT IT ANYMORE I have used sudo apt-get remove wireshark sudo apt-get purge wireshark none is working. When I type `wireshark` on the terminal it still runs normally I fear using the older version will cause me problems on GNS3. I need help Linux gurus
You can't remove a compiled version in the same way as a deb package. 1. If you no longer have the source code, download the source code again 2. Compile Wireshark again, and **don't** install 3. Install `checkinstall` sudo apt-get install checkinstall 4. Install, **yes install** via sudo checkinstall Why? `checkinstall` creates a deb package and installs the package and overwrites in this way all installed files of your earlier installation via `sudo make install` 5. Remove sudo apt-get remove wireshark And in the future, use `checkinstall` to install your self-compiled code.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 1, "tags": "uninstall" }
Firebase event tracking exclude test automation runs and qa testing events We are facing an issue, where our test automation setup spoils our analytics. There is a solution that I found just to exclude staging flavour from testing and added a feature flag to turn it on for testing purposes. However, I see room to improve this logic, by checking if a device is in debug-view mode and allowing test-tracking only for this case. (because devices in a debug view are automatically excluded from statistics) this is what doc says > Note: To prevent your testing and development from affecting your measurements, events logged while in debug mode will be excluded from your overall Analytics data, and will not be included in your daily BigQuery export. `adb shell setprop debug.firebase.analytics.app package_name` Is there a way to check this value?
this is a solution that I found. Hope it would be useful for someone /** * we read user properties and if these properties contain our application id as a selected firebase analytics app * we enable tracking @see for more details */ private fun isDebugEnabled() = try { // Run the command to get properties for debug view for firebase val process = Runtime.getRuntime() .exec(arrayOf("/system/bin/sh", "-l", "-c", "getprop | grep debug.firebase.analytics.app")) val bufferedReader = BufferedReader(InputStreamReader(process.inputStream)) // Grab the results bufferedReader.readLines().any { it.contains(applicationId) } } catch (e: IOException) { false }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, firebase analytics, google analytics firebase, event tracking" }
can we apply enabled settings to already exist field of any index in Elasticsearch Hi I am new to elasticsearch. can we apply or update enabled settings of already exist field of any index in Elasticsearch. if yes, please help with that. i try this doc < of elasticsearch. but getting exception resource already exist.
You can update some settings (like the number of replicas) but not analyzer nor number of shards. and add new mappings but not modify an existing one. So you can add a new field or a new type on an existing field. If you want to add enable: false on a new object never used in your mapping before you can: PUT test/_mapping { "properties": { "meta-datas": { "enabled": false } } } But if you want to "disable" an existing object, you'll have to create a new index, prepare your mapping, reindex in this new index, then delete the first one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, elasticsearch, elasticsearch 5, aws elasticsearch" }
Keeping file for personal use with GPG I have a small text file with personal (sensitve) information. I'm currently encrypting/decrypting it with the Makefile, as described on < ; relevant section is edit: @umask 0077;\ $(GPG) --output $(FILEPLAIN) --decrypt $(FILECRYPT) @emacs $(FILEPLAIN) @umask 0077;\ $(GPG) --encrypt --recipient $(GPGID) $(FILEPLAIN) @$(RM) $(FILEPLAIN) view: @umask 0077; $(GPG) --decrypt $(FILECRYPT) | less this works fine for viewing, but not for editting: I first have to enter my password, then edit the file, but to encrypt it afterwards I again have to enter my password twice (and it's a long one). Is there a better way to do this?
I suggest using a mounted truecrypt volume instead. > `truecrypt -M “rw,sync,utf8,uid=$UID,umask=0007″` > > This is the command to mount your truecrypt-container/volume giving you the right to read and to write data! After that follows the path to your truecrypt-container, for example `/home/usr/tcvolume` and then the place where you want the truecrypt-container to be mounted. In Linux this can be any ordinary folder, so for example, just create a folder “truecryptvolume”, no you type in the whole path (e.g. /home/usr/truecryptvolume ), so that the whole command looks like that: > > `truecrypt -M “rw,sync,utf8,uid=$UID,umask=0007 /home/usr/tcvolume /home/usr/truecryptvolume` > > (one line!) > > Now you will be aksed for your user-or administratorpassword(sudo) and then for the volume password, if both are given correctly truecrypt will now mount your container. > > By opening the folder “truecryptvolume” you will now be able to store your data encrypted. Source of the above
stackexchange-superuser
{ "answer_score": 2, "question_score": 2, "tags": "command line, gnupg" }
How to format date to mmddyyhrmin in sybase i want the date format in mmddyyhhmin . Can anyone help me in achieving this. for eg : FOR GETDATE RESULT SHOULD BE "032520130550"
Try this: select str_replace(convert(varchar,getdate(),101),'/',null)+str_replace(convert(char(5),getdate(),108),':',null)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "sybase" }
Scrambled text preview of pdf files in ranger I'm using ranger to preview/open and rename a number of pdf files. However if the file is open and I navigate back to the terminal window running ranger and then scroll to another file, the text preview in the ranger session (which I believe is the the result of `pdftotext file.pdf -`) gets scrambled. Then after closing the pdf file the whole ranger session becomes unusable. Is it possible to disable the `pdftotext` preview of files in ranger? Running Fedora v31.
Forgot that there was an option to preview image/pdf files within ranger itself, which makes the problem redundant. In that case I hadn't yet installed `w3m` and `w3m-img`. My `scope.sh` file was also missing and so I needed to run: `ranger --copy-config=all` first. Commenting out the lines # PDF pdf) # Preview as text conversion pdftotext -l 10 -nopgbrk -q -- "${FILE_PATH}" - | fmt -w ${PV_WIDTH} && exit 5 mutool draw -F txt -i -- "${FILE_PATH}" 1-10 | fmt -w ${PV_WIDTH} && exit 5 exiftool "${FILE_PATH}" && exit 5 exit 1;; in the `handle_extension()` function (within `scope.sh`) disables `pdftotext` preview. It does not however totally fix the "scrambled text", just reduces it. This is because by default in the `i3wm` new windows appear side by side, and ranger doesn't seem to handle the resizing window well. Useful links: 1. < 2. < 3. < 4. < 5. <
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "pdf, ranger" }
Distinct column values in csv file I have a csv file. columns in csv file - "SNo. StateName CityName AreaName PinCode NonServ.Area MessangerService Remark". The column CityName has repeated values. Ex: In many records, it has unique value (Delhi). Is there any approach in java to read that csv file and get the distinct values from that column of the csv file.
The only way I can think of is to do it row by row and store each value into an array-type structure. Using a set structure such as HashSet or TreeSet will ensure unique values. The other option, which isn't what you were looking for but might work depending on your project is to use a database instead of a csv file. It then becomes very easy to select distinct values in a column.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "csv, distinct values" }
kubernetes and external DNS in ubuntu I have an ubuntu box out of the kubernetes cluster My /etc/resolv.conf content nameserver 10.3.0.1 (kubedns) If i make a nslookup, everything works fine nslookup spark-master-0.spark-master.ns.svc.cluster.local Server: 10.3.0.1 Address: 10.3.0.1#53 Non-authoritative answer: Name: spark-master-0.spark-master.ns.svc.cluster.local Address: 10.2.0.252 if i try to use any other tool (chrome, curl, ping, wget) i get an error: curl spark-master-0.spark-master.ns.svc.cluster.local curl: (6) Could not resolve host: spark-master-0.spark-master.ns.svc.cluster.local The only way is to add search .cluster.local in /etc/resolv.conf, but now i cannot use the fqdn of the nodes any tip on how to use the fqdn ? **Update** The same setup in my mac works perfect ! the problem is only with my ubuntu 14.04.3
It seems like FQDN is working fine with DNS but issue with the host system. Can you try after changing the below entry in /etc/nsswitch.conf. hosts: files mdns4_minimal [NOTFOUND=return] dns to hosts: files mdns4_minimal dns [NOTFOUND=return] if above also not work then try putting only DNS. hosts: dns [NOTFOUND=return]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "kubernetes, dns, dnsmasq, kube dns" }
Help with simple limit calculation I have tried searching the site for an answer but I couldnt find any even though it's a simple calculation. $$ \lim_{n \rightarrow \infty} \left(\frac{4^n + 7^n}{4^{n-1} + 7^{n-1}}\right) $$ Thanks , Danny.
$$\lim_{n \rightarrow \infty} \left(\frac{4^n + 7^n}{4^{n-1} + 7^{n-1}}\right)=\lim_{n \rightarrow \infty}\frac{7^n}{7^{n-1}} \left( \frac{(\frac{4}{7})^n+1}{(\frac{4}{7})^{n-1}+1} \right)=7 \frac{\lim_{n \rightarrow \infty} \left( (\frac{4}{7})^n+1 \right)}{\lim_{n \rightarrow \infty} \left( (\frac{4}{7})^{n-1}+1 \right)}$$ $$\lim_{n \rightarrow \infty}(\frac{4}{7})^n=0, \quad \lim_{n \rightarrow \infty}(\frac{4}{7})^{n-1}=0$$ So $$7 \frac{\lim_{n \rightarrow \infty} \left( (\frac{4}{7})^n+1 \right)}{\lim_{n \rightarrow \infty} \left( (\frac{4}{7})^{n-1}+1 \right)}=7.\frac{(0+1)}{(0+1)}=7$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus, sequences and series, limits" }
MySQL creationg table error with Positional message Hello I am new to MySQL and having trouble creating a table. It says that the types im using are not valid at their position with ')'. Can someone tell me what is wrong with this code snippet? create table CUSTOMER( CustomerID int AUTO_INCREMENT, LastName varchar, FirstName varchar, Address varchar, City varchar, State varchar, ZIP number, Phone number, EmailAddress varchar, constraint pk_cID primary key(CustomerID));
Your table should look like: create table CUSTOMER( CustomerID int not null AUTO_INCREMENT, LastName varchar(100), FirstName varchar(100), Address varchar(100), City varchar(100), State varchar(100), ZIP int, Phone varchar(50), EmailAddress varchar(100), primary key(CustomerID) ); * `number` is not a datatype in `MySQL` * When you assign `auto_increment` it should be `not null auto_increment` * You don't need a constraint for primary key, just add primary key. * I don't think the best way of storing Phone numbers is `int`, you might have different formatting the best way is to treat numbers as addresses , so `varchar` would be better
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, mysql workbench" }