INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Composer classmap autoload does not load new files in folder The following problem: I have defined a classmap in my composer.json: "autoload": { "classmap": [ "app/controllers", "app/models", "app/helper.php" ] } However, when I create a new file in the "controllers" or "models" folder, it will not load them and I always have to make a composer dump-autoload. Is this the correct behavior? I thought the autoloader from composer monitors the folder for new files then?
Yes, this is correct behaviour. If you want new classes to be loaded automatically, you have to use either PSR-0 or PSR-4 autoloading. Generating the classmap requires Composer to know the filename that contains a certain class. This can only be done by parsing the whole source code in the directory and scanning for classes, interfaces and trait definitions. This usually is a CPU and I/O intensive task, so it is only done when Composer does install/update or (on demand) dumps the autoloader, it is not done with every `require "vendor/autoload.php";`. Note that the classmap autoloading is simply there for old legacy codebases that didn't implement at least PSR-0. It is not intended for new code - unless you want to pay the price to dump the autoloader again and again during development.
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 25, "tags": "composer php, autoload" }
Diction in original vs remake of True Grit The diction in the 2010 production of True Grit is much different than that of the 1969 True Grit. Why did the Coen brothers decide to follow the diction of the original novel so closely? Did folks in this time period really speak this way?
Two answers from Newsweek and Language Log When asked why they chose to follow the diction of the book and lack of contractions Ethan Coen said > We’ve been told that the language and all that formality is faithful to how people talked in the period. As to whether or not people actually talked like that Mark Liberman of the University of Pennsylvania Dept. of Linguistics writes: > I know that that informal American speech in the 1870s was far from contractionless, and in fact I suspect that it had roughly the same proportion of contractions as it does today. Therefore, what Portis (and the Coens?) did was either false archaism or poetic truth — or both.
stackexchange-movies
{ "answer_score": 12, "question_score": 14, "tags": "analysis, remake, coen brothers, true grit" }
JS - Ignore numbers after decimal point So I am trying to convert the `.text()` of a div into a number that can be used for some math within the JS (currency conversion). I am gathering the text content of a div which contains items such as currency symbols as well as a decimal point which is always followed by 00 For example if the div contained `£35,000.00` I am trying to get it to return `35000` not `3500000`. I have got some RegExp that only allows use of numbers 1-9 and therefore removes the £ sign but it also takes the decimal point out, thus multiplying the number I want by 100. This is my code: var thisDiv = $(this); var amount = $( this ).text().replace(/[^0-9]/gi, ''); Is there any way to ignore the numbers that come after the dot other than just dividing my variable by 100?
/[^0-9\.]/ this regex will keep 0-9 and . However, it will also allow values like 1.2.3 (multiple dots) if you want more validation than that, you might want to take a couple steps var numberString = value.replace(/[^0-9\.]/gi, ''); if (isNaN(numberString )) { console.log('invalid'); } else { //parse number and use it }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jquery, regex" }
Pandas - Aggregating and Ploting data from multiplefiles I have multiple files naming like starting with Quarter'Year prefix like "Q121", "Q222" and all of these files contains data like below, Identifier stays the same but price and power columns are chainging. What would be the best way to aggregate files and be able to plot column like price across data range e.g from Q1'20 to Q2'22. I was thinking about merging different files based on Identifier and then change column names to reflect Q120 etc... data = [['A1', 10,50], ['A2', 15,60], ['A3', 14,55]] df = pd.DataFrame(data, columns=['Identifier', 'Price','Power'])
from glob import glob import os import pandas as pd files = glob.glob("target_folder/*.csv") dfs = [] for file_path in files: file_name = os.path.basename(file_path) temp = pd.read_csv(file_path, names=["Price","Power"], header=None) temp["Identifier"] = file_name.replace(".csv", "") dfs.append(temp) df = pd.concat(dfs) # change Q122 -> 22Q1, so the plot can order full list nicely df["Identifier"] = df["Identifier"].apply(lambda x: "".join([x[2],x[3],x[0],x[1]]))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, pandas" }
Generating sublist of list given strings I am very new to LINQ and am wondering if there is a way to extract a sublist from a list of strings given that the string values are provided beforehand. For example, if I have: var movies = new List<Movie> { new Movie { Name = "Noah" }, new Movie { Name = "Terminator" }, new Movie { Name = "Troy" }, new Movie { Name = "Gladiator" }, }; I would like to use LINQ to create a sublist if I provide the Name strings "Noah" and "Troy". I have tried googling and results point me to SelectMany and GroupBy but all of the examples involve lists that contains primitive values, not primitives values contained in objects.
Using Linq lambda it would be: var result = movies.where(x => x.Name == "Troy" || x.Name == "Noah"); This would return a `IEnumerable<Movie>` containing the ones searched for using `Where`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, linq" }
Best Way to Monitor Types in DLL Files A portion of an application that I'm developing will monitor a particular folder for DLL files (.NET assemblies, to be more specific) that are placed within it, and it will look for any public types/classes that have the [Addin(...)] attribute. These assemblies would be occasionally replaced with newer versions of themselves, so loading them into the current app domain doesn't seem like a good option. Is the best way to approach this by setting up a separate app domain and loading in the assemblies, and then unload the app domain after the reflection/analysis is finished? Or is there a better way that might not require fully loading in the assemblies (thus not requiring the separate app domain) and might even be faster?
So while the overall approach was the same (temporary AppDomain), I was able to use the Assembly.ReflectionOnlyLoadFrom() call, which is presumably lighter than the full load.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "c#" }
Yii2 disable debug log for specific controller/action In general in development mode i have to use the debug and logging for bugtracing. But on a specific controller/action i don't want this to happen since it's just a background ajax that gets called every 2 seconds, which ends ups in a huge amount of "unneeded" logs. How can I exclude this specific call "site/ajaxupdate" from being logged?
You could simply disable the corresponding log target in your controller, e.g. : \Yii::$app->log->targets['file']->enabled = false; Read more about toggling log targets.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "debugging, yii2" }
Firefox does not start further downloads after certain number of downloads is active I i start several file downloads of a given site firefox won't start further downloads - the where to save dialog does not appear until a download is finished. I guess this is not a problem in Firefox, but is there a way to store the download links and start all downloads later? years ago i used downthemall but this not working anymore. is there an alternative at least with a feature for delayed downloads?
Go to `about:config` in the address line: ![enter image description here]( In the search line, type `network.http.max-persistent-connections-per-server`: ![enter image description here]( Right click on `network.http.max-persistent-connections-per-server` and choose `modify` (sorry the menu is blurry in the screenshot): ![enter image description here]( Enter a larger value (e.g. 10) and click `OK`: ![enter image description here]( Note that some sites indeed themselves limit your total number of download connections, but since you noted the "save" dialog didn't even appear, it seems that it wasn't the case there. As for you latter request of a Firefox download manager extension, SuperUser is not a software recommendation forum, but luckily the Stack Exchange network has such a dedicated site: Software Recommendations.
stackexchange-superuser
{ "answer_score": 2, "question_score": 2, "tags": "firefox, download, firefox extensions" }
ORDER BY using REGEXP in MYSQL I am fiddling around `REGEXP` in MySQL, and I was wondering how the `ORDER BY` command could be used with `REGEXP` in a situation like e.g. this, where we would normally order by the last 3 chars of a column using `ORDER BY RIGHT(COL,3)`. I tried this query SELECT COL FROM TABLE ORDER BY (COL REGEXP "\w{3}$") ASC but it doesn't work. Can I fix it somehow to get the equivalent of `RIGHT(COL,3)` ?
`col REGEXP '...'` return a true/false (actually 1/0) value. To `ORDER BY` col REGEXP '...'` you get the rows that don't _match_ first (in arbitrary order), followed by the ones that do match. It does _not_ sort by the last 3 characters. Use `ORDER BY RIGHT(col, 3)`. Aliasing is a convenience, not a performance issue, here. If you are looking for the `com` at the end of a domain, keep in mind that not all are exactly 3 characters. So, instead, use ORDER BY SUBSTRING_INDEX(domain, '.', -1)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "mysql, regex" }
Eclipse 32 bits running on 64 bits JVM After many investigations I can't find a clear answer to the following question: Can Eclipse 32 bits version runs on a 64 bits JVM (of course on a 64 bits windows) ? I guess the answer should be "NO" but I never worked with 64 bits systems and will be interested to "learn more" of how it work. Thanks in advance, Manu
No, that's not possible, because Eclipse's SWT GUI toolkit depends on native libraries (which is the reason there are separate 32 and 64bit version of eclipse in the first place), and you cannot call 32bit native libraries from a 64bit JVM (or, in general, you cannot mix 64bit and 32bit code within the same OS process).
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "java, eclipse, 64 bit, jvm" }
jQuery: modal form doesn't submit on enter click I want that my modal form would submit on `enter` click. I've checked all of the solutions in here, but none of these helped. I'm trying to solve it like this: $('#field-id').keypress(function(e)) { if (e.which == 13 && !e.shiftKey) e.preventDefault(); $('#modal-form-submit').submit(); } Now it's not submitting. when I use `alert` inside if, it shows the alert. `#modal-form-submit` \- is the button id, which has to be clicked when I click enter. What's wrong here? Thanks for any help
You can't submit the button, you need to submit the form. Assuming that your form has `id="modal-form"`, this should work $('#modal-form').submit(); Or you trigger the button: $('#modal-form-submit').trigger('click');
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
Converting a string to a defined constant in PHP Let's say I have defined the constant `ERROR_0` as follows: define("ERROR_0","An error occurred.") Now, let's say I have the string "ERROR_0" but I want to convert that into the constant `ERROR_0` such that I can get the string "An Error occurred." How can I do that? Thanks!
Use `constant` function echo constant("ERROR_0");
stackexchange-stackoverflow
{ "answer_score": 52, "question_score": 26, "tags": "php, string, constants" }
How to count number of unique values in column based on values in other column I have a dataframe: col1 col2 1 10 1 -2 2 -4 3 5 4 8 4 17 I want to count number of unique values in col1, if at least once on same row there was positive value in col2. So, here answer must be 3, cause unique value 1,2,3 comply with the requirement (1 because there was case when col2 had value 10). value 2 from col1 doesn't comply requirement. How to do that?
You can try dplyr::n_distinct(df1$col1[df1$col2 > 0])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, dataframe, function, count" }
What is the g_init attribute of html tag? What is the g_init attribute of html tag? Like `<html g_init="6909">` here: !enter image description here
When I visit < in Chrome 38, I don't see this attribute in the HTML. As has been pointed out, this attribute has no meaning according to any HTML specification. My guess is that this is inserted by an extension you have running in your browser. Try navigating to `chrome://extensions/` and disabling extensions, then reloading the page.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "javascript, html, google chrome, web" }
Upload a CSV file through a JSP page and print its contents using a Servlet..? I need to design a JSP page through which user uploads a CSV file and then I need to print its contents on the screen through a Servlet. The HTML code goes likes this <form action="decode" enctype="multipart/form-data" method="post> <input type="file" name="record" /> <input type="submit" /> </form> Now In decode.java, DiskFileItemFactory fi = new DiskFileItemFactory(); ServletContext sc = this.getServletConfig().getServletContext(); File file = (File) sc.getAttribute("javax.servlet.context.tempdir"); fi.setRepository(file); ServletFileUpload upload = new ServletFileUpload(fi); List<FileItem> items = upload.parseRequest(request); What should I do next to read each and every word from the uploaded CSV file...? I do not want to store the CSV file anywhere. Just want to read its contents and print them.
You can read CSV files using Apache's CSV parser library for JAVA. And then after importing the library in your classpath you can simply use it as Reader in = new FileReader(file); //The file is the file which you get from the request(java.io.File) Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); for (CSVRecord record : records) { //Do something with the records } For more information look into <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, jsp, servlets" }
Does the existence of partial derivatives imply Frechet differentiability? Let $f : \mathbb R^n \rightarrow \mathbb R^m$ and $a \in \mathbb R^n$such that $\forall i \in [1,n], \large \frac{\partial f}{\partial x_i}(a)$ exists. Is $f$ Frechet differentiable ? I'd say no, but I don't know any counter-examples...
Let $n = 2$, and $m = 1$, and consider $$f(x) = \begin{cases} \frac{xy}{x^2+y^2} &, (x,y) \neq (0,0)\\\ \quad 0 &,(x,y) = (0,0).\end{cases}$$ Then $f$ isn't even _continuous_ at $(0,0)$, but the partial derivatives exist. (The partial derivatives exist on all of $\mathbb{R}^2$. $f$ is Fréchet-differentiable everywhere except at $(0,0)$.)
stackexchange-math
{ "answer_score": 6, "question_score": 3, "tags": "multivariable calculus, derivatives" }
Divide website into vertical columns and give separate colours to each I can divide a page into sections and give them separate colour using css as .window:nth-child(1) { background: #d5d7dd; top: 0%; } .window:nth-child(2) { background: #1babb7; top: 100%; } Can I divide one of these 'child' into different columns and give them separate colour? !Like the third row is divided into 2 coumns
You've tagged HTML & CSS with this question, so here's some basic code to demonstrate how to create this. Note: It seems you're new to HTML & CSS, so I encourage you to do some tutorials! **HTML:** <div id="container"> <div id="one"></div> <div id="two"></div> <div id="three"></div> </div> **CSS:** #container { width:100%; height:200px; } #one { width:33.333%; height:200px; float:left; background-color:red; } #two { width:33.333%; height:200px; float:left; background-color:yellow; } #three { width:33.333%; height:200px; float:left; background-color:blue; }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "html, css" }
TableView to DetailView Video - Swift I'm finding any tutorial to push tableview to detailview but I didn't find any good tutorial. All i want is that when I click on any cell it will open a URL video for example < Can someone help me with it? I'll really appreciate it. Thank u.
Okay, you will have to combine a couple of tutorials. assume you found something that will make a table and then when you select a cell will take you to a detail view. For your detail ViewController implement the following tutorial to call a URL, including a video: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, swift, tableview, detailview" }
Access current user in entity lifecycle callback In my doctrine entity I have a lifecycle callback that needs access to the currently logged in user (something like `TokenStorage`). Can I stick to the lifecycle callback or do I have to switch to an event listener where the token storage is injected? /** @ORM\HasLifecycleCallbacks() */ class Report { /** @ORM\PrePersist */ public function onPrePersist(LifecycleEventArgs $args) { $this->updatedAt = new \DateTime(); $this->lastUpdatedBy = ???->getToken()->getUser(); // <----- } }
the good way to do this is to use the doctrine event listener: file service.yml services: my_report_listener : class : App\EventListener\ReportListner arguments: ['@security.token_storage'] tags: - { name: doctrine.event_listener, event: prePersist } your event listener class : class ReportListner { private $tokenStorage; public function __construct(TokenStorageInterface $tokenStorage) { $this->tokenStorage= $tokenStorage; } public function prePersist(LifecycleEventArgs $args) { $entity = $args->getObject(); if($entity instanceof Report){ $current_user = $this->tokenStorage->getToken()->getUser(); } } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "symfony, doctrine orm" }
Use value from Long calculated Select to Next statements? I have a query (in sp) which takes long time to Execute : e.g. Select name, age ,token1 from Mytable where id=2 //long calc.... //later on the same sp... select anotherCalc from Table2 where tokenId=token1 // token1 is from the prev query. How can i pass the value from 1st query to the second ? Ive tried : declare @tmp int Select name, age ,@tmp=token1 from Mytable where id=2 but its not working...
You can't mix a `select` that assigns to variables with one that returns results. If the first query only returns at most one row you can use SELECT @name = name, @age = age, @token1 = token1 FROM Mytable WHERE id = 2 IF(@@ROWCOUNT > 1) RAISERROR('Multiple rows returned - Indeterminate result',16,1) /*Return result to client*/ SELECT @name AS name, @age AS age, @token1 AS token1 SELECT anotherCalc FROM Table2 WHERE tokenId = @token1
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql server" }
Outgoing data Service Bus for Windows Server For the Service Bus for Windows Server performance counters are available for the number of incoming and outgoing messages per second. But a performance counter for the **_average_** incoming or outgoing messages in bytes is also available. But is there also a performance counter (or another solution) for the incoming (and/or) outgoing bytes for the service bus? (not network because it is for a development machine) Thanks in advance
All the counters seem to be documented here: < This is no specific counter for total bytes in/out. If you can't do that with a network performance counter, it seems the only workaround is to multiply the number of messages in or out by the average message size.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "servicebus, azureservicebus" }
Return all values in a column I am trying to return all the `productnames` from my MySQL table. At the moment this only returns the first name in the column public function selectAll () { $stmt = Database::get()->query('SELECT * FROM retrofootball_products'); while($row = $stmt->fetch()) { return $row['productname']; } } How do I get it to loop through and select all the productnames?
One way you could do is just select only the `productname` column, and then use `$stmt->fetchAll(PDO::FETCH_ASSOC)`. public function selectAll () { $stmt = Database::get()->query('SELECT `productname` FROM retrofootball_products'); return $stmt->fetchAll(PDO::FETCH_ASSOC); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, mysql" }
how to update web reference location i have an application wherein i am using a web-service. Now the ip address of the machine where this web-service was residing has changed. i try to update the web reference in my application and it is still trying to access the web-service from the old location. How do i change this to the new location. I have already updated the new location in my web.config file. Please help!! Thank you.
Right click the service, Choose configure and change the address.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, asp.net, web services, reference" }
Why does a character get Fate points from invocation only at the end of a scene in Fate Core? This answer to "What happens to the fate point after a character invokes an aspect?" shows that in DFRPG (per _Your Story_ , p. 106): > if you're invoking an aspect on another PC or on a NPC to gain an advantage over them, that character will receive the fate point you spent, either at the end of the exchange (in conflict, see page 197) or at the end of the scene (outside of conflict). But in Fate Core (p. 81): > if someone pays a fate point to invoke an aspect attached to your character, you gain their fate point at the end of the scene. **Why did Evil Hat change invocation so that Fate points are given out only at the end of a scene?**
## Because it discourages zero-sum exchanges. Someone just asked this of Fred Hicks in the Fate Core Kickstarter comments. He replied that if Fate points were exchanged immediately after the action in which they were used, the flow of Fate points would become zero-sum: > Let's imagine we're doing it your way. I have an aspect you're invoking, to my detriment, so I'm gonna be getting that fate point. > > You spend it and I get it right away. > > I take what I got from you right away and spend it to invoke one of your aspects. This cheapens the use of Fate points because you can get them back so quickly and easily, and compromises the flow of the narrative crisis/victory cycle that is the hallmark of the Fate point economy. A failure due to being invoked against shouldn't set you up for success in the next _exchange,_ but in the next _scene_.
stackexchange-rpg
{ "answer_score": 30, "question_score": 26, "tags": "fate core, fate points, invokes" }
Tree/Graph Traversal: Find maximum value path I'm attempting to, given a graph G with integer values and N levels, sum the values from the root to a leaf node. Find the maximal sum of these path values. Children nodes can have multiple parents, thats why its more a graph than a tree. For example, !enter image description here I tried implementing this via BFS for a small Java applet, but I'm not sure that was the best way. Are there other suggestions to keep this to scale with the number of nodes, i.e. O(n). I can't think of any way that scales to O(n). Any ideas?
You can solve this in linear time by using a dynamic programming algorithm to propagate the information from the nodes in the bottom layer upward. Think about it this way: if the graph has just one layer, then the optimal answer must be to just take the biggest value from that layer. On the other hand, suppose that the graph has n + 1 layers and assume that you've (recursively) computed the optimal solution for the bottommost n layers. In that case, you can find the optimal solution overall by looking at the top layer and computing, for each entry, the sum of that entry plus the optimal solution for any of its direct children (which you've already precomputed). The maximum value out of all of these then gives you the overall maximum value. This approach ends up visiting every edge exactly once, so the total runtime ends up being O(n + m), where n is the number of nodes and m the number of edges. Hope this helps!
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, algorithm, search, graph, tree" }
Git diff all local uncommitted changes I have a following problem. I want to get the output from `git diff`, but for all uncommitted local changes (that means unstaged and staged files). I am not searching for git log, or any other output, it has to be `git diff` output, because then I am parsing it with the parser I made. For now I have: All unstaged files: git diff Staged + unstaged files + all local commits (compare to remote) git diff origin/master Now I am missing the part when I can get `git diff` for all unstaged and staged files, but not compare it with remote (cuz it would take all local commits too), but just compare it with last local commit. Is there a way to do this?
Taken from this answer, to a similar (but I don't think duplicate) question, I think what you're looking for is: git diff HEAD This will show you all the differences between your current working directory (i.e. your staged and unstaged changes) and the HEAD commit. Or - if you prefer to match the syntax in your question, this would do the same thing: git diff master (where `master` is your current branch).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "git, git diff" }
Docker container running Mesos cluster and running other docker containers on cluster (using Marathon) I'm just starting off with Mesos, Docker and Marathon but I can't find anywhere where this specific question is answered. I want to set up a Mesos cluster running on Docker - there are a couple of internet resources to do this, but then I want to run Docker containers on top of Mesos itself. This would then mean Docker containers running inside other Docker containers. Is there a problem with this? It doesn't intuitively seem right somehow but would seem like it would be really handy to do so. Ideally I want to run Mesos cluster (with Marathon, Chronos etc.) and then run Hadoop within Docker containers on top of that. Is this possible or a standard way of doing things? Any other suggestions as to what good practice is would be appreciated. Thanks
You should be able to run it, taking care of some issues when running the mesos (with Docker) containers, like running in privileged mode. Take a look to jpetazzo/dind to see how you can install and run docker in docker. Then you can setup mesos in that container to have one container with mesos and docker installed. There are some references over the Internet similar to what you want to do. Check this article and this project that I think you will find very interesting.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "hadoop, docker, cluster computing, mesos, marathon" }
ASP.Net MVC jQuery UI DatePicker Date Format I'm at my wits end trying to force this jQuery datepicker control to understand specific date formats. What the hell is going on here? View @Html.TextBoxFor(model => model.StartDate, "{0:dd/MM/yyyy}", new { @class = "datefield" }) Javascript $(function () { $(".datefield").datepicker({ dateFormat: 'dd/MM/yyyy', showOn: "button" }); }); On page load !On page load datepicker clicked, so far so good !datepicker clicked date selected... what? !date selected
According to the documentation: * `dd` \- day of month (two digit) * `MM` \- month name long * `yy` \- year (four digit) So `dd/MM/yyyy` _should_ produce that result. (The day, the long month name, and the 4-digit year twice.) To match your initially loaded format, you'd want this: dd/mm/yy
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "javascript, jquery, asp.net, asp.net mvc, datepicker" }
Can't use www.saberparts.com When I go to a website that looks like using flash or java or somthing similar, it says that "your current browser isn't compatible with saberparts" and I actualized firefox, tried it with chrome, installed flash and java complement. I use ubuntu mate 15.04. Thank you for your help.
It isn't using Java or Flash. It's Three.js which uses WebGL. It might be possible your browsers aren't seeing a 3D graphics device powerful enough, or it might be that you don't have the drivers set up correctly, or it could just be that you don't have your browser set correctly. I'd start with the last by viewing the official WebGL support page. If that doesn't work it will direct you to your browser's settings. If that doesn't work, it's time to look at your graphics setup in Ubuntu. * * * It seems your Intel 945 integrated graphics might be so underpowered that it's been blacklisted to stop things grinding to a halt. It might also just not support enough features. However you can force Firefox to ignore the blacklist by opening `about:config` in Firefox (put that in the address bar) and setting the following keys to `true`: webgl.force-enabled layers.acceleration.force-enabled This may make Firefox crash however.
stackexchange-askubuntu
{ "answer_score": 8, "question_score": 2, "tags": "java, flash" }
ASIHTTPRequest equivalent for Android or any HTTP request manager/wrapper? I'm developing an app that will make extensive HTTP requests. I know for a fact that iOS has a third-party library called ASIHTTPRequest to manage and organize all these requests, making it much easier and less tedious. Is there a similar library available for Android?
According to this talk, if you're targeting pre-Gingerbread versions (<2.3) you should stick to Apache Http Client library. If however you're targeting Gingerbread or later, you will be safer to use the java.net.URLConneciton class as recommended by the Google engineer.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 11, "tags": "android, web services, http, libraries" }
How to select a table dynamically with HSQLDB and Hibernate? I have a table with references to other tables. Stored is the table name and the entity id. Like this: ref_table id | table_name | refId -------+------------+------- 1 | test | 6 2 | test | 9 3 | other | 5 Now I try to formulate an SQL/FUNCTION that returns the correct entities from the correct tables. Something like: SELECT * FROM resolveId(3) I would expect to get the entity with the id "5" from the table "other". Is this possible? I would guess I can do it with a stored procedure (CREATE FUNCTION). The function would have to inspect the "ref_table" and return the name of the table to use in the SQL statement ... but how exactly?
If you want to use the resuling entities in select statements or joins, you should use CREATE FUNCTION with RETURNS TABLE ( .. ) There is a limitation in HSQLDB routines which disallows dynamically creating SQL. Therefore the body of the CREATE FUNCTION may include a CASE or IF ELSE block that switches to a pre-defined SELECT statement based on the input value (1, 2, 3, ..). The details of CREATE FUNCTION are documented here: < There is one example for an SQL function with RETURNS TABLE.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, stored procedures, hsqldb" }
Energy of a complex exponential signal Noob question here. Why would the term \$j2\pi t\$ not have any effect on the energy of the signal? ![Complex Exponential Signal](
Just apply Euler’s formula. Hence $$|e^{at + jbt}|^2 = |e^{at} e^{jbt}|^2 = |e^{at} [\cos(bt) + j \sin(b t)]|^2.$$ Thus $$|e^{at + jbt}|^2 = e^{2at} [\cos^2(b t) + \sin^2(b t)] = e^{2at}.$$
stackexchange-electronics
{ "answer_score": 0, "question_score": 0, "tags": "communication, digital communications, homework" }
ElasticSearch _update_by_query filter elements of array Problem: I need to remove numbers > 25000000 from array in elasticsearch using _update_by_query. curl -XPOST ' --header 'Content-Type: application/json' --data ' {"query": { "range": { "multiAccounts": { "gte": 25000000 } } }, "script": {"source": "ctx._source.multiAccounts = ctx._source.multiAccounts;"} }' Insted of `ctx._source.multiAccounts = ctx._source.multiAccounts;` I need somethig like: ctx._source.multiAccounts = ctx._source.multiAccounts.filter(el < 25000000);
Since Painless relies on Java (and if `multiAccounts` is an array in your source document), then you can use streams, like this: ctx._source.multiAccounts = ctx._source.multiAccounts.stream().filter(el -> el > 25000000).collect(Collectors.toList());
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "elasticsearch, elasticsearch painless" }
git rebase "already up to date" when I know I am behind git switch develop git checkout -b <branchName> (do work here) npm run lint/prettier/test git stash git rebase develop git stash pop git commit -a -m '' git push origin <branchName> I'm having this issue when I'm working on my branch and the next day I try to rebase before I commit "Current branch is up to date." and when I commit bitbucket says I'm like x commits behind sync now. Why an I having these issues every time and what can I do to fix this? This is my git command flow. The git rebase never works and always says I'm up to date. The solution I've been doing is just cloning the repo every single time and copy pasting my changes before commit/pushing. Halp me!
When you do git rebase develop then develop refers to your local develop branch. If develop has been changed on the remote repo you should first integrate those changes into your develop. I.e. git switch develop git pull git switch <branchName> git rebase develop Or alternatively a little faster without updating local develop first # stay on <branchName> git fetch git rebase origin/develop
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "git, bitbucket" }
Starting Apache Nifi process group from CMD In Apache Nifi, is there any command to start particular process group from Command Prompt?
I was able to do this using curl commands
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "cmd, apache nifi, apache nifi registry, process group" }
Vectorized way of accessing row specific elements in a numpy array I have a 2-D NumPy array and a set of indices the size of which is the first dimension of the NumPy array. X = np.random.rand(5, 3) a = np.random.randint(0, 3, 5) I need to do something like for i, ind in enumerate(a): print X[i][ind] Is there a vectorized way of doing this?
Here you go: X = np.random.rand(5, 3) a = np.random.randint(0, 3, 5) In [12]: X[np.arange(a.size), a] Out[12]: array([ 0.99653335, 0.30275346, 0.92844957, 0.54728781, 0.43535668]) In [13]: for i, ind in enumerate(a): print X[i][ind] # ....: #0.996533345844 #0.30275345582 #0.92844956619 #0.54728781105 #0.435356681672 I'm assuming here that you don't need each value on a separate line and just want to extract the values.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, numpy, vectorization" }
List all tables in Hibernate I want to list all table names from database. My application has to be independent from DBMS. Different DBMS has different command to list tables, e.g: PstgreSQL: `SELECT * FROM pg_catalog.pg_table`s MySQL: show tables Oracle: SELECT DISTINCT OBJECT_NAME FROM DBA_OBJECTS WHERE OBJECT_TYPE = 'TABLE' I think that I should use hibernate because writing different SQL query for all DBMS is uncomfortable. There are examples in network how to list tables in hibernate, but all examples which I found list only mapped entitites. I want to list all table names regardless of hibernate entities.
This post explains how to do it using JDBC driver, which is IMHO a better approach then using hibernate for this. I'll post the code here also, for reference Connection conn = DriverManager.getConnection("", "", ""); DatabaseMetaData md = conn.getMetaData(); ResultSet rs = md.getTables(null, null, "%", null); while (rs.next()) { System.out.println(rs.getString(3)); // 3rd column is table name }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "sql, hibernate" }
C: Cannot declare pointer inside if statement I have a pointer which points to a function. I would like to: if (mode == 0) { const unsigned char *packet = read_serial_packet(src, &len); } else { const unsigned char *packet = read_network_packet(fd, &len); } But I cannot do it because my compiler complains when I first use the pointer later in the code. error: 'packet' undeclared (first use in this function) This is strange. It worked without the if statement, but now I need my program to be able to get data from different sources. Isn't it possible to do this? I think so. If it isn't, is there any other simple way to get what I am trying? Thanks a lot.
You need to review the concept of _blocks_ or _compound-statements_ , or variable scope. If you declare a variable in a compound statement (`{`, `}`), the variable will be declared only in that exact scope. Thus, change your code to const unsigned char *packet = NULL; if (mode == 0) { packet = read_serial_packet(src, &len); } else { packet = read_network_packet(fd, &len); } // Now you can perform operations on packet.
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 1, "tags": "c, conditional statements, lexical scope" }
How to find element with specific class attributes in selenium (python)? On Windows Server 2012 I am using selenium 2.53.6, and I want to check if the `class` contains the element `lock-icon` for the following html element: <a href=" class="more-link lock-icon" target="_blank"> Selenium Projekt dianep geheim </a> I tried the following expression with the python API: find_element(by=By.CSS_SELECTOR, value="more-link.lock-icon") but it returns a `None` although the element (shown above) is visible on the website. How to do it correctly?
try: find_element(by=By.CSS_SELECTOR, value="a.more-link")
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, selenium" }
Footnotes in a single paragraph in Beamer The answer to Horizontal placement of footnotes in beamer shows how to have two columns of footnotes in beamer, but it doesn't answer how to have footnotes in a single paragraph separated by commas. footmisc does not work with beamer. How can I redefine or patch commands to allow footnotes in the format desired? beamerbaseframecomponents.sty seems to be the file to work with, but so far I haven't had success editing things. I've made footnotes disappear, changed fonts and spacing, but I just can't put it all on one line!
Here's one way. Be careful not to abuse the power `parnotes` provides.... \documentclass{beamer} \usepackage{parnotes}% \begin{document} \begin{frame}{My Frame} Some important thoughts: \begin{itemize} \item Foo\parnote{First note} \item Bar\parnote{Second note} \item Baz\parnote{Third note} \end{itemize} %\vfill % <-- compare difference \parnotes \end{frame} \end{document}
stackexchange-tex
{ "answer_score": 5, "question_score": 2, "tags": "beamer, footnotes" }
evaluating some limits with $\ln(x)$ I don't understand how to prove these results. $\lim\limits_{x \to +\infty}\dfrac{\ln{x}}{x} = 0$ $\lim\limits_{x \to 0^{+}}x\ln{x} = 0$
Since $$\lim _{ x\rightarrow \infty }{ \frac { x }{ { b }^{ x } } =0,b>1\quad } $$ then for enough big $x$ : $$\frac { 1 }{ { b }^{ x } } <\frac { x }{ { b }^{ x } } <1$$ denote $b=e^{ \varepsilon }$ for small arbitrary $\varepsilon >0$ then we get: $$\frac { 1 }{ { e }^{ \varepsilon x } } <\frac { x }{ e^{ \varepsilon x } } <1$$ or $$1<x<{ e }^{ \varepsilon x }$$ take the natural logarithm of both sides,we get $$\\\ 0<\ln { x } <\varepsilon x$$ from this for enough big $x $ we finally get $$0<\frac { \ln { x } }{ x } <\varepsilon $$
stackexchange-math
{ "answer_score": 1, "question_score": 3, "tags": "calculus, limits, logarithms" }
Java cyrillic encoding I have input string - `UAH;"Ãîëüô 855229-7"`, it should be displayed like `UAH;"Гольф 855229-7"`, I'm trying to use `Cp1251` encoding, but get output `UAH;"????? 855229-7"`. String cyrillic = row[0] + row[1]; String utf8String= new String(cyrillic.getBytes("Cp1251"), "UTF-8"); lbl1.setText(utf8String);
UTF-8 has nothing to do with this. All of your characters in `cyrillic` are being represented as single bytes. Currently, those bytes are in the ISO 8859-1 encoding, also known as Latin-1, which is a subset of the Windows English code page, Cp1252. So, you want to encode the string as Cp1252, then decode the resulting bytes as Cp1251: String corrected8String = new String(cyrillic.getBytes("Cp1252"), "Cp1251");
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, character encoding" }
what is the ruby on rails server port range and how to run the multiple ports using same server what is the ruby on rails server port range? want to know the server port no range for ruby on rails . please guide me how to run the multiple ports using same server? want to run the same application in the different server port number like 3000 , 3005
* The port range very much depends on the underlying operating system. It has nothing to do with Ruby or Rails. * Do you want to run different instances with different port numbers or a single instance accessible from multiple ports? Either way you might want to look into setting up a proxy server in front of your instances (nginx can act as proxy for example).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "ruby on rails, ruby, ruby on rails 3, web, port" }
one score at a time, update method I'm creating a simple game with SpriteKit (mostly for learning), and I got a question about score adding. some background: I'm checking if a sprite (SKShapeNode) contains another one, if true, I'm checking their color, if it is the same color, the player should get 1 score. I wrote this function: func onMatch(){ for ring in mColorRings { if(mPlayer.contains(ring.position)){ if mPlayer.fillColor.isEqual(ring.fillColor) { score += 1 mScoreLbl.text = "\(score)" } } } } which works, the problem is, I'm calling this function inside the update method. as the update method runs a lot, it calls my function a lot of time and as long as `mPlayer` contains `ring` it is adding 1 score to the player. How can I avoid that ?
Ok, so this is what i suggest: var playerPassed = false func onMatch(){ for ring in mColorRings { if(mPlayer.contains(ring.position)) { if ((mPlayer.fillColor.isEqual(ring.fillColor)) && playerPassed == false) { score += 1 mScoreLbl.text = "\(score)" playerPassed = true } } } } You're creating a bool and you check if that is **false** (default) and if so, the block executes and when it does, the bool is set to **true** and the condition will be false and no longer return true.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "swift, sprite kit" }
Optimization of arrow functions in react Apart from needing to create a new function each time `render` is invoked, are there any other differences from using: class { on = () => true render = () => <z on={this.on} /> } vs class { render = () => <z on={() => true} /> } For example, are there any optimizations that browsers make? Are there any implementation differences? If there are zero differences, would it make sense for something like bable to transform the code to avoid creating the function in the `render` function?
From Reactjs point of view, since the arrow function creates a new function everytime, it could potentially cause two performance related problems: * Could invoke the garbage collector more frequently than usual * Will cause unnecessary re-render of your components(even the pure components) as new function will be considered as a new prop. There is already a babel plugin that solves this re-render problem caused by using arrow fn: reflective-bind The performance benefit from using this plugin has been described here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, reactjs, babeljs" }
Java SWT extending another class for Dialogs Every dialog window in SWT should extend the `Dialog` class, but I also have my own class `View`, that my dialogs also should extend. OK, you should just make your `View` to `extends Dialog`, you can say. But the problem is, that my `View` shouldn't do it, because it also is used for classes, that aren't SWT dialogs. Is there a way to overcome this problem?
class ViewDialog extends Dialog { View view; } class DialogView extends View { Dialog diag; } Not everything has to extend. Not everything is another object. Some objects have other objects. A dialog can have a view that it displays or a view can have a dialog that displays it. If anything it doesn't really make sense for a dialog to also "be" the content that it displays.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, oop, inheritance, extends" }
Bash - How to share constants between scripts? Is there a way to make it so that there isn't a list of constants at the top of every bash script i have? I have a lot of readonly constants for formatting and such but having them at the top of every single one of my scripts takes up space. Is there a way to make a separate script containing all of them and access it or something? or some way to clean it up?
Use a common script that you `source` in your other scripts. E.g. `source common.sh` will execute that file and you may export variables there. This is also how files like `.bashrc` and `.bash_profile` work, it is sourced when you execute bash (the latter when it is a login shell). When you change `.bashrc`, you can source it again in the running shell for the changes to take effect.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "bash, constants, code cleanup" }
Web development transition from MAMP to Docker I am new to Docker and I am having a hard time applying its core technology to my present web development. Using MAMP, you just need to download the app, put your PHP/HTML files on /htdocs, start servers, then go to < to see your webapp. Now, using docker, I’m wondering how can I do the same. What I’ve done so far is to pull http, php and mysql images from the Docker Hub. 1. How can I link these three images together to make them work? Or How should I run them simultaneously? 2. Where should I put the /htdocs or how can I access it? 3. MAMP has a phpMyAdmin for database access, does Docker has something like this? I’m working on a Mac OS X Yosemite (10.10.1) with boot2docker v1.4.1 and VirtualBox 4.3.20.
> 1. How can I link these three images together to make them work? Or How should I run them simultaneously? > Use fig to define and link containers. > 2. Where should I put the /htdocs or how can I access it? > This depends solely on your container configuration. You may try PHP with Apache from DockerHub. See the docs for an explanation where to put your files. > 3. MAMP has a phpMyAdmin for database access, does Docker has something like this? > Sure, a Docker container ;) search DockerHub
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 11, "tags": "php, mysql, web, docker, boot2docker" }
React state is undefined even if on console log is defined <li className="field-title">Role: </li> {console.log(this.state.userData.roles)} {this.state.userData.roles.map((role) => { return ( <li>{role.name}</li> ) })} When I console log the state of userData it shows the actual array value. But when I am using the mapping it says that: > this.state.userData.roles is undefined Why is this happening and how can I solve this?
Try this code - { this.state.userData && this.state.userData.roles && this.state.userData.roles.length > 0 && this.state.userData.roles.map( (role) => ... /*rest of your code*/ ) }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, reactjs" }
Integration of Wiener process: $\int_{t_1}^{t_2} dB(s)$ We all know that $\int_0^t dB(s) = B(t)$, where $B(t)$ is a standard Brownian Motion. However, is the following identity true? Also, why or why not? $\boxed{ \displaystyle \ \ \int_{t_1}^{t_2} dB(s) = B(t_2) - B(t_1)}$
If you recall the definition of the stochastic integral with respect to a Wiener process $(B_t, t \geq 0)$, it is plain that for $0 \leq a < b \leq T$ we have $$ \int_{0}^{T} \xi \cdot \mathbf{1}_{[a, b)}(s) \, dB_s = \xi \cdot (B_{b} - B_{a})$$ for _bounded_ $\mathcal{F}_a$-measurable random variable $\xi$. Extending to the $L^2$-case is immediate in view of the Itō isometry. However, for a general process $X = (X_t : t \geq 0)$, we cannot say much about the integral $$ \int_{0}^{T} X_{s} \, dB_{s}$$ even we assume a mild condition to $X$. For example, for a $C^2$ function $f$ we have $$ f(B_t) - f(B_s) = \int_{s}^{t} f'(B_s) \, dB_s + \frac{1}{2} \int_{s}^{t} f''(B_s) \, ds,$$ which is the celebrated Itō formula.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "stochastic processes, brownian motion, stochastic integrals, stochastic calculus, stochastic analysis" }
Added the same socket fd twice to fd_set then calling select I'm been reading the man page for select (from difference sources) and can't seem to get a straight explanation. Lets say I have an already connected socket like this: s1 = socket(...); connect(s1, ...)... Now lets say I add the socket twice (eg: mistakenly) to the same fd_set like so: fd_set readfds; FD_ZERO(&readfds); FD_SET(s1, &readfds); .... FD_SET(s1, &readfds); Now I call select: int rv = select(n, &readfds, NULL, NULL, &tv); if (rv == -1) { perror("select"); // error occurred in select() } else if (rv == 0) { printf("Timeout occurred! No data after 10.5 seconds.\n"); } else { // one the descriptors have data ..... } If data is send from the socket, will select have set both FDs as ready or only the first one that I've added?
Since `FD_SET` is a set (in the mathematical meaning of the word), any file descriptor is either _in_ it or it is _not_. Adding the same descriptor to the set more than once has no effect.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "c, sockets, select, networking" }
Are Calendars considered to be Azure AD based resources? < states that Azure AD based resources are subject to a Per app and tenant combination: 7 total subscriptions Calendars are assigned to users. Does this mean that they are "Azure AD based resources"? I'm hoping to be able to have hundreds of subscriptions active for a single tenant.
Well since the line reads: > Certain limits apply to Azure AD based resources (users, groups) and may generate errors when exceeded: I'd assume it only applies to users and groups which reside in Azure AD. Office 365 Calendars do not, MS Graph API gets them from the Outlook Calendars API. And it's not too hard to test this, try creating 8 subscriptions :)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "azure, azure active directory, microsoft graph api" }
Как правильно произносить фамилию Беен (немецкая)? Например Фриц Беен. Следует тянуть "е" или произносить её как двойную?
Если речь идет об актере и режиссере Бене Фритце, то, во-первых, стоит писать его имя только так: Бен Фритц — в языке-источнике оно записывается как Ben Fritz. Тогда вопрос отпадает. Во-вторых, в подобных случаях обычно произносятся обе гласные, ср. Илья Леенсон.
stackexchange-rus
{ "answer_score": 0, "question_score": 0, "tags": "гласные" }
If $p^k|n!$ then $p!^k|n!$ Is there a direct proof of the result that if $p$ is a prime and if $p^k|n!$ then $p!^k|n!$? The proof that I know is rather circuitous (take $k$ to be given by de Polignac's formula and construct a subgroup of $S_n$ of order $p!^k$). The result seems too elegant to not admit a slick combinatorial proof.
Induction on $n$: If $n=mp+r$ with $0\le r<p$, there are $\frac{n!}{p!^mr!m!}$ ways to partitoin $n$ objects into $m$ indistinguishable subsets of size $p$ each and a rest of size $r$. Note that $p^{k-m}\mid m!$ (because the multiples of $p$ among $1,2,\ldots, n$ are precisely $p,2p,,\ldots, mp$) and by induction hypothesis $p!^{k-m}\mid m!$. Hence $p!^n\mid p!^mm!\mid n!$.
stackexchange-math
{ "answer_score": 2, "question_score": 7, "tags": "combinatorics, elementary number theory" }
Add Ponytails in avatar I don't use blender so much and I need help. I would like to create a ponytail like the image in the link, I don't know how to create the curve (shape) in the image. Can you help me? I appreciate also YouTube tutorial. Thanks! <
To create hair, a method is to create a curve, and under _Object Data > Geometry_, click on _Object_ , and choose your _Object_ and your _Taper object_ , which are 2 other curves that you need to edit the way you want to define the section profile and the length profile: ![enter image description here](
stackexchange-blender
{ "answer_score": 1, "question_score": 1, "tags": "bezier curves" }
How to use your own mysql database server with heroku? I want to use mysql database which is hosted on my own server. I've changed DATABASE_URL and SHARED_DATABASE_URL config vars to point to my server, but it's still trying to connect to heroku's amazonaws servers. How do I fix that?
According to the Heroku documentation, changing `DATABASE_URL` is the correct way to go. > If you would like to have your rails application connect to a non-Heroku provided database, you can take advantage of this same mechanism. Simply set your DATABASE_URL config var to point to any cloud-accessible database, and Heroku will automatically create your database.yml file to point to your chosen server. The Amazon RDS Add-on does this for you automatically, though you can also use this same method to connect to non-RDS databases as well. Here's an example that should work: `heroku config:add DATABASE_URL=mysql://user:password@host/db` You may need to redeploy by making a change and running `git push heroku master`
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "ruby, heroku" }
How to efficiently filter maximum elements of a matrix per row Given a 2D array, I'm looking for a pythonic way to get an array of same shape, with only the maximum element per each row. See max_row_filter function below def max_row_filter(mat2d): m = np.zeros(mat2d.shape) for r in range(mat2d.shape[0]): c = np.argmax(mat2d[r]) m[r,c]=mat2d[r,c] return m p = np.array([[1,2,3],[5,4,3,],[9,10,3]]) max_row_filter(p) Out: array([[ 0., 0., 3.], [ 5., 0., 0.], [ 0., 10., 0.]]) I'm looking for an efficient way to do this, suitable to be done on big arrays.
Alternative answer (this will keep duplicates): p * (p==p.max(axis=1, keepdims=True))
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, arrays, numpy, max" }
php mysqli stmt i'm new to the php mysql usage. i'm selecting the results from database .. and i'm cycling/printing them out to the screen using while($stmt->fetch()): .. what i'd like to do is to cycle through the results again after the first cycle without calling the database (frombuffered results set). i'm using php5, mysqli, stms on xampp server.
You can use arrays. When you cycle through the result for the first time you can put the values in the array and later in the 2nd cycle you can access the elements from the array. Something like: $query = "SELECT name FROM EMP"; $arr = array(); if ($stmt = $mysqli->prepare($query)) { $stmt->execute(); $stmt->bind_result($name); // 1st cycle. while ($stmt->fetch()) { $arr[] = $name; // save in array. } $stmt->close(); // 2nd cycle. foreach($arr as $name) { // use $name again. } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, mysqli" }
How to make the smoke become a mask layer? Im a beginner in video editing industry, so I got one main question and few sub questions based on this video: **Main question** \- The intro title cover by smoke effect, when the smoke effect pass by then it reveal the text, after that it become a shape. How are those done? **Sub question** * how the background been made? it is like a curtain and keep moving, is that made by After Effect or others software? * at 0:04 when the food shown up, how is the small sparkling effect that surrounding the food?
Grab a pre-keyed smoke element from somewhere. Mask the smoke element as desired. Copy that mask onto the text or you can parent the mask as an adjustment layer. Keyframe opacity of text, linear wipe with feather in a gradient/ramp solid for the background. The "sparkling" effects are lens flares (see JJ Abrams) The curtain moving effect could be just another preset with the layer style set to overlay. Or you can generate your own layer like that using fractal noise.
stackexchange-avp
{ "answer_score": 2, "question_score": 0, "tags": "video, after effects, video editor, editing, transitions" }
In D&D 4e, does the half-elf get an extra encounter power, or does his race power take the place of his class power? The half-elf gets a racial power that lets him take an at-will from a class not his own and make it an encounter power. Does that mean it replaces his class encounter power or that he gets an additional encounter power?
You seem to be talking about the Dilettante. this does not replace anything. It is a bonus Racial power. The first Player's Handbook has the details on page 42 as does Player Essentials: Heroes of the Forgotten Kingdoms on page 252. If it replaced something the text would say it.
stackexchange-rpg
{ "answer_score": 12, "question_score": 8, "tags": "dnd 4e, powers, half elf" }
Why does Coop Mode not work for my Assembly? I have three assemblers currently on my station. Two are marked for Coop Mode and named Slave I and Slave II. I only issue build orders to the Master Assembler. But the other 2 assemblers do not get any build orders. I can issue direct orders to the slave assemblers though. !Master Screenshot !Slave I !Slave II It starts working when I set my entire base to be owned by nobody though. It won't work when everything is owned by me. Is there a way to get my assemblers working while the base is owned by me without tearing down/rebuilding the whole base? All Items in the base are currently owned by me and shared with the faction (Screenshot says differently, but I changed it), I double checked that.
This seems to be a bug in the current build. If one wants to work around it, set the owner to yourself and share the assemblers with **everyone**. This makes them work in coop mode again. Another solution is to build them in a way that does not require the use of any conveyors, including the connection to any sort of container.
stackexchange-gaming
{ "answer_score": 1, "question_score": 1, "tags": "space engineers" }
NDSolve::ndode: Input is not an ordinary differential equation I am new to Mathematica. I am working on solving the following different equations numerically written in the code as below. www[x_] := Sin[x^2] NDSolve[{x'[t] == -3 www[x[t]] (x[t] - y[t]), y'[t] == -x[t] z[t] + 27 x[t] - y[t], z'[t] == x[t] y[t] - z[t]}, {x, y, z}, {t, 0, 20}]; Plot[Evaluate[{x[t], y[t], z[t]} /. %], {t, 0, 20}, Frame -> True] Where is my mistake and how fix it?
Your mistake has nothing to do with _Mathematica_. For solving a differential equation numerically, you need to provide inital- (or boundary-) conditions. Here is your code that runs. Please adapt it to your needs: www[x_] := Sin[x^2] NDSolve[{x'[t] == -3 www[x[t]] (x[t] - y[t]), y'[t] == -x[t] z[t] + 27 x[t] - y[t], z'[t] == x[t] y[t] - z[t], x[0] == 5, y[0] == 2, z[0] == 1}, {x, y, z}, {t, 0, 20}]; Plot[Evaluate[{x[t], y[t], z[t]} /. %], {t, 0, 20}, Frame -> True] !Mathematica graphics
stackexchange-mathematica
{ "answer_score": 2, "question_score": 0, "tags": "differential equations, warning messages" }
Как передать переменную из сидера в factory? У меня в сидере есть цикл: public function run() { for ($i = 0; $i < 100; ++$i) { CharacterEpisode::factory()->count(3)->create(['title' => $i]); } } Я хочу переменную $i передать в factory: public function definition($title) { return [ 'character_id' => $title, 'episode_id' => $this->faker->unique()->numberBetween($min = 1, $max = 30), ]; } Но у меня выдает ошибку: > Declaration of Database\Factories\CharacterEpisodeFactory::definition($title) must be compatible with Illuminate\Database\Eloquent\Factories\Factory::definition()
В фабрике вы указываете значения "по умолчанию" для всех атрибутов. Если нужно их переопределить, то передаете соответствующий массив. Читать тут: Переопределение атрибутов То есть, в сиде будет так: public function run() { for ($i = 0; $i < 100; ++$i) { CharacterEpisode::factory()->count(3)->create(['character_id' => $i]); } } А из фабрики убрать `$title`.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, laravel" }
Weird result comparing property values using reflection Can someone explain why this is occurring? The code below was executed in the immediate window in vs2008. The prop is an Int32 property (id column) on an object created by the entity framework. The objects entity and defaultEntity were created using Activator.CreateInstance(); Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) false
I assume you're wondering why the third line prints false. If you want to know why the first two lines are printing 0, you'll have to post more code and tell us what you actually expected. `Convert.ChangeType` returns `object`. Therefore when the property type is actually `Int32` it will return a _boxed_ integer. Your final line is comparing the _references_ of two boxed values. Effectively you're doing: object x = 0; object y = 0; Console.WriteLine (x == y); // Prints False You can use `Equals` instead - and the static `object.Equals` method handily copes with null references, should that be an issue: object x = 0; object y = 0; Console.WriteLine (object.Equals(x, y)); // Prints True
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "comparison, properties" }
MySQL Select The Most Recent Incoming or Outgoing Messages of Distinct Users I have a table structure where I keep records of the messages sent and received like below; !Database table structure member_id1 is the sender and member_id2 is the receiver. Now what I'm trying to achieve is to get the rows with the most recent messages of the user who has the member_id of 3. The result should contain only 2 rows with the message ids of 2 and 4, as 2 is the last message between the user with the member_id of 3 and the user with the member_id of 2, and 4 is the only message between the user with the member_id of 3 and the user with the member_id of 1 yet. The result shouldn't contain the rows with the message_id of 3 for it has nothing to do with the user who has the member_id of 3, and the message_id of 1 because it has been overdated by the message with the message_id of 2. Hope I've made my question clear for people who can help me with this problem.
I think I've figured out the right answer for my own question. Although I'm not quite sure, it seems to work great. For those who need a solution to such a problem; give this a try: SELECT m1.* FROM table_name m1 INNER JOIN (SELECT MAX(senddate) AS senddate, IF(member_id2 = 3, member_id1, member_id2 ) AS user FROM table_name WHERE (member_id1 = 3 AND delete1=0) OR (member_id2 = 3 AND delete2=0) GROUP BY user) m2 ON m1.senddate = m2.senddate AND (m1.member_id1 = m2.user OR m1.member_id2 = m2.user) WHERE (member_id1 = 3 AND delete1=0) OR (member_id2 = 3 AND delete2=0) ORDER BY m1.senddate DESC
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
Using Stokes' theorem around a circular loop ![enter image description here]( I know that I have to use: $$\oint F\cdot dr = \iint \operatorname{curl}(F)\cdot n \;dS,$$ with $\operatorname{curl}(F)= -x j -yk$ and $n\;dS = dA\; k$ But the dot product of the curl and $dS$ leaves me with $$\iint -y \; dA$$ but I am unsure how to proceed from here. Do I need to change coordinate systems as I am dealing with a cicle? Any help is appreciated!
In order to apply Stoke's Theorem to evaluate $\int_CF\cdot d\vec{r}$ where $C$ is the circular loop $x^2+y^2=a^2$ you need to first establish a surface $S$ whose boundary is $C$ and is equipped with a normal vector $\vec{n}$ that induces the original orientation prescribed to $C$. Let's take $S$ to be the circular disc $$\\{x^2+y^2\leq a^2,z=0\\}$$ which we'll parameterize by $$\vec{r}(u,v)=(u\cos(v),u\sin(v),0)$$ on the domain $0\leq u\leq a$ and $0\leq v\leq 2\pi$. Clearly the vector $\vec{n}=\big<0,0,1\big>$ is perpendiular to $S$ and induces a counterclockwise orientation on its boundary $C$. (I'm assuming you're prescribing a counterclockwise orientation to $C$.) A little bit of calculation also reveals that $$\text{curl}(F)=\big<0,-1,-1\big>$$ $$\vec{r}_u \times \vec{r}_v=\big<0,0,u\big>$$ $$dS=||\vec{r}_u \times \vec{r}_v||dudv=ududv$$ So with Stoke's Theorem, $$\int_C F \cdot d\vec{r}=\int_{S}\big[\text{curl}(F)\cdot \vec{n}\big]dS=\int_0^{2\pi} \int_0^a -ududv=-\pi a^2$$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "integration, vectors, surfaces, stokes theorem" }
When to initialize the collection I have define a collection like List ids. I am wondering which is better 1) initialize in the declaration 2) initialize int he constructor.
You should declarate it in the constructor, not only for readability but also for inheritance matters. You might want to inherit another class from that and maybe for that particular new class you would like to overwrite the constructor because it has different parameters.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, .net" }
Potential of metric tensor As I understand so far, the metric tensor of a Riemannian manifold is an $n \times n$ matrix in many specific examples. As such it could formally be the curl of some vector potential or just the derivative. I wonder if this is indeed possible and if yes, if it is interesting or really just a formal coincidence.
If I do not misunderstand your question your are asking if it is possible to define a more primitive object than the metric tensor, on a smooth manifold $M$, from which we can derive the metric tensor $g$, isn't it?. Such a more primitive object of course must be called _potential_. This approach recall me the so called Kaehler manifolds < Kaehler manifolds form a subclass of Riemannian manifolds. For them there is indeed a concept of potential. Namely, around each point of a Kaehler manifold the metric tensor can be recovered from a function called potential. The recovering procedure is something like taking the Hessian of the potential. The following post develops the idea of Hessian type metric on a Riemannian manifold: <
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "riemannian geometry" }
Incompatible types in assignment of int to char void trinti1() { int b,lines; char ch[20]; FILE* file = fopen ("Kordinates.txt", "r"); while(!feof(file)) { ch = fgetc(file); if(ch == '\n') { lines++; } } fclose(file); } Hello guys I am trying to count lines in file, but seems `fgetc(file)` returns `int` and it can't be converted to char. Help me what I am doing wrong?
In your code `ch` is not a `char`, it is `char[20]` \- an array of 20 characters. You cannot assign a result of `fgetc` to it, because `fgetc` returns an `int` (which contains either a single `char`, or an `EOF` mark). Change the declaration of `ch` to `int ch` to fix this problem. You can also drop the call to `feof` because it happens at the wrong time anyway (you call it after read operations, not before read operations). for (;;) { int ch = fgetc(file); if (ch == EOF) break; if (ch == '\n') lines++; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c" }
is there a toggleSrc method in jQuery? Does jQuery have something like toggleSrc :-p ?? I want to change src of an image on slideToggling of a div.is there something like that give me the chance of not writing conditional statement to check the src of image to change to another src. (I am not lazy !!!)
There isn't a built-in method for this, but you could make a plugin for it, for example: $.fn.toggleSrc = function(onSuffix, offSuffix) { return this.attr("src", function(i, src) { return src.indexOf(onSuffix) != -1 ? src.replace(onSuffix, offSuffix) : src.replace(offSuffix, onSuffix); }); }; Then you'd call it like this: $("img").toggleSrc("_on", "_off"); ...or a big safer: $("img").toggleSrc("_on.jpg", "_off.jpg"); You can test it out here. There are (as usual) 10 _other_ ways to do this as well, this is just one example of how to do this and save you some code repetition.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, jquery selectors" }
iOS auto-layout constraints I'm unsure of how I should set up some constraints in my auto-layout storyboard in iOS. I have a textbox and a button next to it, constrained to each other, and they're both constrained to the sides of their superview by 20. It works great for iPhones/iPods. Moving up to iPad, however, the textbox becomes too wide. Is there some way to set a "max width" on the text box in order to allow some growth, and allow the constrains to the superview grow after that point? It feels like I'm approaching it all wrong, do I have the wrong approach?
**The constraint** You can set a constraint for "width less than or equal to X" (whatever your value X is). Then pair that with your "trailing edge space to the edge of the superview is equal 20". **The Conflict** This will not work as it is though as if the superview is too wide it will create a conflict. **Priorities** What you can do though is give the "edge space" constraint a priority of 1 less than the priority of the width constraint. So if the width constraint has a priority of 750 (which is default) then give then space constraint a priority of 749. This has the effect of telling AutoLayout. "If there is a conflict, then break gracefully by 'removing' the space constraint and keeping the width constraint".
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, autolayout" }
Load jar file contained within another jar file not working I've been playing around with loading jar files dynamically and I can't get this to work. I have a jar file (resource.jar) in my source folder of Eclipse so it's in the classpath. I'm trying to get it as a resource to load an applet, add it to a jframe, and run it. This isn't working for some unknown reason to myself. This is the code I'm trying. URL jarURL = getClass().getClassLoader().getResource("resource.jar"); ClassLoader urlLoader = new URLClassLoader(new URL[]{jarURL}); applet = (Applet) urlLoader.loadClass("test.TestClassApplet").newInstance(); jframe.add(applet); applet.init(); applet.start(); I get no error when I try to get the resource, the error is when I load the class. I get a ClassNotFoundException, even though the class IS in the jar file.
URLClassLoader is designed to be used for loading classes and resources that are accessed by searching a set of URLs. It won't extract the class in the jar file for you. See JarClassLoader tutorial.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, resources, classloader" }
scrollTop() returns 0 if there is a doctype In Firefox 39.0 and IE 11, if a HTML5 document has a doctype `<!doctype html>`, `document.body.scrollTop` will always return `0`. For example: <!DOCTYPE html> <!--doctype--> <html> <head> <title>Sample page</title> </head> <body> Aliquip summis doctrina admodum, pariatur praesentibus non laboris aut an eram... <script> window.addEventListener("scroll",function(){ console.log(document.body.scrollTop); }); </script> </body> </html> The above always logs 0 in the console when you scroll, but if you remove the `doctype`, it returns, as expected, the distance from the top the body has been scrolled. Note that it works with or without a doctype in Chrome. I would rather not remove the doctype, and am wondering why it does this, and if there is a way around it?
Use this: `document.documentElement.scrollTop.` `document.body.scrollTop` is deprecated. If you need it to be browser specific, you can if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1){ scrollTo(document.documentElement, y, 200); }else{ scrollTo(document.body, y, 200); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, html" }
Showing WMS layer data and marker popup simultaneously in Leaflet I need to show WMS layer information and if there are some marker or other layers at the same coordinate, it should show both data of WMS layer and marker information. But when marker covers wms layer, click would not trigger getfeatureinfo to get WMS data. Is there any method to show both? My marker: L.marker([lat,lng], { icon: icons }).bindPopup( '<table><thead><tr><th>test</th></tr></thead ><tbody align="center"><tr><td>context</td></tr>' ).openPopup(); I write a sample on codepen: < I want to trigger map.on('click') event when click the marker, that means both alert and popup would show on web.
Since mouse `click` event gets caught by marker popup handler and does not reach the map, solution is to fire map `click` event yourself inside marker `click` event handler. Code could then look something like this: marker.on('click', function(evt) { map.fire('click', evt, false); });
stackexchange-gis
{ "answer_score": 1, "question_score": 2, "tags": "leaflet, geojson, wms, getfeatureinfo" }
display ckeditor data saved in database in div tag > i want to display ckeditor data saved in dadabase in div tag. I mean, I save ckeditor data to the database and restore this data to the div tag and also with the tags being applied to that text. > > When typing this code, the following text will be displayed this is code: <div> {{$object->text}} </div> > It displays this; I want these tags to apply html> <head> <title></title> </head> <body dir="rtl"> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry.
{!! $object->text !!} string will auto escape when you'll use {{ }}
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "php, html, laravel, ckeditor" }
interpret effect of interaction term between two binary variables on continuous outcome If I set up an interaction term between two dichotomous variables, let's say experiment (1= control, 2 = experiment group) and gender (1 = male , 2 = female). If the effect of the interaction term (experiment*gender) on happiness is .46 using regression, does that mean the experiment increased happiness in females more than males?
Issues of statistical significance aside, that would be the interpretation as long as you had the level effects as well (say if your model also included a constant as well as experiment and gender coefficients).
stackexchange-stats
{ "answer_score": 0, "question_score": 0, "tags": "regression, interaction" }
An explicit ring quotient I need to calculate the quotient $\mathbb{Z}\left[\frac{1}{2}\right]/\left(3\mathbb{Z}\left[\frac{1}{2}\right]\right)$. I tried to factorize it as $\mathbb{Z}[X]/(2X-1,3)\cong\mathbb{F}_3[X]/(2X-1)$. I observed that in $\mathbb{F}_3[X]$, $(2X-1)=(2)(X-2)$ and that $\mathbb{F}_3[X]/(X-2)\cong \mathbb{F}_3$, $\mathbb{F}_3[X]/(2)\cong 0$, but the quotient seems to be quite a strange object and not as simple... My question is, is there a simple description of the quotient ring and how to demonstrate?
In $\Bbb F_3$, $2X-1=-X-1=-(X+1)$. Then your quotient is $\Bbb F_3[X]/(X+1)\cong\Bbb F_3$.
stackexchange-math
{ "answer_score": 3, "question_score": 4, "tags": "number theory, elementary number theory, ring theory, commutative algebra" }
Check if a field in Meteor.users collection is true / false? I have a field in the `Meteor.users` collection that can be set to `true` or `false`. I want to check if the field for the current user is equal to `true` or `false`. How would this be done?
**inside a template** {{#if currentUser.isAwesome}} <p>You are awesome!</p> {{/if}} **inside a publish function** Meteor.publish('something', function() { var user = Meteor.users.findOne(this.userId); if (user.isAwesome) console.log('You are awesome!'); }); **anywhere else** if(Meteor.user().isAwesome) console.log('You are awesome!'); Note: If your custom field isn't visible on the client, please see this question.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "meteor, meteor accounts" }
Output raw image from Imagick image in PHP I'm using Imagick lib to do some modifications to original image. Then I'd like to output it directly to browser without saving. Is there a way to do that? I tried to use `Imagick::writeImage('STDOUT')` (empty output) and 'php://stdout' with error "Unable to write to file". Any ideas? :)
You just need to echo your imagick object: $img = new Imagick($file); header('Content-Type: image/'.$img->getImageFormat()); echo $img;
stackexchange-stackoverflow
{ "answer_score": 32, "question_score": 19, "tags": "php, stdout, imagick" }
Как добавлять данные в имеющуюся таблицу mysql Hibernate создаёт новую таблицу, а мне нужно, чтобы добавлял в существующую, как реализовать? Вот код: @Entity @Table public class User { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Integer id; public String phone; public String message; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMessage() { return message; } public void setLastName(String message) { this.message = message; } }
1. Для того, чтобы добавить данные в имеющую таблицу, необходимо было поправить строку: > > @Table(name = "НАЗВАНИЕМ ТАБЛИЦЫ", schema = "НАЗВАНИЕ СХЕМЫ") > Таблица - это то, куда записывать данные. Схема - это то, где находится таблица. Пример: ![Пример]( TestApi - название схемы, а ApiTable - названием таблицы. 2. Добавляем в `application.properties` вот такую строчку: `spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl` и смотрим на то, какой версии наши зависимости,а точнее spring-boot, лучше всего иметь от 1.4.3 и выше. 3. В `application.propperties` добавляем строку `spring.jpa.hibernate.ddl-auto=update`
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, hibernate" }
date Manipulation in iphone sdk? i am using following code to compare two dates only(not time) and also with time, but it returns always future …any help please?how can i alter the following code to do it? NSComparisonResult result = [[NSDate date] compare:[NSDate date]]; switch (result) { case NSOrderedAscending: NSLog(@" in future"); break; case NSOrderedDescending: NSLog(@" in past"); break; case NSOrderedSame: NSLog(@" in same"); break; }
[NSDate date] will create new date object using current date and time. Since you are creating two objects of NSDate at different times (though only a difference of milliseconds), thats why it is returning in future always. I can think of two ways to fix this. Create date object only ones: NSDate *currentDate = [NSDate date]; NSComparisonResult result = [currentDate compare:currentDate]; Or You can use NSTimeInterval which returns time differnce in seconds: (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "iphone, ipad, ios4" }
Generate all unordered pairs of bit strings with Hamming distance at most 2 I'm looking for an efficient way to generate all unordered pairs of bit strings (represented as integers) that have Hamming distance at most 2. In this answer, it is shown how this is quite efficiently done for pairs having Hamming distance 1. In other words, the answer above gives us all edges of the hypercube graph. Phrased in these terms, I'm looking for an efficient way to generate the edges of the square of a hypercube. Is there some nice known fast method, perhaps similarly based on bit tricks?
There's an easy modification to Nate Kohl's answer. int n = 3; // examine all vertices from 0...2^n-1 unsigned long long max = 1ULL << n; for (unsigned long long vertex = 0; vertex < max; ++vertex) { std::cout << vertex << ':'; // print all vertices that differ from vertex by one bit unsigned long long mask = 1; for (int shift_amt = 0; shift_amt < n; ++shift_amt) { std::cout << ' ' << (vertex ^ (mask << shift_amt)); } for (int shift_amt1 = 0; shift_amt1 < n; ++shift_amt1) { for (int shift_amt2 = 0; shift_amt2 < shift_amt1; ++shift_amt2) { std::cout << ' ' << (vertex ^ (mask << shift_amt1) ^ (mask << shift_amt2)); } } std::cout << '\n'; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, algorithm, combinatorics, hamming distance" }
Surjective bounded linear map bound Let $X,Y$ be Banach spaces. Let $T: X \rightarrow Y$ be a surjective bounded linear map. Show that there is a constant $M>0$ such that for each $y\in Y $ there is a solution to $Tx=y$ with $\| x\| \leq M \| y\|$. Let $B_Y(0,r)= \\{ y \in Y : \| y \| < r\\}$. I have shown that there exists $r>0$ such that $B_Y(0,r) \subset T(B_X(0,1))$. Not sure how to conclude from here. Thank you in advance!
The open mappin theorem implies that there exits $r>0$ such that $B_Y(0,r)\subset T(B_X(0,1))$. Let $y\in Y, y\neq 0$, ${r\over {\|y\|}}y\in B_Y(0,r)$ implies that there exists $x'\in B_X(0,1)$ such that $T(x')={r\over{\|y\|}}y$. We have $T({{\|y\|}\over r}x')=y$ and $\|{{\|y\|}\over r}x'\|\leq {{\|y\|}\over r}$. Take $M={1\over r}$.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "functional analysis" }
Installing new OS using the Pi I don't have another computer to go in and mess around with the SD card. Is it possible to change operating systems from within the Pi itself?
Yes, if you have a second SD card, you can write that one from the running OS, then shut down the running OS and swap the newly-created card into the SD card slot. You will probably need a "USB SD adapter" device that can hold SD cards. Once you've got the SD adapter and card plugged into the Pi you can use the dd command to copy the .IMG file to the new SD card (dd if=inputfile.img of=/dev/sdx iflag=fullblock oflag=direct status=progress), where /dev/sdx is the name of the device that you found from journalctl.
stackexchange-raspberrypi
{ "answer_score": 3, "question_score": 0, "tags": "sd card" }
Set graphical signature location while creating a Signature Field with CoSign Signature API How to set graphical signature location, left or top, while creating a Signature Field with CoSign Signature API programmatically?
The default location of the graphical signature is on the left. If you want it to be on top, you need to set the `AR_PDF_SIGN_VERTICAL` flag (0x00000004) as part of the signature field’s _Flags_ attribute in the `SAPI_SIG_FIELD_SETTINGS` structure.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "digital signature, cosign api" }
paper-radio-group buttons inside a template possible? I'm creating a project with Polymer and have the following code: <paper-radio-group> <template repeat="{{answer in answers}}"> <p> <paper-radio-button name="{{answer.choice}}" label="{{answer.choice}}"></paper-radio-button> </p> </template> </paper-radio-group> I have a list of answers that I want to use in the paper-radio-group. Displaying this works fine. Every item in the answers array is displayed as a paper-radio-button. The problem is that they are not connected to each other. So, when selecting one paper-radio-button, another is not deselected. This is probably because the paper-radio-group tag is outside the template tag. But placing it inside would make it repeat like the paper-radio-button and that's not going to work either. Is there a way to get this to work? Or is it not possible?
The `<paper-radio-group>` expects `<paper-radio-button>` as it's children. When you wrap them in other elements like `<p>` the `<paper-radio-group>` can't manage the state. The `<template>` element is is not actually included in the DOM and doesn't get in the way when the elements are rendered.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "html, data binding, polymer, web component" }
How to get length of a dynamic array in Delphi? Is there a function to determine length of a dynamic array in Delphi ?
Use `Length` function to get the length of your array: var ArrayLength: Integer; begin ArrayLength := Length(ArrayOfSomething); ... end; From the reference for this function (emphasized by me): > In Delphi code, **Length returns** the number of characters actually used in the string or **the number of elements in the array**.
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 6, "tags": "delphi" }
UITableView and popover : dismiss popover and select row I have a little problem. I have a table view and when the user select a row, a popover is display with it contents. But if I want to select another row in the table view I need to tap once for dismiss the popover and another time for select the row. How can I do the same thing but only with one tap : dismiss and select the row ? Chears, iBen
~~Dismiss the popover in the`didSelectRowAtIndexPath:` method of the popover's table view.~~ When creating the popover or pushing the segue in the table view controller: popoverController.passthroughViews = @[self.tableView];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "objective c, uitableview, popover" }
Basis of a quotient vector space $\mathbb{R^2}/V$ > Be $\mathbb{R^2}$ be the usual $\mathbb{R}-space$ of dimension 2. Let $V = \langle \left( 1, 1 \right) \rangle$ be the sub-space of $V$ generated by the vector $\left( 1, 1 \right)$. Give a basis of the quotient vector space $\mathbb{R^2}/V$. * * * I need some assistance to determine if my answer is correct. Since $V$ is generated by $\left( 1, 1 \right)$, it implies that its span is simply a line $y = x$ passing through the origin. Therefore $\mathbb{R^2}/V := \left\\{ all \ lines \ y = x + \lambda : \lambda \in \mathbb{R }\right\\}$. Since all elements of the set are linearly independent, the only basis possible is $\left\\{ all \ lines \ y = x + \lambda : \lambda \in \mathbb{R }\right\\}$. Is the idea correct? If it is, is the notation alright? Thanks a lot.
Since $\dim\Bbb R^2=2$ and $\dim V=1$, $\dim(\Bbb R^2/V)=2-1=1$. So, take _any_ element $\alpha$ other than $0$ from $\Bbb R^2/V$, and $\\{\alpha\\}$ will be a basis of $\Bbb R^2/V$. For instance, take $\alpha=(1,0)+V$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "linear algebra, abstract algebra" }
Is there a way to convert a PDF file to ePUB format WITHOUT using Calibre I'll tell you clearly and loudly: I don't like Calibre! So, how can I convert PDF to ePUB without it?
We know you don't like Calibre... but have you tried its CLI conversion tool? The Calibre install provides the command `ebook-convert` that will handle what you want, and there's no need to run Calibre. ebook-convert file.pdf file.epub is all that's required. If the output looks a little wrong - try this ebook-convert file.pdf file.epub --enable-heuristics It will try a "smart" way to convert. Not perfect, but can work well in most conversions.
stackexchange-askubuntu
{ "answer_score": 108, "question_score": 75, "tags": "pdf, ebooks, epub" }
What is the best VB.NET control (standard/custom) for displaying list of files? I'm developing a Desktop Search Engine in VB.NET and I'm looking for a powerful, flexible and feature-rich control for displaying the search results i.e. list of files.
If you are using WinForms, the standard is to use TreeView for folders a ListView for files/results. If you aren't in a hurry, rolling your own using WPF might be interesting. It would be much more flexible, but also a lot more work.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "vb.net, user interface, file, custom controls, user controls" }
The number of positive integral values taken by $f(x)=(x^3-11^3)^{1/3}$ over natural numbers $x$ > For $f:{\Bbb{N}}\to \mathbb R$, $f(x)=(x^3-11^3)^{1/3}$, what is the number of positive integral values $f(x)$ can take? The first thing that came into my mind was just simply trial and error but I soon realised that it wasn't going to come handy here. I thought maybe factoring $$(x^3-11^3)= (x-11)(x^2 + 11x + 121)$$ might give some leads to this but I just couldn't figure something out from this. How do I approach this? I believe there might be some kind of specific theorem or rule that helps to solve these kind of problems that I don't know of, because I just can't figure out how to start in the first place.
The answer is $0$ by Fermat's Last Theorem. Indeed, $(x^3-11^3)^{1/3}=y \in \mathbb{N}$ would imply $y^3+11^3=x^3$, which has no solutions in the positive integers by FLT.
stackexchange-math
{ "answer_score": 5, "question_score": 2, "tags": "number theory, functions" }
getting eventlogs from Applications and Services log using python I am trying to read event logs from Applications and Services log using python. However the output are not as expected. (Actual 10 vs output 838) I am using the following code. Was wondering if there is a mistake with the parameters. import win32evtlog server = 'localhost' logtype = "Microsoft-Windows-Storage-Storport/Operational" hand = win32evtlog.OpenEventLog(server, logtype) flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ while True: events = win32evtlog.ReadEventLog(hand, flags,0) if events: for event in events: print ('Source Name:', event.SourceName) print ('Event ID:', event.EventID) print ('Time Generated:', event.TimeGenerated)
Found a method to get the information through the use of powershell using python. import subprocess getinfo = subprocess.check_output( ['powershell.exe', 'get-Winevent Microsoft-Windows-xxx/Operational']) where xxx is a variable
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, get eventlog" }
Is WebMehods a BPMN 2.0 supporting Process Engine? As the title says everything, If the answer is yes then I would like to have a nice tutorial/link for using WebMethods as a BPMN 2.0 process engine. Thank you in advance.
Yes with the 8.2 version : < > Process Engine now supports BPMN 2.0 semantics corresponding to the BPMN 2.0 constructs that webMethods Process Development supports in notation. If you want a good tuto, you could appreciate this one : <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jbpm, webmethods, business process management, bpmn, activiti" }
Convert array to an array object with some modifications i'm pretty beginner in the JavaScript and I really need help to convert an array to an array object. There are many examples here in stackOverflow, but I need some modidfication during this process, which is why I couldn't do anything For example I have: data = [{id: 21, name: "jack"} , {id: 185, name: "yas"}] and I need to convert it with something like that (id key change to student_id, and present = true, should be added), and the length of this array is dynamic and will change over time. [ { "student_id" : 21, "present" = true }, { "student_id" : 185, "present" = true } ] I need to add these array object to: const data: any = { here.... }; your help will be much appreciated.
Assuming your data actually looks more like this data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}] This is a simple matter of _mapping_ the array to a new format with the properties you want const data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}] const newData = data.map(({ id }) => ({ student_id: id, present: true })) console.log(newData)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, arrays, typescript" }
Firebase Email/Password Auth not registering users I am using Firebase for web and I am trying to register users with email and password, I have done everything they said on the docs but it is not working for some reason. This is my submit function: function submitForm(){ var email = document.getElementById("email").value; var password = document.getElementById("password").value; console.log(email, password); firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; alert("oof not valid info brochocho"); }); window.location = 'index.html'; alert("registered"); };
`window.location = 'index.html'; You are redirecting to another page before the sign up finished. You should have put this line in the then block of the promise returned by `createUserWithEmailAndPassword`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, firebase, firebase authentication" }
python - Sorting custom container objects In Python lists, there are two alternative ways of performing a list sort: 1. Using its `.sort` method, which sorts in place 2. Using the `sorted()` built-in function, which returns a new sorted list Now, if I create a custom container type (say by subclassing from `itertools`'s ABC), can I do the same? I can figure out how to make the custom container object sorts in place. But what I want is for the built-in `sort()` to return a new instance of that custom container object (instead of a list) when I use it. Is this possible? If so, how?
What about just subclassing the builtin `list`, and just redefining `sort` method ? >>> class MyList(list): def sort(self): copy = list(self) copy.sort() return MyList(copy) >>> l2 = MyList([2, 6, 9, 8]) >>> l2 [2, 6, 9, 8] >>> l3 = l2.sort() >>> l2 [2, 6, 9, 8] >>> l3 [2, 6, 8, 9] >>> EDIT: after the OP's comment, leaving `sort` method as is and adding a new one: >>> class MyList(list): def sort_copy(self): copy = list(self) copy.sort() return MyList(copy) The `sort` method inherited from parent remains as is (in place), the new `sort_copy` method creates a new one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, oop, list" }
How to re-add deleted columns from a dataframe in pandas python? How to re-add columns from original dataframe, which were once in the data frame but got removed using a list? df_original =['a','b','c','d','f'] df_new=df_original[['b','c','d']] user_re_add col=['a'] if user_re_add not in df_new.columns: add= df_new.append(user_re_add) print("Re-add the column from original df") Expecting the df_new = ['a','b','c','d','f']
Using your example: df_original = pd.DataFrame(columns=['a','b','c','d','f']) df_new=df_original[['b','c','d']] user_re_add = df_original[['a']] if [column for column in user_re_add.columns] not in [column for column in df_new.columns]: add = df_new.append(user_re_add) add = add[[column for column in df_original.columns if column in add.columns]] print("Re-add the column from original df") Restoring the column deleted that was saved in a variable and reordering as the original frame.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas, dataframe, data science, data manipulation" }
If $f(n) = \Theta(g(n))$, do both functions bound each other for all $n$ or only sufficiently large $n$? The following is an excerpt from CLRS: > $\Theta(g(n))= \\{ f(n) \mid \text{ $\exists c_1,c_2,n_0>0$ such that $0 \le c_1 g(n) \le f(n) \le c_2g(n)$ for all $n \ge n_0$}\\}$. Assuming $n \in \mathbb{N}$, I was unable to find $f(n)$ and $g(n)$ such that the bound does not apply for all $n$. **Note:** This question was asked with the flawed assumption that $f(n)$ and $g(n)$ necessarily have natural domains.
You need to have a non-negative sufficiently large input size $n$ from which point on the bound holds. Have a look the Figure 3.1 in CLRS, which shows graphically examples of the $O, \Theta$ and $\Omega$ notation. You can also see why this makes sense. For example, we are interested in knowing how an algorithm's runtime behaves as the input gets larger and larger. Thus, we don't really care too much about small values of $n$. It is not always the case that for every nonnegative $n$ a bound would hold. For example, consider two functions $f(n)=n$ and $g(n)=n \log n$. We can plot them for a few small values of $n$. $g(n)$ does not dominate $f(n)$ for all values of $n$. For sufficiently large values of $n$, it will. In other words, $f(n) = O(g(n))$. Note that this is only an upper bound, but the idea will be the same for $\Theta$.
stackexchange-cs
{ "answer_score": 0, "question_score": 3, "tags": "asymptotics, landau notation" }
Как правильно составить regexp (Python), чтобы запретить спец. символы (\W не подходит) Стоит задача: пользователь вводит имя задачи, которое потом будет использовано в качестве шаблона для имени класса Python **2.7** (в Scrapy). Поэтому необходимо запретить ввод спец. символов. Пользователь может использовать русские (кроме ь, ё, Ё, ъ) и англ буквы и цифры ( пробел запрещен, разрешено _ ). Главное требование - соблюдение правил Python для идентификатора класса: > identifier ::= (letter|"") (letter | digit | "")* > > letter ::= lowercase | uppercase > > lowercase ::= "a"..."z" > > uppercase ::= "A"..."Z" > > digit ::= "0"..."9" Пока есть такой вариант "[a-zA-Zа-яА-Я][^ ёьъЁ]+$" `\W` не выход - запрещает русские буквы т.е. такой вариант не подходит "[a-zA-Zа-яА-Я][^ \WёьъЁ]+$" Цифры в начале можно не фильтровать, т.к. к исходной строке, в начало и в конец, прибавляется по 1 символу через нижнее подчеркивание. Надеюсь на помощь, спасибо.
Чтобы запретить спец.символы, достаточно разрешить только выбранный набор символов: `(letter | digit | "_")*` плюс некоторые русские буквы: #!/usr/bin/env python2 # -*- coding: utf-8 -*- import re fullmatch = re.compile(ur'[a-zA-Z0-9_а-щыэ-яА-ЩЫЭ-Я]+$', re.UNICODE).match Пример: >>> bool(fullmatch(u"Первая_задача\n")) True >>> bool(fullmatch(u"ё")) False Это работает даже, если передать `ё` как U+0435 U+0308 комбинацию. При этом U+0435 отдельно (`е`) работает: >>> import unicodedata >>> bool(fullmatch(unicodedata.normalize('NFD', u"ё"))) False >>> bool(fullmatch(unicodedata.normalize('NFD', u"ё")[0])) True
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "python, регулярные выражения, запрос, символы, match" }