INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Loop from another WP site onto mine What i'm trying to achieve is bringing a loop from one WP site into another WP Site. I used this method to get the loop into an external php file (which all works fine, the results show) <?php define('WP_USE_THEMES', false); require('path_on_server/wp-blog-header.php'); query_posts('showposts=5'); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li> <a href="<?php the_permalink() ?>"><?php the_title(); ?>" /></a> </li> <?php endwhile; endif; ?> I then try and include the file in my sidebar using a simple php include call but the results don't show.... I imagine this is because of some sort of confliction between my WP & the other sites WP. Any help on achieving this? Thanks
If you want to grab info right off the page you should use one of these options if you don't want a plugin, the content can be returned and parsed as xml, rss, json or just html/text. This is the proper way to do this. WordPress HTTP API: < or `fetch_feed()` ( for rss only). ps. On side note I usually use simplexml instead of the built in rss wp stuff as it has way more functionality along with the HTTP API. Also an alternative, though more troublesome way is to connect to the other database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop" }
JavaFX chart variable scope final CategoryAxis yAxis = new CategoryAxis(); final NumberAxis zAxis = new NumberAxis(); if (cbTypeGraphView.equals("Bar Chart")) { BarChart<String, Number> chart = new BarChart<String, Number>(yAxis,xAxis); } if (cbTypeGraphView.equals("Line Chart")) { LineChart<String, Number> chart = new LineChart<String, Number>(yAxis,xAxis); } AnchorPane.setTopAnchor(chart, 110d); AnchorPane.setLeftAnchor(chart, 10d); AnchorPane.setRightAnchor(chart, 5d); AnchorPane.setBottomAnchor(chart, 50d); The `chart` variable looses scope outside the if statement I was wondering how this can be fixed so that the `chart` does not lose scope outside the if statement. I was thinking about using it's parent class `XYChart` class. I'm not sure how to add a `BarChart` or a `LineChart` to `XYChart`.
You can do final CategoryAxis yAxis = new CategoryAxis(); final NumberAxis zAxis = new NumberAxis(); XYChart<String, Number> chart = null ; if (cbTypeGraphView.equals("Bar Chart")) { chart = new BarChart<String, Number>(yAxis,xAxis); } if (cbTypeGraphView.equals("Line Chart")) { chart = new LineChart<String, Number>(yAxis,xAxis); } AnchorPane.setTopAnchor(chart, 110d); AnchorPane.setLeftAnchor(chart, 10d); AnchorPane.setRightAnchor(chart, 5d); AnchorPane.setBottomAnchor(chart, 50d); You should probably deal with the case where neither `if` statement executes, in order to avoid null pointer exceptions.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, javafx, charts, javafx 8" }
capture special string between 2 characters in python I have been working on a python project while I don't have that much experience so can you tell me please if I have this string : `Synset'dog.n.01'` and I want to extract the string dog only what should I do ? I mean just to extract any string between `Synset'` and `.n.01'`
I suggest to use `re` (regex) import re s = "Synset'dog.n.01'" result = re.search("Synset'(.*).n.01'", s) print result.group(1)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python 2.7" }
In U-Net, is there a non-linearity (relu) in up-convolution layer? I am doing semantic segmentatio using U-Net. I was wondering whether to include 'relu' activation or not in the up-convolution layer? x = Conv2DTranspose(filters, kernel_size) (x) OR x = Conv2DTranspose(filters, kernel_size, activation='relu') (x) ```
I'd not use activation function in these layers because that's how I saw it done first time, but it's probably worth trying since I can't come to a reason why we woudn't use activation function in this layer, it probably shoudn't change the results much. U-Net anyway has an architecture with convolutions between each upsampling, which use activation functions, so not using activation function in upsampling layers is not a big deal.
stackexchange-datascience
{ "answer_score": 1, "question_score": 0, "tags": "deep learning, tensorflow, cnn" }
Objectify - filter() with range and with a 100 records limit does return the same result always? Objectify filter() with range and with a 100 records limit does return the same result always, is there a way to get 100 random record on a given matching criteria??? **Example:** Lets say I have an index on score field (in GAE Entity Leaderboard), where I would like to fetch out records where score range is 0 to 10 with a limit of 100 records I do get the same results out all the time (considering there is no change in the data records). I understand this is purely to do with the index where the data could have been stored and ordered in ASC order and any time you query we might end up with the same result? Is there way with GAE objectify to fetch out the random 100 records matching the same criteria considering we have 1000s of records b/w 0-100 score range???
Depending on your specific needs, you may be able to use the `__scatter__` property built into GAE: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "google app engine, google cloud datastore, objectify" }
using subprocess in python across os platforms I am developing a software which includes a python script that runs bash commands using subprocess. Would I be able to run this particular script using windows in the future? I basically am using three languages: Bash, C and Python. I run all the scripts within python using bash commands. `cat run.sh` gcc [programName].c -o programName ./programName or potentially just do: `subprocess.call(["gcc",programName])`
I've been working on this a bit recently. If you want to have code that works both on Unix and Windows, I'd advise you to use e.g. `os.remove` or `os.rename` wherever possible instead of `rm` or `mv`, `glob.glob` instead of `ls`, and only use `subprocess` to run external commands (remember they'll have `.exe` extensions most of the time -- you might check `os.name` to decide whether to include it or not). You might also want to rewrite all your `grep`s, `awk`s or `sed`s as Python functions. The point is, even though technically you can install Bash on Windows and run your Python code from the console, it seemed to me the code from `subprocess` was always run in CMD or PowerShell anyway.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "python, bash, subprocess, cross platform" }
Symfony services container is imported but how? I have to make modifications on a Symfony project and I am currently wondering how this project works. It has a services.php file in Company/Bundle/Resources/config that manages the instantiation of services, but it is not imported anywhere... I looked in app/config/config.yml, config_dev.yml, config_prod.yml, security.yml, etc and there are no imports for this file! I know it used by the application, but I have no idea how it is imported :/.
Does it make use of the DependenctInjection service? Have a look at the docs here use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; $container = new ContainerBuilder(); $loader = new PhpFileLoader($container, new FileLocator(__DIR__)); $loader->load('services.php'); This will autoload the service when the symfony app is initialized.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, symfony" }
WooCommerce product category and product tag base product permalink not working my website link < please check image I have added the product permalink(Settings ->Permalinks) to image ![enter image description here]( ![enter image description here](
Permalinks works only woocommerce defalut pages, you have made custom templates for shop and category pages. that's why its not working correctly. Thanks
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, wordpress, woocommerce, product" }
command npm install is not working and showing errors When entered npm install the following errors appeared Errors displayed in terminal i want to set up my angular project but fail miserably !! enter image description here
First, Try with npm cache clean --force npm install -g @angular/cli@latest and after that do `npm install` If above not work then try with below solution Update the version of core-js to version above 3. npm install --save core-js@^3 and after that do `npm install`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "angular, npm install" }
Counterexample with mapping Let $f$ is mapping from metric space $X$ into metric space $Y$. Let $E$ some subset of $X$. Am I true if $f(x)\in f(E)$ then doesn't imply that $x\in E$? Let $f(x)=x^2$ and $X=Y=\mathbb{R}^1.$ Taking $E=[0,1]$ then $f(E)=[0,1]$ but $f(-\frac{1}{2})\in [0,1]$ and $-\frac{1}{2}\notin E$. Am I true?
Yes, that is correct. An even easier example is $f: \mathbb R\to \\{0\\}$ (which must be constant). Then $f([0,1]) = \\{0\\}$ and $f(-1/2) \in \\{0\\}$ but $-1/2\not\in[0,1]$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "real analysis, metric spaces" }
Pass to a case class constructor the instance being constructed I have a complex set of traits and case classes, but for the sake of the discussion let me summarize what I'm trying to model in this way: case class X(x: X) That's fine until I end up initializing one of the instances this way: val myX: X = X(myX) It compiles (unbelievably), but the `myX` passed to the constructor is actually _null_ , easily visible by checking `myX.x` afterwards. Suppose having an instance pointing to itself is fine for what I'm trying to model, is there an elegant way to solve this issue and have the new instance of `X` with a pointer to itself? I mean without mutating the object after its creation, nor introducing a 2nd constructor that takes no parameter and uses `this` inside. Remember please the real situation is more complex that what sketched here.
If you need to have a case class, I don't think it can be done. Case classes cannot have lazy parameters, and if they could point to themselves most of their methods would probably blow the stack. With a regular class you can do this: scala> class X(x0: =>X) { | lazy val x = x0 | } class X scala> val x: X = new X(x) val x: X = X@5f98cb6f scala> x.x val res0: X = X@5f98cb6f scala> x.x.x val res1: X = X@5f98cb6f If you want case class-like behavior you'll have to implement the boilerplate (apply, unapply, copy, equals, hashcode, ...) yourself, and be very careful not to trigger an infinite loop or a stack overflow.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "scala" }
Launching and terminating a helper app with a sandbox main app I have a main app with a bundled helper app within. The helper app is a necessity for the main app to function correctly. As of right now, I have the main app launch the helper app on launch, and have the main app send a notification telling the helper app to terminated through the `NSDistributedNotificationCenter` on the termination of the main app. This way works most of the time. However, if the main app is force closed, the helper app remains running (no notification is sent. I am using the `AppDelegate`'s `applicationWillTerminate` method to send the notification). Is there a way to make the running of the helper app more reliable? Also, is there a better way to make the communication between the two apps (ie not `NSDistributedNotificationCenter`; is there away to communicate through app bundles?)? Thanks!
You could always use a common approach of ' ** _pinging_** ' each other to indicate the app is still alive (also via notifications) like once a minute. No notification received after some timeout being the helper app's trigger to shut itself down. Not super-elegant but pragmatic and proven. Or check the list of processes for the other app still being alive, though the latter sounds more brittle to me.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "objective c, cocoa" }
How to create a full-screen form with max/min/close button in c#? I made full-screen by: FormBorderStyle = FormBorderStyle.None; but there is no max/min/close button? How to get it?
Set the WindowState property of your form to Maximized instead of removing the form border if you want a full screen form to retain the controls. private void Form1_Shown(object sender, EventArgs e) { this.WindowState = System.Windows.Forms.FormWindowState.Maximized; } If you actually want a full screen form with no border the best way to do this would likely be a custom user control to emulate the standard min/max/close functions.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, fullscreen, formborderstyle" }
How can I encrypt Kali Linux after the install? Okay so here is some useful background before we get started. I booted a Windows 7 install disk, split the hard drive into two partitions, installed windows. Rebooted, installed Kali, then booted into Windows and encrypted the Windows partition with PGP Desktop. When I power on I have to enter my PGP pass phrase then it loads grub and from there I can choose between Windows and Kali. While in Kali I can tell Windows is encrypted. During the Kali install I did not choose to encrypt, So my question is: How do I encrypt Kali without re-installing. A terminal command would be nice.
As Kali Linux is based upon Debian, instructions for encrypting an existing Debian install should be valid. These instructions are from the Setting up encryption after debian wheezy install question. I did some basic testing, and it seems to be a working solution (last tested on Kali 2016.2). > First install ecryptfs-utils (it may already be installed) > > > sudo apt-get install ecryptfs-utils > > > then boot to recovery mode and as root run > > > ecryptfs-migrate-home -u your_user_to_migrate > > > After the script runs, log out and log in as your user > > > exit > > > You might also with to run > > > ecryptfs-unwrap-passphrase > > > enter your use password when prompted and save the information in a safe place in the event you need to perform data recovery. > > Last you can delete the temp files / directories created by the migration script and reboot (technically you do not need to reboot).
stackexchange-superuser
{ "answer_score": 6, "question_score": 2, "tags": "encryption, windows, kali linux" }
Chose a random paperclip attachment I have "foo" controller that, among other things has 3 paperclip attached images. foo.image1, foo.image2 and foo.image3 What is the best way to render in a view one random attachment that gets refreshed every time the page is reloaded? \--EDIT--- Ok, this is not very elegant code but at least avoids using send and serves my purpose. @a = foo.image1(:thumb) @b = foo.image2(:thumb) @c = foo.image3(:thumb) @rand = ([@a, @b, @c].sample)
In your controller you can do something like: @image = foo.send([:image1, :image2, :image3].sample) What this is doing is randomly selecting (sampling) a symbol corresponding to the name of the images, and then sending that symbol to `foo` to execute. The result is stored in the instance variable, which can then be used in your view. As long as this is done every time someone hits your action (e.g if it's in a `show` action or something) then it will always randomly select a new image, even on refresh.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, ruby on rails 3" }
"Forward" a directions request from MKMapView I have a MKMapView with a few Annotations. I would like to add the option to "forward" the user to the native Maps (iOS6) app for directions to the selected annotation from within the callout "pop-up"... Is this possible? Maybe using a pseudo-link?
I suppose it is possible to implement according to this article: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "objective c, ios6, mkmapview, mkannotationview, ios6 maps" }
Quotient of Riemann surface by properly discontinuous group action I am looking for a reference on quotients of Riemann surfaces by properly discontinuous group actions. In particular, I would like a reference for the following result: Let $M$ be a Riemann surface and let $G$ be a subgroup of $\text{Aut}(M)$ whose action on $M$ is properly discontinuous. Then the quotient space $M/G$ has the structure of a Riemann surface, and the projection map $\pi\colon M\to M/G$ is holomorphic. Edit: My definition of "properly discontinuous" is that for any compact subset $K$ of $M$, the set $\\{g\in G:K\cap g(K)\neq\varnothing\\}$ is finite.
For the first part, you might want to take a look at Theorem 6.2.1. in Beardon's Geometry of Discrete Groups: Theorem 6.2.1. Let $D$ be a subdomain of $\hat{\mathbb{C}}$ and let $G$ be a group of Möbius transformations which leaves $D$ invariant and which acts discontinuously in $D$. Then $D/G$ is a Riemann surface. Beardon gives a detailed proof over several pages. Chapter III Section 3 of Miranda - Algebraic Curves and Riemann Surfaces might also be interesting as well as Theorem 5.9.1 in Jones & Singerman - Complex Functions. Here the second part is also shown. Non of these sources contain the exact statement you are looking for, but may contain ingredients for a proof.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "reference request, group actions, riemann surfaces, quotient spaces" }
Can you modify the number of slidesPerView in swiperjs after it was init? I am trying to modify the number of the slides per view in swiperjs after it was initiated. In the API I couldn't find any method that allow me to update that. Currently the swiper is created with 1 slide per view and I would like to change it to 3 per view after it was initiated. How can I achieve that?
Solved it by modify the params. let params = swiperModify.params; params.slidesPerView = 3; params.slidesPerColumn = 3; For some reason at first I was looking for a method to handle new params (set method).. but this works perfectly fine. If that not best practice I would like to know :)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, swiper.js" }
In SQL, How does using DISTINCT affect performance? I am attempting to select a distinct list where duplicates are created over several fields. For example, SELECT tablename.field1Date, tablename.field2Number, tablename.field3Text FROM tablename; Would select duplicating records over the date, number and text fields respectively. Now, when I select distinct records to provide what I am looking for, the performance seems to decrease dramatically. SELECT DISTINCT tablename.field1Date, tablename.field2Number, tablename.field3Text FROM tablename; Is there any known reasons for this? I must admit I am using MS Access 2003 which may be the issue.
Yes, basically it has to sort the results and then re-processed to eliminate the duplicates. This cull could also be being done during the sort, but we can only speculate as to how exactly the code works in the background. You could try and improve the performance by creating an index composed of all three (3) fields.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 7, "tags": "sql, ms access, performance" }
How can I stay hydrated? So far in _DayZ_ , I've found a rifle, some ammo, some firewood, and even a bike! The one thing I _haven't_ found, however, is water. Or any kind of drink for that matter. I'm slowly dying of dehydration, and I have no idea how to fix this. Well, alright, I know that I need to drink something, but I can't find anything to drink! **How can I stay hydrated? Can certain containers be used to hold water?**
To rehydrate, you'll need either water or soda. Soda is a one time use item and will completely refill your thirst meter, but it makes sound and can actually alert zombies. Water bottles (Canteens) on the other hand are refillable. The can be found either empty or full. A full water bottle will become empty after one use. To refill a water bottle, you'll need to find a lake/pond, well, or water pump. You cannot refill a water bottle in the ocean. **Alert:** It is possible to lose all your equipment while refilling your water bottle in a pond. This is a feature.
stackexchange-gaming
{ "answer_score": 8, "question_score": 8, "tags": "dayz 2012" }
How to convert between different pylab.histogram results what is the formula relating variables `values1` and `values2` in the following code: values1, _ = pylab.histogram(data, bins, density = False) values2, _ = pylab.histogram(data, bins, density = True) ? Or put in another way, given `values1` how can I get `values2` thus avoiding another call to `pylab.histogram` ? Thanks
The one-dimensional density is defined as the `values / length`. But it's also a normalization method for histograms. So in order to get from your original values to the `density`-values just divide by the total count (normalization) and the bin-width (density): bin_width = bins[1:] - bins[:-1] values2 = values1 / np.sum(values1) / bin_width A quick test with a random array: from matplotlib import pylab import numpy as np data = np.random.randint(0,10, 1000) bins = np.array([0,1,2,5,11]) values1, _ = pylab.histogram(data, bins, density = False) print(values1) # [ 97, 117, 278, 508] values2, _ = pylab.histogram(data, bins, density = True) print(values2) # [ 0.097, 0.117, 0.09266667, 0.08466667] bin_width = bins[1:] - bins[:-1] print(values1 / np.sum(values1) / bin_width) # [ 0.097, 0.117, 0.09266667, 0.08466667] So it is the same for this case.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, numpy, matplotlib" }
Mapping database table to class I'm writing an application with ASP.NET MVC2. In the tutorial I'm following for registration, the author mentions mapping a database table to my `User` class to make it easy to insert the user once they pass validation checks, but he doesn't explain how to do that. These are the attributes of my `User` class: public string Username { get; set; } public string Email { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } They have DataAnnotation validations as well. I also made a database table on a remote server (hosted at my University) called `Users` which has the following fields: Id Username Email Password How can I map them and then easily save the user to the database? Thanks.
You can use some well known ORM solutions out there. I would recommend Entity Framework. This code project example is good place to start
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, asp.net, orm, mapping" }
strut and strutbox The definition of a `\strut` in LaTeX is given in the source as: 211 \newbox\strutbox 212 \def\strut{\relax\ifmmode\copy\strutbox\else\unhcopy\strutbox\fi} Shoudn't a `\strutbox`, give an empty box? AS you can see from the example below, it prints the ligature `ae`, if I include `fixltx2e` and the ligature `ff` if I don't. `\strut` works as expected. \documentclass[11pt]{article} \usepackage{fixltx2e} \begin{document} \strutbox \texttt{\strutbox} \textit{\strutbox} \end{document}
You need to use `\copy\strutbox` to get the box. The definition `\newbox\strutbox` merely allocates a box number for the strutbox, then assigns that number to `\strutbox` using `\chardef`. Hence `\strutbox` in isolation typesets the character in the current font with the same number as the box number allocated to strutbox.
stackexchange-tex
{ "answer_score": 12, "question_score": 9, "tags": "strut" }
Creating a decision tree? So I'm trying to split on an attribute "Color" that has possible values (Blue,Green,Red,Orange,Pink). I'm splitting on entropy values, and the best split can either be Multi-Way 5, Multi-Way 4, Multi-Way 3, or Binary. For example: 5: (Blue, Green,Red,Orange,Pink) 4: (Blue, Green), (Red), (Orange), (Pink) (Green,Pink), (Blue),(Red),(Orange) 3: (Red,Orange), (Blue,Green), (Pink) (Red,Blue), (Green, Orange), (Pink) 2: (Blue,Green,Red), (Orange,Pink) (Pink), (Blue, Green, Red, Orange) And so on. But how can I make a comprehensive list of all the possible splits? Is there a specific algorithm I could use? Or how would I even know how many max possible combinations there are with this? Any help would be greatly appreciated, thanks!!!
The entropy of a given attribute is non increasing over refinement of partitions. This means that the best possible partition is singletons (one value per set). This is the method used for discrete attributes in known algorithms such as ID3 or C4.5. As a side note, the number of partitions is given by Bell's number.
stackexchange-cs
{ "answer_score": 2, "question_score": 0, "tags": "trees, enumeration, bdd" }
Do you need to pay any type of fees to send tokens? If i made a token and sent it to a few new eos users that has no eos. can they send these tokens back to me with out a fee? in ethereum i need to pay eth to send a token back. also what stops me from spammimg my tokens to every eos account?
To send the tokens back, the receiver account must have some EOS. This because he needs to stake some of them in order to be able to send a transaction (to call an action) to send the tokens back to you. There are no fees in EOS but you need to stake resources in order to send transactions. So if you want to spam all the accounts with your tokens you must have enough resources staked. The biggest is the number of the account you want to spam, the biggest must be the value of resources staked.
stackexchange-eosio
{ "answer_score": 1, "question_score": 1, "tags": "tokens" }
how can force user to logout after 30 minutes(for example) in codeigniter is there way that if user have any activity in 30 minutes, that user logout automatically. I use **Ion_auth** authentication in Codeigniter.
check the file `system/cms/config.php` and set the option `$config['sess_expiration']` to the value you'd like to have (in seconds, so 30 minutes would be 1800 seconds). Keep in mind that this won't immediately throw your user out of the session, but he will have to relog the next time he'll request something that utilises the session (e. g. a password protected page).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, codeigniter, authentication, pyrocms" }
How to set a UIView to be of certain size? Suppose i need to place a `UIView` of size `320 x 376` onto my Window? How can i control this from the Interface Builder? **ANSWERED:** Image below shows how to do it visually !enter image description here
Go into the size Inspector (In Xcode 4, it's Command-Option-5; the icon is a ruler). From there you can type in a size.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "uiview, interface builder" }
Is $f'(x)$ monotonically increasing if $f''(x) >0$? Given $f:(0,\infty) \rightarrow \mathbb{R}$ and $f''(x)>0\forall x \in (0,\infty)$. Is it correct to say that $f'(x)$ is a monotonically increasing function? Can I correctly assume that for any $a,b \in (0,\infty)$ $f'(a) > f('b)$ if $a > b$?
Mean value theorem says yes. For each $a>0$, $b>0$ there exists $c\in(a,b)$ with $f'(b)=f'(a)+f''(c)(b-a)$, since $f''(x)$ is positive for all $x>0$ we get that $f'(b)\ge f'(a)$ which gives us the required statement.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "calculus" }
video orientation detection in bash I need to detect whether videos are recorded in portrait or landscape mode, then transpose those into the correct orientation, in a scripted fashion. if [ "$v_orient" == "landscape" ] then ffmpeg -i file.mp4 -vf "transpose=1" file.ogv else ffmpeg -i file.mp4 file.ogv fi I've looked in ffmpeg online documentation and googled around, I've attempted exiftool exiftool -Rotation -Rotate file.mp4 However, this outputs Rotate: 90 for both landscape & portrait videos I have. * * * How can I detect the video orientation in bash?
`ffprobe` is part of the `ffmpeg` package and it will report on video metadata. ffprobe somevideo.mp4 `grep` can be used to select just the rotation information. On a rotated video, I see this output: $ ffprobe somevideo.mp4 2>&1 | grep rotate rotate : 90 On unrotated videos that I tried, the above command produced no output. This command depends on video file's metadata. If you have a source that does not produce a reliable `rotate` tag, you may need to look for other tags. Old cameras that do not have accelerometers (gravity sensors) cannot tell if they are held in portrait or landscape orientation and hence cannot produce any useful tag.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "bash, video, ffmpeg, orientation" }
Build querystring automatically to send form via ajax I need to send a complete form via ajax to prevent the refresh of the complete page. Since the form has a huge number of inputfields, i dont want to build the querystring manually. I found some scripts collecting all elements in the form and building the querystring automatically. But is there any easier way to build the query string automatically?
using serialize() method of your jquery form wrapper object ! see : <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "javascript, jquery, ajax, forms, post" }
Find key contain specific key value pair in Puppet Hash I am still a beginner in Puppet. So please bear with me. Let's assume i have this hash created in Puppet through some module account = { user@desktop1 => { owner => john, type => ssh-rsa, public => SomePublicKey }, user@desktop2 => { owner => mary, type => ssh-rsa, public => SomePublicKey }, user@desktop3 => { owner => john, type => ssh-rsa, public => SomePublicKey }, user@desktop4 => { owner => matt, type => ssh-rsa, public => SomePublicKey } } How can i find find the key for specific key and value pair inside the hash? which in this case just for example i want to find all the key owned by `john`. So the expected result would be something like: `[user@desktop1, user@desktop3]` Thanks in advance
The question asks about how to do this in Puppet, although, confusingly, the Hash is a Ruby Hash and the question also has a Ruby tag. Anyway, this is how you do it in Puppet: $account = { 'user@desktop1' => { 'owner' => 'john', 'type' => 'ssh-rsa', 'public' => 'SomePublicKey', }, 'user@desktop2' => { 'owner' => 'mary', 'type' => 'ssh-rsa', 'public' => 'SomePublicKey', }, 'user@desktop3' => { 'owner' => 'john', 'type' => 'ssh-rsa', 'public' => 'SomePublicKey', }, 'user@desktop4' => { 'owner' => 'matt', 'type' => 'ssh-rsa', 'public' => 'SomePublicKey', } } $users = $account.filter |$k, $v| { $v['owner'] == 'john' }.keys notice($users) Puppet applying that leads to: Notice: Scope(Class[main]): [user@desktop1, user@desktop3]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "puppet" }
Lower bound for binomial theorem for $\frac{n}{2}$ I have this case of binomial theorem: $$ \sum_{i=0}^n \binom{n}{i} r^i (n-r)^{n-i}. $$ Now, for some reason, we know that $r\le \frac{n}{2}$. Is this enough to conclude that $$ \sum_{i=0}^n \binom{n}{i} r^i (n-r)^{n-i} > \sum_{i=0}^r \binom{n}{i} r^r (n-r)^{n-r} ? $$
I assume you mean $0 < r \le n/2$. Then $r \le n-r$, so for $0 \le i \le r$ you have $$ r^{i-r} \ge (n-r)^{i-r}$$ and thus $$ r^i (n-r)^{n-i} \ge r^r (n-r)^{n-r}$$ Using this for $i=0$ to $r$, and putting additional positive terms on the left for $i=r+1$ to $n$, we do indeed have $$ \sum_{i=0}^n {n \choose i} r^i (n-r)^{n-i} > \sum_{i=0}^r {n \choose i} r^r (n-r)^{n-r} $$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "combinatorics, binomial theorem" }
Physical object is halfly inside another object when spawn. How to set point of spawn right? I have a problem with calculating position for the GameObject for spawn (instantiate). There are: 1) cube. 2) room with floor and walls. 3) user that's clicking mouse. Cube has rigidbody and collider so when I spawn it at the point of user's click the cube is halfly inside the floor or a wall and physics pushes it away. Point of click == Cube's center. So it spawn halfly inside another object. The question is how to calculate position for spawn in a right way? Example Image: ![enter image description here](
You can try using `Collider.bounds` like this: Collider col = cube.GetComponent<Collider>(); cube.position = mouseClickPos - col.bounds.extents; Haven't tested the code, but hope you got the idea. You can find more about `Bounds` here: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, unity3d, geometry" }
Azure SQL Server database with visual studio subscription I wanted to learn Azure SQL Server database and I created pay as you go account with Microsoft but I ended up with subscription to Visual studio premium edition with MSDN also My question is do I need to have visual studio premium subscription? in order to learn Azure SQL server data
No, it does not matter what kind of Visual Studio you have, you just need an azure subscription then you can create your own Azure SQL Server and DB. And probably you should use SQL Server Management Studio instead of Visual Studio for SQL Azure: < Here is a step by step guide how to create an SQL Azure DB: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "azure" }
Emitting object or value in vue.js component child to parent communication I would like to know which is better way to emit data to parent in vue component. From parent to child I pass `prop` object but from child to parent with `$emit`. Should I pass object or value? e.g.: `{ product }` or `product.id` and also I have to reuse some data in the `{ product }` like `product.price` on event listener. What should I use? Emit an object or just value then loop and condition in listener function?
Just use a two way sync here: @product.sync="product" In the child: this.$emit('update:product', product) Whenever you make a change to the property of the product.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "vue.js, vue component" }
Ruby on Rails: Is it possible to use Camel-cased database field and table names? The Ruby on Rails convention for database table and field names is snake_case and not CamelCase. However, I have an existing database being used by a PHP application. I would like to write a Rails application that interacts with this database. Is there an easy, "Rails way" to interact with a database using CamelCase database table and field names?
The short answer is yes but it's not always easier than migrating the old database to a new database. If you want both applications to be able to use the same database though then it is probably the quickest approach up front. You can override the table and foreign key fields by doing the following: set_table_name "camelCaseName" set_primary_key "cameCaseIdName" You can alias all the field names if necessary as well: alias "camelCaseFieldName", "field_name" All of the AR relationships can set the primary key field as well. has_many :comments, :foreign_key_id => "commentCamelCaseID" It's more work than normal but it is possible.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "ruby on rails" }
Domains of differential equations Consider the following inital value problem: $$ \frac{\operatorname d y}{\operatorname d t} = \frac 1 {(y + 2)^2},\; y(0) = 1 $$ where $y$ is a real-valued function of $t$. It can easily be solved by separation of variables to obtain $$ y(t) = (3 t + 27)^{1/3} - 2 $$ Now, I understand that $t = -9$ is outside of the domain of the differential equation, because $y(-9) = -2$, and the first derivative is not defined at $-2$. However, the answer sheet stated that the solution exists only for $t > -9$. My question is: why doesn't it exist for $t < -9$, too?
We consider a solution to a differential equation to stop existing when it hits a point where the differential equation is undefined: in this case, where the right side $1/(y+2)^2$ has a zero in the denominator. It may be that the solution has a formula that is still defined on the other side of such a point, and provides a solution of the differential equation there, but we don't consider these as parts of the same solution.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "ordinary differential equations" }
Set a variable in another package I'd like to set a variable with a chosen name in another package. How can I do this easily? Something like: $variable_name = 'x'; $package::$variable_name = '0'; # now $package::x should be == '0'
Given that `$variable_name` was validated, you could do: eval "\$package::$variable_name = '0'";
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "perl" }
Django Template error: “category_list takes 2 arguments” Django template not loading from DB I'm in the process of changing the templates to a new design. During this process, the category list stopped loading. > “category_list takes 2 arguments” In the html file, “category_list” is being loaded with: {% category_list request.path %} Can someone explain what it means by “takes 2 arguments” in this situation? Edit: Here is the custom template tag: def category_list(request_path): list_cache_key = 'active_category_link_list' active_categories = cache.get(list_cache_key) if not active_categories: active_categories = Category.active.all() cache.set(list_cache_key, active_categories, CACHE_TIMEOUT) return { 'active_categories': active_categories, 'request_path': request_path }
`category_list` must be a Django custom template tag that takes two arguments. In your current template syntax your first argument is `request.path`. Look in your code for the definition of function `category_list` and check what arguments it should receive and add the second argument.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django" }
How to get object from file that imported another file? Say I have a python file called `fileOne.py` that imports `fileTwo.py`. Is there a way for `fileTwo.py` to access the objects from `fileOne.py` dynamically? So `fileTwo.py` doesn't need to know the name of the file that will import it, and instead can do something like this: `FILE_THAT_IMPORTED_ME.myFunction()`. Basically I want to know if there is a way to access objects from the 'parent' file that is importing a script, from said script.
You can access the file which imported you by doing `import __main__` and `__main__` will contain the parent module. `a.py#` import b print(b) `b.py#` import __main__ print(__main__) Executing `a.py` will result in <module '__main__' from '/home/jonatan/PycharmProjects/tests/test/a.py'> <module 'b' from '/home/jonatan/PycharmProjects/tests/test/b.py'> **Note** that `__main__` is being printed before `b` since the module b has to complete its loading before continue the file `a`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, python 3.x, import, python import" }
How to mount a partition on the root directory (for example /data) I am installing Ubuntu on my empty hard drive and I would like to have a separate partition on which I would store my data, like movies, music, documents, etc. I don't like the idea of putting those files in `/home/user` directory because I would have multiple users on my computer and I want them all to easily access those files. I might also have multiple operating systems on my computer. Now, the idea is, I would like that partition to be mounted on something like `/data` , instead of `/media/data`. Is that safe, and how can I do that?
I don't know what should prevent you from mounting that partition just under root. The command would be `sudo mount /dev/sda1 /data`, where `/dev/sda1` is the partition. Unmount via `sudo umount /data`. To mount on startup add the following line to `/etc/fstab`: /dev/sda1 /data <partition type> defaults 0 0
stackexchange-superuser
{ "answer_score": 6, "question_score": 2, "tags": "linux, ubuntu, partitioning, mount" }
Problem with onClick in React. On desktops works very well, on mobile doesnt work just like up, i have problem with onClick it doesnt work on mobile. {buttonSkills.map((item, i) => <Button key={i} variant={item.variant} onClick={() => filterIcons(`${item.className}`)}>{item.name}</Button> )} you may see this _< click F12 and see that on mobile buttons ("Wszystko", "Front-End" etc..) in section skills at the very bottom doesnt work here is full code of my skills section: _< Anybody know why my onClick doesnt work on mobile?
You have a container with the following css over the entire page, which gets all the click events: .header-main-container { z-index: 9999 } If you'll remove it you clicking would work.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, reactjs, events, mobile, onclick" }
dig @server doesn't work I have Ubuntu 12.04 with BIND9, working just as a caching server (forwarding to 8.8.8.8). When I use, for example, `dig +norecurse @l.root-servers.net www.uniroma1.it`, I obtain the following output: ; <<>> DiG 9.8.1-P1 <<>> +norecurse @l.root-servers.net www.uniroma1.it ; (1 server found) ;; global options: +cmd ;; connection timed out; no servers could be reached Using Wireshark I discovered that the outgoing queries are correct, but there aren't any incoming answers. Why? P.S. Using simply `dig www.uniroma1.it` I obtain the correct answers.
This is an issue with how the root name servers respond(or fail, in this case) to queries than with the dig tool itself. The following queries to a secondary DNS server in Italy will respond appropriately: * `dig +norecurse @dns.nic.it www.uniroma1.it` as will a query to one of Google's DNS servers using this: * `dig +norecurse @8.8.8.8 www.uniroma1.it` Off the top of my head, I don't recall how the Primary DNS servers are set up in regards to individual queries. It may be a security, or DDOS avoidance measure, but I would just be guessing at this point. Hope this helps. **Update** : See the second comment in response to this question which gives a much better explanation of interpreting a response from the top level name servers using the dig tool.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "dns, bind" }
how to pass string type list in F# function This code is giving error FS0001: This expression was expected to have type 'string' but here has type ''a * 'b' open System open System.Linq let list1 = [ "one"; "two"; "three" ] let list2 = [ "one"; "two"; "three" ] let tablesValidation (l1 : string list) (l2 : string list) = printfn "%O" l1 printfn "%O" l2 tablesValidation(list1,list2) Console.ReadKey() |> ignore
In F#, function arguments do not need parentheses and are separated by spaces. Change it to this: tablesValidation list1 list2 Your original version passed a tuple value as a single parameter, hence the error message, where `a * b` means a tuple with two fields.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "f#" }
Help adding new property to object literal Why is this returning: tracker.paramsToTrack is undefined var tracker = {}; var paramsToTrack = ['a', 'b', 'c', 'd', 'e']; for (p in paramsToTrack) { if(params[paramsToTrack[p]]) { tracker.paramsToTrack[p] = params[paramsToTrack[p]]; } } console.log(tracker); I'm basically checking params if 'a' through 'e' are present. If so, add them to the tracker object like so: tracker.a = stuff tracker.b = stuff Thoughts on what I'm doing wrong here?
tracker.paramsToTrack[p] Should probably be tracker[paramsToTrack[p]] Also, and not that you asked, you may want to eliminate the redundant array lookups: var tracker = {}; var paramsToTrack = ['a', 'b', 'c', 'd', 'e']; var paramName; for (p in paramsToTrack) { paramName = paramsToTrack[p]; if(params[paramName]) { tracker[paramName] = params[paramName]; } } console.log(tracker); Or better yet, if you are working in a modern Javascript environment: paramsToTrack.forEach(function (paramName) { if(params[paramName]) { tracker[paramName] = params[paramName]; } });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, json, object literal" }
My background image doesnt display right on my android phone Ive been searching for an answer for this but could not find it. My website is using an background image in the html like this html { background: url(img/bg.jpg) center top fixed no-repeat; background-size:center 100%; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; overflow-y: hidden; It works great in all the browsers ive checked except for the android webbrowser, nor the google chrome browser on the phone. Then It displays either 4 images or just one image at the top. Anyone met this problem before and found a solution?
Just add `height: 100vh` to you body
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css" }
how can I recover my directory permissions in XP? recently a folder containing my web documents was switched to "read only", and now I can't save or edit any files there. even when I log on as administrator I can't change it back to writeable. when I uncheck the "read only" box it says "access is denied" for every file in that folder. is there a tool I can use to force windows to give my folder back?
I would check to make sure you are still the owner of the file. See this guide: <
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "windows xp, permissions" }
What does the status code of the perl interpreter mean? I'm trying to execute a copy of the Perl interpreter using Java's Runtime.exec(). However, it returned error code `9`. After running the file a few times, the `perl` interpreter mysteriously started to return code 253 with no changes in my command at all. What does code `253` / code `9` mean? A Google search for `perl` interpreter's exit codes turned up nothing. Where can I find a list of exit codes for the Perl interpreter?
See perldoc perlrun: > If the program is syntactically correct, it is executed. If the program runs off the end without hitting an `exit()` or `die()` operator, an implicit `exit(0)` is provided to indicate successful completion. Thus, the program you are running must be somehow specifying those exit values via die, exit or equivalent.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "java, perl, exec, exit code" }
Oracle SqlDeveloper Completion Insight table name with # Got following error: if table name contains # (like z#users) code completion does not work. With normal table names all works fine. Is there any workarounds? Renaming all tables is not possible. Sqldeveloper version 4.0.0 Oracle 10.2.0.5
I just tried this with a table called ABC#DEF - with both table and column completion in the worksheet, and it worked with no issues. I'm on 4.0.2 and 11.2.0.4, so an upgrade to our latest SQL Developer patch might help.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "oracle, oracle sqldeveloper, code completion" }
iOS searching for a string inside of a string, or how to work with Yahoo weather I am trying to make a weather app. So far I managed to get some basic information from the rss. I am using the following code: if ([currentElement isEqualToString:@"description"]) { [currentLink appendString:string];} The thing is that I don't know how to look up for child informations. For example the wind variable has 3 sub variables: chill, speed, direction I get the following xml <yweather:wind chill="50" direction="0" speed="0" /> I am wondering how do I request this variable. Or how can I look up if there is yweather:wind inside the tag
what I understand about your problem is "you are unable to handle the attribute of any element" if you use TBXML parser it will help you to solve your problem. following is the link and example of your problem. To extract attribute: < To learn TBXML <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "iphone, ios" }
Integrating a trigonometric polynomial by changing variable Let the integral be: $$\int{\sin^4(x)\cos^3(x) dx} $$ I have to integrate this function by changing the variable. I'm trying: $u=\sin(x) $ and so $du = \cos(x)dx$. By rewriting the integral I get: $$ \int{u^4 \cos^2(x)du} $$ But I'm stuck here because I'm not sure there should be any expression with x left in the integral. Also I know the final answer is : $$ \int{\sin^4(x)\cos^3(x)dx} = -\frac{\sin^7(x)}{7} +\frac{\sin^5(x)}{5} $$
**Hint:** Use the identity $$\cos^{2}(x)=1-\sin^2(x)$$ and don't forget the constant of integration!
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "integration, trigonometry, trigonometric integrals, change of variable" }
C#: How to set the value of an mshtml.HTMLInputFileElement I am currently working on a project that needs to be able to set the value of an input element of type "file" in an HTML document using mshtml.HTMLInputFileElement. I am having a great deal of difficulty doing this. First I tried this: IHTMLInputFileElement element = (IHTMLInputFileElement)args[0]; string filename element.value = newFileName; But the value was not set. I then read on another forum that the value property could not be set directly, but could be set by giving the focus to that input element and then using SendKeys to send the value to the file element like so: HTMLInputElement writableFileElement = (HTMLInputElement)element; writableFileElement.focus(); SendKeys.SendWait(newFileName); this also failed and threw a COM exception saying that the field was not writable. Is there any way to set the value field of an HTMLInputFileElement?
No, search "browser file input stealing" in your favorite search engine for reasons. The SendKeys hack was patched in IE8 and Firefox 2 I think.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, internet explorer, forms, mshtml" }
Advice installing PSPP on Ubuntu 20.04 PSPP is an open source alternative to SPSS. Because of licensing issues it isn't in official Ubuntu repositories. I have found downloads available for Ubuntu 20.10 and 18.04 at < but I run 20.04 and don't want to upgrade. Am I out of luck or is there a safe choice for me? (I can follow directions but am not really adept at Linux yet - just switched over.) Thx.
You can install PSPP by using its package and dependencies from 20.10. cd ~/Downloads wget -c wget -c wget -c wget -c sudo apt-get install ./libgsl25_2.6+dfsg-2_amd64.deb ./libgslcblas0_2.6+dfsg-2_amd64.deb ./libspread-sheet-widget_0.6-3_amd64.deb ./pspp_1.4.0-3_amd64.deb And then launch it from menu or with `psppire` command.
stackexchange-askubuntu
{ "answer_score": 8, "question_score": 3, "tags": "software installation, 20.04" }
Group by and display grouped by row info, and rows with its ID in other table below it Let's say I have 2 tables In the first table, I have the following fields: STRUCTURE for `FRUITS` `id` - int `name` - varchar ROWS in `FRUITS` 1 | apples 2 | grapes in the second table, I have: STRUCTURE for `COLORS` `id` - int `id_fruit` - int `name` - varchar ROWS in `COLORS` 1 | 1 | red 2 | 1 | green 3 | 1 | yellow 4 | 2 | purple 5 | 2 | green in a single query, I want it to output the results like this: APPLES (#1) - red (#1) - green (#2) - yellow (#3) GRAPES (#2) - purple (#4) - green (#5) basically I'm just having trouble with it grouping by rows in 1 table, and then outputting all rows from another table with the ID of the grouped by row.
Something like this might do: SELECT `name` FROM ( SELECT `id_fruit`, `id` AS `id_color`, CONCAT('- ', `name`) AS `name` FROM `COLORS` UNION ALL SELECT `id`, 0, `name` FROM `FRUITS` ) s ORDER BY `id_fruit`, `id_color` Both fruit names and colour names are combined together. Colour names receive their ``id``s as their ``id_color`` values, and fruit names are assigned a fictitious ``id_color`` value of `0`. That way, when sorted by ``id_fruit`, `id_color``, fruits always appear before their respective colours. Additionally, a 'bullet' (`'- '`) is attached before colour names.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, sql, join, group by" }
How to plot individual points in Matlab at certain locations? I have the following graph : !enter image description here Each line changes according to 3 values : `1 2 3` .. However plotting anything less than 5000 will not show on the graph (axis min size is 5000), so I can't plot them directly. How can I show that these lines are changing according to either of these 3 values ?? Any way to implement this ?
You can add an offset value to the data you can not display properly so that you caan observe the relationship between the lines
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "matlab, plot, appearance" }
Как удалить пробелы и переносы строк самом тексте массива Помогите решить проблему, есть массивы такого типа: Array ( [0] => 1. Иванов Иван Иванович [1] => 2. Иванова Иванна Ивановна ) Задачи: 1. удалить пробелы и переносы строк от точки до первой буквы с пробелом между ними 2. удалить все и оставить только ФИО в массиве Как удалять пробелы до и после текста я разобрался, а вот с остальным - беда :) $data = array_map('trim', $data['Manager']);
$data = array_map(function($v) { return preg_replace('/\s\s+/', ' ', $v); }, $data); при желании можно объединить: $data = array_map(function($v) { return preg_replace('/\s\s+/', ' ', trim($v)); }, $data['Manager']);
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php" }
Using sdemon command of ArcSDE? I am pretty new to ArcGIS for Server and ArcSDE but cannot find a solution in the Esri Documentation or Forums. I don not know how to use **sdemon** or even where to start this command line tool.
Robert, if you are on 10.1, you need to install the ArcSDE Command Line Tools separately by running the application server install program. The installation would be DBMS specific. Here is the reference for the sdemon command in SQL Server, for instance. Otherwise, the full CMD commands reference is installed with this installation on your local machine, so you can always access it from the Start menu (assuming you are on Windows). The 10.0 version (no big difference with 10.1) is available here.
stackexchange-gis
{ "answer_score": 3, "question_score": 1, "tags": "arcgis server, enterprise geodatabase" }
How to get a single value from FormGroup I am aware that I can get the values of a form using JSON.stringify(this.formName.value) However, I want to get a single value from the form. How do I go about doing that?
You can get value like this this.form.controls['your form control name'].value
stackexchange-stackoverflow
{ "answer_score": 219, "question_score": 140, "tags": "angular, typescript, angular reactive forms" }
add number between string then render it in react.js I have tried this with console.log and it works, but I am stuck on how to turn it into a div let N = 13; let nums = Array.apply(1, { length: N }).map(Number.call, Number) console.log(nums) for (let el of nums) { if (el <= 9) { time = `0`+el+`:00`; console.log(time); } else if (el >= 9) { time = el+`:00` console.log(time); } } I want to put it in jsx class SchedulePage extends React.Component { render(){ return ( <div className="schedule-page-container"> {right here} </div> ); } }
Maybe like this? Render one `div` for each number in your nums array: class SchedulePage extends React.Component { render(){ let N = 13; let nums = Array.apply(1, { length: N }).map(Number.call, Number); return ( <div className="schedule-page-container"> {nums.map(el => { const time = el <= 9 ? `0${el}:00` : `${el}:00`; return <div key={time}>{time}</div>; }) } </div> ); } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, reactjs" }
Linspace using matrix input matlab My question seems wierd, because I know that we can't use a matrix as input in `linspace(x1,x2,n)` function. But my question is more something like : I have a vector `A=linspace(0,Amax,N)`, and I want to build a serie of vector B_k or big matrix `B_k=linspace(0,A(k),N)` but without making a `for` loop that slows down my whole calculation. % already defined A rGC=linspace(0,75e-7,N); for k=1:N r=rGC(k); v=linspace(0,A*r,N); y=f(r,v); INT=trapz(v,y); % The same for 8 more integrals end
Maybe something using interp1, to interpolate something like: [0 0 0 ... 0 ] [A(1) A(2) A(3) ... A(N)] with N rows .... For instance: N = 5; Amax = 15; A = linspace(0, Amax, N); x = [0 1]; y = zeros(2, N); y(2, :) = A; B = interp1(x, y, linspace(0, 1, N)) Which will give: B = 0 0 0 0 0 0 0.9375 1.8750 2.8125 3.7500 0 1.8750 3.7500 5.6250 7.5000 0 2.8125 5.6250 8.4375 11.2500 0 3.7500 7.5000 11.2500 15.0000 Not sure it will be any faster than a `for` loop or that even get the point here :)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "matlab" }
Is ivy (genus Hedera) a shrub or an herb? It seems like the difference between a bush (shurb) and an herb is that a bush has a woody stem. What does that make ivy (genus Hedera)? I know that ivy can get a pretty hard stem, does that count as woody? Is there something between a bush and an herb?
Woody plants are usually either trees, shrubs, or lianas. Ivies are lianas, they can have 40 years of woody growth rings and bark. The categories are flexible. It's an arbitrary division for convenience, it isn't that clear cut. Bamboos for example, are a woody grass. < Does that count as a woody plant? yes it's a woody liana.
stackexchange-biology
{ "answer_score": 2, "question_score": 1, "tags": "botany, classification" }
Sonar Web Plugin Can anyone point me in a direction to add custom profile rules for the sonarqube web plugin? I've seen the xpath rules in javascript, but the web plugin does not contain anything like that. Specifically, I'm trying to write some rules to check for WCAG2.0A compliance. The first rule I know I'm missing is checking for duplicate ids on the page. If the web plugin doesn't support custom rules, can anyone provide a resource on how to build the plugin from source?
This is not currently possible to add custom rules to the Web plugin. Feel free to discuss the new rules that you would like to be added on the user mailing-list: user [at] sonar.codehaus.org. To build it: mvn install
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, sonarqube" }
Asymptotic of $\sum_{n = 1}^{N}\frac{1}{n}$ versus $\sum_{1 \leq n \leq x}\frac{1}{n}$ Consider the series $\sum_{n = 1}^{N}\frac{1}{n}$. It is well known that we have the asymptotic: $$\sum_{n = 1}^{N}\frac{1}{n} = \log N + \gamma + \frac{1}{2N} + \frac{1}{12N^{2}} + O(N^{-3}).$$ My question: Consider the similar sum $F(x) = \sum_{1 \leq n \leq x}\frac{1}{n}$. Note that $F(N) = \sum_{n = 1}^{N}\frac{1}{n}$. Then does $F$ has the same asymptotic above? That is, is $$F\sum_{1 \leq n \leq x}\frac{1}{n} = \log x + \gamma + \frac{1}{2x} + \frac{1}{12x^{2}} + O(x^{-3})?$$ I think this should be true, but the only thing I can come up with is to look at $F(\lfloor x \rfloor)$ and use the asymptotic for $\sum_{n = 1}^{\lfloor x \rfloor}\frac{1}{n}$ but I am unsure how to compare $\log x$ and $\log \lfloor x \rfloor$ in a way that the error that occurs is $O(x^{-3})$.
Let $g(x)$ denote any $C^2$ function such that $$g(x)=\log x + \gamma+\frac{1}{2x}+\frac{1}{12x^2}+O(x^{-3})$$ Then $g'(x)= \frac{1}{x}-\frac{1}{2x^2}+O(x^{-3})$ and $g''(x)=-\frac{1}{x^2}+O(x^{-3})$, so the Taylor Series gives: $$g(x)=g(\lfloor x\rfloor)+\\{x\\}\left(\frac{1}{x}-\frac{1}{2x^2}\right)-\frac{1}{2}\left(\frac{\\{x\\}}{x}\right)^2+O(x^{-3})$$ Therefore by a density argument, we have the following growth of $F(\lfloor x\rfloor)$: $$ F(\lfloor x\rfloor)=\log x + \gamma + \left(\frac{1}{2}-\\{x\\}\right)\frac{1}{x} +\left(\frac{1}{12}-\frac{\\{x\\}+\\{x\\}^2}{2}\right)\frac{1}{x^2}+O(x^{-3})$$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "sequences and series, summation, harmonic numbers" }
слияние html и js У меня есть сайт хтмл и я хочу добавить форму связи с javascript, чтобы после ввода юзера он видел свое имя и фамилию после сабмита. Как это: <label>Благодарим за отправку (имя и фамилия) мы с вами свяжемся!</label> Мой вопрос. Как вставить эти данные в код html? Помогите если несложно)
Например так $('[name="button"]').on('click', function() { $('#rezult').html('<label>Благодарим за отправку '+$('[name="fname"]').val()+' '+$('[name="fname"]').val()+' мы с вами свяжемся!</label>') }); <script src=" <div> <input type="text" name="fname" value="Иван"> </div> <div> <input type="text" name="lname" value="Иванов"> </div> <button type="button" name="button">Отправить</button> <div id="rezult"></div>
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html" }
how to customize UITableViewCell i want to customize table cell to show data like this (chk image) !enter image description here
For those rows which you want set color like above the simply set this color (shown in above pic) fo cell' background color. or find this color use digital meter and use that rgb. like this [UIColor colorWithRed:200.0/255 green:200.0/255 blue:200.0/255 alpha:1.0]; replace 200.0 with your rgb values waht you need, you need to store data in common array for simply showing single detail you need to save that in form of string others in dictionary format. And at time of showing data. check wheter object is string or dictionary, and show accordingly. for checking type of object use this if([[myArray objectAtIndex:index] isKindOfClass:[NSString class]])
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "iphone, objective c, uitableview" }
plink command to print free|grep "Mem:" I like to print only one "Mem:" line in the output using plink command. plink -batch [email protected] -P 22 -pw test@123 (free;) --> **working** total used free shared buffers cached Mem: 8182004 7137528 1044476 0 284648 4852520 -/+ buffers/cache: 2000360 6181644 Swap: 16386260 188 16386072 plink -batch [email protected] -P 22 -pw test@123 (free|grep "Mem:";) --> **not working** above command not printing the output & terminated without any error. What's wrong in the syntax?
There is no reason to run the `grep` remotely. plink -batch [email protected] -P 22 -pw test@123 free | grep "Mem:" Note that you should not give the command to `plink` inside a subshell, `( ... )`. I don't know anything about Windows' `cmd.exe`, but you could also try plink -batch [email protected] -P 22 -pw test@123 sh -c "free | grep 'Mem:'"
stackexchange-unix
{ "answer_score": 3, "question_score": 0, "tags": "command line, free" }
Why the volume of a region is not a diffeomorphism invariant? (LQG) In loop quantum gravity, the volume operator for a given region is not a diffeomorphism invariant. But classically we know that volume is a scalar quantity under a diffeomorphism even if we take the full manifold or any region.
Why would you think that volume is not diffeo-invariant? If the region moves along with the diffemorphisms (aka passive diffeomorphisms), the volume is invariant. In LQG, the volume is also invariant (if you disagree, please explain why). If the region doesn't move with diffeomorphisms (aka active diffeomorphisms), the volume changes. That is because the region here is only a region in the coordinate space, which doesn't have a well-defined notion of volume. The same is also true in LQG. LQG is really not different from General Relavitity when it comes to diffeomorphism invariance.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "general relativity, volume, loop quantum gravity, diffeomorphism invariance" }
PHP DOM traverse HTML nodes for hyperlink tag I posted a SO question: PHP DOM traverse HTML nodes and childnode Someone kindly gave me a solution for this. However, the data that I'm parsing actually has several hyperlink tags as shown below: <tr> <td>DATA 1</td> <td><a href="12345" target="_top">DATA 2</a></td> <td><a href="other_link">DATA 3</a></td> </tr> My desired output is to only select the `href` (e.g. '12345') for the hyperlink tag that has a target of `"_top"`. My current code selects all the hyperlink tags in the table. foreach ($dom->getElementsByTagName('td') as $node) { foreach ($node->getElementsByTagName('a') as $node){ $array_href[]= $node->getAttribute('href'); } $array_data[] = $node->nodeValue; }
`target` is just another attribute, like `href`. Get the value and compare: foreach ($node->getElementsByTagName('a') as $node){ if ($node->getAttribute('target') === '_top') { $array_href[]= $node->getAttribute('href'); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, parsing, dom, html parsing, domdocument" }
How to create SharePoint Sub-Folders programmatically? I want to refer to this question which shows how to create first-level folders: SharePoint Question But I also need to know how to create Sub-Folders e.g. a Sub-Folder inside a List. Does anyone know how to create Folders inside a List?
Try to use this foreach (SPListItem item in list.Folders) { if (item.Title == "yourfoldername") { SPListItem newItem = list.AddItem(item.Folder.ServerRelativeUrl, SPFileSystemObjectType.Folder); newItem["Title"] = "SubFolder"; newItem.Update(); } } Check the full code at Programmatically create a subfolder in SharePoint list also you can add subfolder at specific folder by useing `SPFolderCollection` as the following SPFolderCollection Col = oList.RootFolder.SubFolders; SPFolder Folder = Col[foldername]; SPListItem newFolder = oList.AddItem(Folder.Url, SPFileSystemObjectType.Folder, newFolderName);
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 0, "tags": "2013, development, custom timer job, subfolders" }
Unable to get heroku $port in dockerfile In docker hub, there is a container which when launched opens a port of 9000 by default. The port can be overridden by passing an enviorment variable _server__port_. I am trying to pass Heroku $PORT value in the dockerfile as shown below: ENV server__port=$PORT EXPOSE $PORT CMD start.sh When the start.sh executes, I can see a log where server__port is shown as blank. If I put a random value of '8889' in the server__port environment variable then in the logs I can see 8889 value assigned to server__port. I tried to use ARG as shown below, and unfortunately got blank value in server__port variable. ARG PORT ENV server__port=$PORT EXPOSE $PORT CMD start.sh How do I get Heroku port value and set in the dockerfile?
Figured it out, I had to export the variable as shown below. The variable would define the port that would be used by the application. The command is CMD export CONF_listener__port=$PORT && sh ./start.sh && sh ./startServer.sh -Dclearreports.config="$DEFAULT_CONFIG" -Dsetupautoexecution=true
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "docker, heroku, containers, dockerfile" }
Remainder of Taylor expansion My lecture note says for $f\in C^2 _c $ the $|f(z+h)-(f(z)+f'(z)h+\frac{1}{2}f''(z)h^2)|\le \omega(h)h^2$ where $\omega$ is the modulus of continuity of $f''$. I have been thinking this for an hour and I cannot get the answer without assuming third derivative. Could anyone help to show why this is true? Thanks!
The mean value form of the Taylor series is $$f(z+h) = f(z) + f'(z) h + \frac{1}{2} f''(\xi) h^2,$$ for some $\xi$ between $z$ and $z+h$. Then use $|f''(\xi) - f''(z)| \le \omega(|\xi-z|) \le \omega(h)$. * * * More detail: substituting the mean value form for $f(z+h)$ gives \begin{align} &\left|f(z+h) - f(z) - f'(z) h - \frac{1}{2} f''(z) h^2\right|\\\ &\le \frac{1}{2} |f''(\xi) - f''(z)| h^2\\\ &\le \frac{1}{2} \omega(h) h^2. \end{align}
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "calculus, taylor expansion" }
How to make a relative clause point at the required referent? > Direct sequencing detected a heterozygous rs123456 mutation of the ABC gene in the mother of patient P20, who suffers from impaired carbohydrate metabolism. The clause "who suffers from impaired carbohydrate metabolism" may point at "patient P20". Can anything be done to make it unambiguously point at "mother"? Can one write: > Direct sequencing detected a heterozygous rs123456 mutation of the ABC gene in patient P20's mother, who suffers from impaired carbohydrate metabolism. Or would "patient P20's mother" look strange?
As has been established by the able first commenter, yes, you can use _'s_ to express the relationship between P20 and P20's mother, and it does not seem strange. You may have been led to reluctance or doubt because: Perhaps the _something of something_ form is used in another language you know. English learners often commit more frank errors for this reason, like _the pencil of my classmate._ It is sometimes taught that _something of something_ must be used to express family relationships, creation, and place > The sister of the tall boy. > > The ninth symphony of Beethoven. > > The food capital of Europe. In fact this is normally just an alternative to possessive s, used to shift back an element for emphasis, or to achieve a more formal style.
stackexchange-ell
{ "answer_score": 1, "question_score": 3, "tags": "relative clauses, possessives" }
Error: GetImaePath Doesnot exist in current context I am binding the gridview to GetImagePath to show the Image at the edit and delete button. as : <asp:ImageButton ID="ibEdit" runat="server" CommandName="EditItem" CausesValidation="false" ImageUrl='<%#GetImagePath("edit.gif")%>' ToolTip="Edit Item" /> &nbsp;&nbsp;&nbsp;&nbsp; <asp:ImageButton ID="ibDelete" runat="server" CausesValidation="false" OnClick="ibDelete_Click" ImageUrl='<%#GetImagePath("action_delete.gif")%>' ToolTip="Delete Item" /> </ItemTemplate> but when i run, it shows me the following error `GetImaePath Doesnot exist in current context` what possible code i am missing or if there are any error. thanks for any assistence.
There should be a C# function defined in code behind (.cs) or in .aspx code block with the name GetImagePath(string image) public string GetImagePath(string image) { // return full image path }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, visual studio, data binding" }
C function modification I had some fun with imitating OOP in C, but I got somewhat discouraged when I understood that I'll have to call member methods like `obj->method(obj, ...)`. Then I thought about cloning and modifying functions at runtime. Can I implement a function like strdup but for functions using a simple parser to identify the return opcode to stop copying and then modify a value in the function to point to the object the member method refers to so that I can use just `obj->method(...)`?
No, at least from what it sounds like you are asking, which is to modify functions at run-time. Modifying functions at run-time is possible but is difficult and requires considerable knowledge (and is system-specific). However, you seem to be asking to be able to execute a function and modify the function so that it does something with the object it is associated with. However, by the time the function is executing, there is generally no information about that object available: In a call like `obj->method(…)`, there is generally no reference to `obj` included in the arguments. So even if you could modify the function at run-time, it does not have the information needed to do the job you want. There are ways to do it at compile-time. That is how C++ developed. If that is a feature you want, the best approach is to use C++.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "c, oop" }
Conditional automatic variable void function(typeA* ptr_to_A) { if (!ptr_to_A) { typeB B; // typeB is a derived class of typeA ptr_to_A = &B; } do_stuff_to_ptr_to_A(ptr_to_A); // my hope is that B is still in scope here so that this function will operate on my B object (which is on the stack) which only gets created if ptr_to_A was initially NULL } Will this function do what I think it does (what I want it to do)? That is, only allocate B on the stack if the argument was a null pointer?
> Will this function do what I think it does? No, it's undefined behavior because `B` goes out of scope. Since this is undefined behavior anything can happen, and therefore you can't predict the results. You want to keep `B` in at least the same scope as the function call, so just move it to the top of the method: void function(typeA* ptr_to_A) { typeB B; // typeB is a derived class of typeA if (!ptr_to_A) { ptr_to_A = &B; } do_stuff_to_ptr_to_A(ptr_to_A); } But if you only want to allocate a `typeB` if `ptr_to_A` is null then you could do this: void function(typeA* ptr_to_A) { if (!ptr_to_A) { typeB B; // typeB is a derived class of typeA do_stuff_to_ptr_to_A(&B); } else { do_stuff_to_ptr_to_A(ptr_to_A); } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, memory, memory management, callstack" }
Write variable in quotes to output file (for %%f in (%zipfiles%) do ( <nul set /p ="%%f", certutil -hashfile "%%f" SHA256|find /v ":" || echo empty file ))> "C:\Location\Report\ListOfFiles.csv" the "%%f" does not work, neither %%"f" nor "/p =%%f", What I want is the filename in quotes: "Filename 001.zip",68b17a9d0d98dd64f3c6c5b29e5cd304a6397d21f24e3087723ccad9f6f77c58
@ECHO OFF SETLOCAL EnableExtensions set "zipfiles=*.zip" (for %%f in (%zipfiles%) do ( <nul set /p =""%%f"," certutil -hashfile "%%f" SHA256|find /v ":" || echo empty file ))>".\ListOfFiles.csv" Here in `<nul set /p =""%%f","`: * outer double quotes used to escape the comma as well as inner double quotes so that * inner double quotes and the comma are copied to the output stream.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "batch file" }
How to connect to AWS Neptune (graph database) with Python? I'm following this tutorial: < How can I add a node and then retrieve the same node? from __future__ import print_function # Python 2/3 compatibility from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection graph = Graph() remoteConn = DriverRemoteConnection('wss://your-neptune-endpoint:8182/gremlin','g') g = graph.traversal().withRemote(remoteConn) print(g.V().limit(2).toList()) remoteConn.close() All the above right now is doing is retrieving 2 nodes right?
If you want to add a vertex and then return the information about the vertex (assuming you did not provide your own ID) you can do something like newId = g.addV("mylabel").id().next()
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "amazon neptune" }
Find values in one column that share same value in different column without knowing the 2nd cols value Given This Table: Relationship managerId companyId 12 33 19 33 27 44 21 33 4 20 Is there a way to find all managerId's that share the same companyId but only by knowing ONE of the managerId's and not knowing the companyId So for example, if we only know that the managerId is `12` SELECT companyId FROM Relationship WHERE managerId = 12 We will obviously get `33` back. But within the same query is there a way to get back all managerId's where the companyId is the value of the return from that first statement. So in this case just by knowing managerId=12 I want to get back `12,19,21`.
Join the table to itself on `companyId`: select b.managerId from relationship a join relationship b on b.companyId = a.companyId where a.managerId = 19
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "mysql, sql" }
Find $\lim_a \frac{Tr^n \left( ({\bf x}-a\cdot{\bf y}) \cdot ({\bf x}-a \cdot{\bf y})^T \right)-Tr^n \left( {\bf x} \cdot {\bf x}^T \right)}{a}$ Let ${\bf x}, {\bf y} \in \mathbb{R}^{ m \times 1}$ and $a \in \mathbb{R}$. How to find the following limit \begin{align} \lim_{a \to 0 } \frac{Tr^n \left( ({\bf x}-a\cdot{\bf y}) \cdot ({\bf x}-a \cdot{\bf y})^T \right)-Tr^n \left( {\bf x} \cdot {\bf x}^T \right)}{a} \end{align} form some $n>0$. For the case $m=1$ we have that \begin{align} \lim_{a \to 0 } \frac{ (x-a\cdot y)^{2n} - x^{2n}}{a}=-2n\cdot y \cdot x^{2n-1} \end{align} But how to do the general case? Thank you
Define the function $T(a) = {\rm tr}\Big((x-ay)(x-ay)^T\Big)$ First, use L'Hopital's rule to reduce the problem to the evaluation of the function $(\frac{dT^n}{da})$ at the point $a=0$. Second, find the derivative $$\eqalign{ w &= (ay-x) \cr T &= {\rm tr}(ww^T) = w^Tw \cr dT &= 2w^Tdw \cr dT^n &= nT^{n-1}dT \cr &= 2nT^{n-1}\,w^Tdw \cr &= 2nT^{n-1}\,w^Ty\,da \cr &= 2nT^{n-1}\,(ay-x)^Ty\,da \cr \frac{dT^n}{da} &= 2nT^{n-1}\,(ay-x)^Ty \cr\cr }$$ Finally, evaluate this derivative at $a=0$ $$\eqalign{ \frac{dT^n}{da} &= -2nT^{n-1}\,x^Ty \cr &= -2n(x^Tx)^{n-1}\,x^Ty \cr }$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "limits, matrix calculus, trace" }
What factors determine consumer group rebalancing time? We recently saw some issues in production where a consumer group was taking on the order of minutes to rebalance when a consumer left the group. This particular consumer group has about 8-10 consumer members at any given time and is subscribing to roughly 15 topics, each with 32 partitions. Essentially trying to figure out what we should look to do in order to make rebalancing take less time. (e.g. do we try and reduce the number of consumers per group? less partitions per topic? etc)
Alright, so after significant trial and error found that the biggest factor in rebalancing time was the number of total topics & partitions that a given consumer group was trying to subscribe to. We had a consumer group that was basically covering about 600~ partitions across 20 or so topics. By changing up our polling strategy, etc. we were able to move to a consumer group per topic and times have dropped drastically.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "apache kafka" }
React way to "setState" in a pure ES2015 function React newb here. I have a pure function that returns a form (presentation component). In this form I need to handle onChange events for those text fields that are controlled. FWIU, I need to this.setState(...) in my onChange event handlers. However due to this being a pure function, I don't have access to this.setState(). Is there a nice way to set the state on these onChange events in a ES2015 function? I'm also using redux if this helps. Example code: import React, {PropTypes} from 'react' const ApplicationForm = ({submitHandler, person}) => ( <form onSubmit={e => submitHandler(e)}> <div> <label htmlFor="firstName">First Name:</label> <input type="text" name="firstName" onChange={e => setState(e.target.value)} value={person.firstName || ''}/> </div> ... </form> )
That is a Stateless Function, there is no state to set If you're using redux, you probably want to trigger a redux action in the onChange, passing the new value as an argument, and have the action update the value of firstName in the redux store for `person.firstName` I would recommend taking a look at redux-form to reduce a bunch of boilerplate
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 5, "tags": "reactjs, redux, react redux" }
If-statement does not work correctly I have the following problem with JavaScript: I have an array with booleans I received from my database and want to do some action if a specific field is true. Because it didn't work I wrote the following: if(data.participants[i].attended) { console.log(data.participants[i].attended); } In my opinion that should just print 1 or nothing on the console, but -because 0 means false in JS- never 0. But when I let it run it prints 0 on the console.
Parse value of variable as integer like this: if(parseInt(data.participants[i].attended)) { console.log(data.participants[i].attended); }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -2, "tags": "javascript, if statement" }
Set up a matlab eclipse interface Could we write an android client to ask for some data from Matlab output and then write the server part in matlab that sends the information to eclipse? How can we do this? Can we do this through wireless connection? Or use internet to connect to computers together to do this? Do you have any example on how we could do this? I'm totally new to socket programming and Matlab.
If you want to make an android client talks to MatLab first you will need to open a socket. That will be made like you would do with java in the android application. An example of socket communication with matlab is seen in here (it uses java): < You can use the same object in android to make a socket comunication (Using java.net.socket): < I just do not understand what you want to do with eclipse.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "android, eclipse, sockets, matlab" }
How do I use dictation paste with applescript? I am trying to make dictation code snippets/templates with applescript because I want to add multi language functionality and toggle between languages to change syntax. What's the programmatic way of using the built in dictation's paste feature? Also, is there any command for cursor placement after paste? Thanks!
If dictation is enabled and running on your system, the command you would say to paste something from your clipboard is “Paste That”. If dictation is enabled and running on your system, you can say the command “Show Commands” … which should open a window showing all of your dictation commands > Also, is there any command for cursor placement after paste? Look at the "Navigation" section of the image below for cursor placement commands ![enter image description here]( Once this window was open you can then say something like. “How Do I Paste”. This should narrow down the results to all of the dictation commands with the word “Paste” ![enter image description here](
stackexchange-apple
{ "answer_score": 0, "question_score": 0, "tags": "macos, applescript, voice dictation" }
Find KNN with a geometry data type using POSTGIS in postgresql i want to find k nearest points for a point with the best performance in postgresql using PostGIS. The structure of my table is : ` CREATE TABLE mylocations (id integer, name varchar, geom geometry); ` sample inserted row is: ` INSERT INTO mylocations VALUES (5, 'Alaska', 'POINT(-172.7078 52.373)'); ` I can find nearest points by ST_Distance() with the following query : ` SELECT ST_Distance(geography(geom), 'POINT(178.1375 51.6186)'::geometry) as distance,ST_AsText(geom),name, id FROM mylocations ORDER BY distance limit 10; ` but actually i want to find them without calculating distance of my points with all points of table. in fact i want to find the best query with best performance, because my table would have huge data. i appreciate for your thoughts
You are missing `<->` operator which `Returns the 2D distance between A and B`. Make sure your `geom` types and `SRID` are the same. SELECT ST_Distance(geom, 'POINT(178.1375 51.6186)'::geometry) as distance, ST_AsText(geom), name, id FROM mylocations ORDER BY geom <-> 'POINT(178.1375 51.6186)'::geometry limit 10
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "postgresql, postgis, knn" }
Living in other EU countries while being on a work visa If I have a work visa from one EU member state and my work is remote, can I live in other EU member states for longer than 90 days out of 180, or is it possible to actually live in other EU member states for as long as my EU work permit is valid?
In general: * You are not covered by the EU freedom of movement (that's for EU citizens and their family). * You are not allowed to live in other EU member states on the basis of your visa. * You are allowed to visit other Schengen countries but only for stays of less than 90 days in any 180 period (if your residence permit is from a Schengen country). If your visa is not from a Schengen country or you want to visit Ireland, even that is not a given, you might still need another visa for a short stay. * You are not allowed to work without additional permission even for less than 90 days. There are a few corner cases and special rules, e.g. for long-term residents (after 5 years) or EU Blue Card holders but nothing that would give you a general right to live anywhere in the EU without restrictions or additional formalities.
stackexchange-travel
{ "answer_score": 14, "question_score": 9, "tags": "eu, working visas, freedom of movement" }
Mongodb database backup on windows Ive got a problem concerning the mongodump function provided in mongodb. When the below code is run on mongodb shell it doesnt respond, Mongodump --db database1 --out path:
mongodump --db students --collection grades Here students is the name of the database and grades is the name of the collection. Running this command will create a folder named dump in your current working directory. A folder with the name of your database will be created inside the dump folder within which you'll get a collection_name.bson file and collection_name.metadata.json file. P.S. : Make sure you're running this command outside mongo shell.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 6, "tags": "mongodb, mongodump, nosql" }
Excel 2013 - Transforming data in Excel I need advice as to how I can create a data entry worksheet in Excel and have it transform into a table in a separate worksheet. This is used for tracking the location of items shipped to different locations. Sample Data - this is the page for data entry Based on the data, plot into a table like this for easier reference Once an item is taken back, the information is deleted and the shipping process continues. Not sure if this can be done in Excel but am just exploring possibilities.
Assuming the source data (1st table) is located in Sheet1, Column A-D, and the 2nd table is in Sheet2, with the "Item Code" text is in A1, "WH1"-"WH3" is in B1-D1. Put in A2 of sheet2 : =IF(Sheet1!A2="","",Sheet1!A2) and drag downwards. Then in B2, put : =IFERROR(INDEX(Sheet1!$C:$C,MATCH(1,INDEX((Sheet1!$A:$A=$A2)*(Sheet1!$B:$B=B$1),0,1),0))&" ("&TEXT(INDEX(Sheet1!$D:$D,MATCH(1,INDEX((Sheet1!$A:$A=$A2)*(Sheet1!$B:$B=B$1),0,1),0)),"MM/DD/YY")&")","") and drag till D6. Idea : use multiple criteria index match to 'load' the values based on values in columnA Sheet2 and Row1 Sheet2. Hope it helps. (: * * * Extra info : The $ in the formula are used to 'lock' the column/row when we copy/drag the 1 cell formula. It saves a LOT of formula re-write when some of the formula element doesn't change per row/column.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "microsoft excel 2013" }
SwiftUI on app load - redirect to web URL In my iOS app, I have a requirement to load a web URL on app load or app icon is tapped by the user. application landing page has a UI but it will only appear after user press back button from the browser. How to redirect to any URL as soon as app is open? I am using swift UI.
You can use `NavigationView` with pre-selected `NavigationLink`: this will open as soon as the view appears. Display your main app only after `NavigationLink` is closed with `if`. struct ContentView: View { var body: some View { MainApp() .onAppear { UIApplication.shared.open(URL(string: " } } } struct MainApp: View { var body: some View { Text("hello") } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, swiftui" }
Get a sublist by class in Java Suppose I have an ArrayList<Fruit> I would like to get all elements from this list of any given subclass of Fruit, such as an ArrayList<Apple> C# seems to have a rather handy OfType<T>() method. Is there an equivalent way of doing this in Java? Cheers
public static <T> Collection<T> ofType(Collection<? super T> col, Class<T> type) { final List<T> ret = new ArrayList<T>(); for (Object o : col) if (type.isInstance(o)) ret.add((T)o); return ret; }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "java, list, generics, subclass" }
android app force closes i have this android code .I have my layout for button defined in the xml file .i want to set the text for button here by getting it by id .but the app force closes.whats wrong ? package com.action ; import android.app.Activity; import android.os.Bundle; import android.widget.Button; public class ActionActivity extends Activity { @Override public void onCreate(Bundle i){ super.onCreate(i); Button button=(Button) findViewById(R.id.but); button.setText("Hey!!"); setContentView(R.layout.main); } } Thnx...
You have to use `setContentView(R.layout.main);` before using `findViewById()`. If you don't do that, `findViewById()` will return `null` (since no view with that ID is in the current layout) and you will get a `NullPointerException` when trying to set the text on the `TextView`. The correct version of `onCreate()` should look like this: public void onCreate(Bundle i) { super.onCreate(i); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.but); button.setText("Hey!!"); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "android, android xml" }
Common way to format Exception The standard format of an exception (like it is printed by the default `sys.excepthook`) is something like "%s: %s" % (type(e).__name__, e) However, that seems error-prone to me. For example, what if `__name__` is not defined? Is there some standard way? I looked into the `traceback` module and it seems to handle quite a few special cases.
The standard way is to use `traceback.format_exception_only`. If you want custom formatting etc. you can copy the logic from there and modify it (e.g. IPython does this).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x" }
Track/Monitor who is using internet, on shared network I live in an apartment with my three other colleagues. We have a broadband network, and monthly rental plan that we share. I use a linux system. Can I track who is using the network at any time, like who is downloading etc.? Thanks for any help in this regard. Also, is there any way with which we can control how much speed one person can have (so that no one can exceed that particular speed limit)?
Yes, you can control how much bandwidth is allocated. Most routers (not all) have a service called QoS (Quality of service) which allows you to fix the bandwidth on a per-application-basis. Mind you, it is not a per-user-basis. Yet, if you suspect that torrent downloads are really the source of your problem, you can easily limit the fraction of available bandwidth allotted to a variety of processes, so as to keep the use of common resources fairly distributed among all users. Also, keep in mind that downloading may very well take place at night, so that you even search for more sophisticated routers allowing a finer control of resource allocation. As for seeing who is doing what on your LAN, the best known instruments is _wireshark_ , which is based upon a cruder-looking program, _tcpdump_ , which is basically only a debugging tool. With wireshark, sorting users, protocols, destination is considerably easier. You may want to look at that.
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "networking, display, internet, broadband" }
CI Model Access -> Unable to locate the model you have specified when model name is specified in lower case letters Everytime the controller tries to access home model, It displays Unable to locate the model you have specified: HomeModel error. The controller has no problem in accessing view. And it was able to access the model class after I changes the model name to lowercase. Can somebody explain why this happens?
When creating a model on codeigniter classes and file names should have there first letter as upper case this also applies for controllers and libraries etc. Home_model.php class Home_model extends CI_Model { public function __construct() { parent::__construct(); } public function some_function() { } } How to load model on controller example only class Welcome extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('home_model'); // Or In a subfolder application / models / subfoldername $this->load->model('subfoldername/home_model'); } public function index() { $data['results'] = $this->home_model->some_function(); $this->load->view('welcome_message', $data) } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, codeigniter, model" }
How to get already saved file in file upload control in replace of 'No file choosen' in Edit mode in asp.net C#? I saved my file in location and get path & file name in database with file upload control.After this when I edit the form then did not get the saved file in file upload cantrol.It showing the blank file upload cantrol.How its possible ?
You can't assign a path to a file upload element. If this means that your web application overwrites the file info when editing, then do a check if a file was actually uploaded when editing.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "asp.net" }
How to prove that $\omega \wedge d \omega =0 $ here? This question is from my exercise in Differential geometry and I am struck on it. So, I am posting it here in hope of getting some help. > Let $\omega$ be a differential $1-$ form on a manifold $M$ and consider a nowhere - vanishing function $f: M \to \mathbb{R} $ such that $d(fw)=0.$ Prove that $\omega \wedge d\omega =0.$ Attempt: we have $d(f\omega)= df\wedge \omega + f d \omega $ and $f(x)\neq 0 $ for all $x\in M$ , we have $d\omega = (-1/f) df \wedge \omega $. As $\omega$ is a differential 1-form , we have $ \omega \wedge d\omega = -(1/f) \omega \wedge df \wedge \omega$ , but I am not able to move forward from this. Can you please help?
You are almost done. Since $$ \omega \wedge d\omega = -(1/f) \omega \wedge df \wedge \omega = (1/f)df \wedge \omega \wedge \omega$$ and $\omega$ is a one form, hence $\omega\wedge \omega = 0$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "differential geometry" }
Why google-collections contains semantically equal functions and strange generics? Why google-collections or guava contains semantically equal functions? example: static <T> Predicate<T> and(Predicate<? super T>... components) static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) I.e. all functions that can accept several arguments. The second question why do defintion of such functions use generic `<? super T>` instead of `<T>`?
To answer the first question, the varargs version (`Predicate<? super T>...`) will give you a warning about the unchecked creation of a generic array when called with several generic predicates (e.g. `Predicate<T>`). For the common case of combining two predicates, you don't get that warning. To answer the second question, taking `Predicate<? super T>` means you can pass in a `Predicate<Object>` (or `Predicate<Number>` or whatever) when calling the method to create a `Predicate<Integer>`. For example, if `Predicates.notNull()` were a `Predicate<Object>` (as it should be) and you wanted to combine that and some `Predicate<Integer>`, it would not be possible if the arguments were required to be of type `Predicate<T>`.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "java, generics, guava" }
Extend get_european_union_countries() function in WooCommerce I'm using a filter that targets the EU countries, which works well. However - I would like to included UK which isn't part of the EU anymore as well as US. Is there a way to extend get_european_union_countries() function in WooCommerce? So I get a specific country (UK, US) from WC_Countries, so I can add it to my `true` statement in my existing code? add_filter( 'wc_aelia_tdbc_keep_prices_fixed', function($keep_prices_fixed): bool { $countries = new WC_Countries(); $eu_countries = $countries->get_european_union_countries(); if ( WC()->customer ) { if ( in_array( WC()->customer->get_billing_country(), $eu_countries ) ) { $keep_prices_fixed = true; } else { $keep_prices_fixed = false; } } return $keep_prices_fixed; });
Besides using your existing code you can use the `woocommerce_european_union_countries` filter hook So you get: function filter_woocommerce_european_union_countries( $countries, $type ) { // Add to the array array_push( $countries, 'UK', 'US' ); return $countries; } add_filter( 'woocommerce_european_union_countries', 'filter_woocommerce_european_union_countries', 10, 2 );
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, wordpress, woocommerce, hook woocommerce" }
Is FunctionA(Exception ex) the same as FunctionB<T>(T ex) where T : Exception? Two simple questions about generics. Are the following two function definitions the same? FunctionA(Exception ex); FunctionB<T>(T ex) where T : Exception; Are there advantages the Generic implementation (FunctionB) has over the normal implementation (FunctionA)?
See this question: Difference between generic argument constrained to an interface and just using the interface
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, generics" }
Batch process an NSArray In PHP I would use `array_chunk` to split up an array then process each chunk. In objective C this doesn't seem so straight forward, is there a cleaner way than something like this? - (void)processTransaction:(NSArray *)transactions { NSInteger batchCount = (transactions.count - 1) / self.batchSize + 1; for (NSInteger batch = 0; batch < batchCount; batch ++) { for (NSInteger batchIndex = 0; batchIndex < self.batchSize; batchIndex++) { NSInteger index = batch * self.batchSize + batchIndex; if (index >= transactions.count) { return; } Transaction *transaction = [transactions objectAtIndex:index]; // Process } // Save } // Done }
If `// Save` isn't too complicated I would do - (void)processTransaction:(NSArray *)transactions { NSInteger batchIndex = 0; for (Transaction *transaction in transactions) { // Process batchIndex++; if (batchIndex >= self.batchSize) { // Save batchIndex = 0; } } if (batchIndex > 0) { // Save } // Done }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, nsarray" }