INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Portable wchar_t in C++
Is there a portable wchar_t in C++? On Windows, its 2 bytes. On everything else is 4 bytes. I would like to use wstring in my application, but this will cause problems if I decide down the line to port it.
|
If you're dealing with use internal to the program, don't worry about it; a wchar_t in class A is the same as in class B.
If you're planning to transfer data between Windows and Linux/MacOSX versions, you've got more than wchar_t to worry about, and you need to come up with means to handle all the details.
You could define a type that you'll define to be four bytes everywhere, and implement your own strings, etc. (since most text handling in C++ is templated), but I don't know how well that would work for your needs.
Something like `typedef int my_char; typedef std::basic_string<my_char> my_string;`
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "c++, windows, portability, wchar t, wstring"
}
|
How to run a command on remote host from a service?
I have a service in '/etc/init.d'. In that service, I run a command on a remote machine using ssh as a user. Currently I do this in the following way:
sudo -u user bash -c "ssh [email protected] 'source ~/.envrc ; (cd /catalog; ./bin/catalog start &)'"
This is the start command of that service and the service name is catalog.
When I do `sudo service catatlog start` the command runs successfully i.e it properly SSH'es into the target machine which is `[email protected]` as the user `user` but it does not start the service.
Can anyone tell me how to tweak this so that it runs successfully?
|
So I fixed it by using `nohup` command:
sudo -iu user ssh [email protected] "nohup bash -c 'source ~/.envrc ; (cd /catalog; ./bin/catalog start &)'"
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": -1,
"tags": "command line, server, bash, ssh"
}
|
dynamically created img tag with jQuery?
How to create dynamically tag inside table. At first create link then inside link create an img tag like if i have..
<table>
<tr>
<td>
<a>
<img />
</a>
// Add Some more when every time my function is run..? like that
// <a>
// <img/>
// </a>
</td>
</tr>
</table>
Im using this inside function but its didn't work help me.
$(document.createElement("img")).attr('Some attr');
|
If you mean JQuery by "jquree", then try this:
$('table tr td').append('<a href="#"><img src="/favicon.ico"/></a>');
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -3,
"tags": "javascript, jquery, asp.net, image, dom"
}
|
social.framework ios5
When I run my app with social framework for facebook on ios5 it crashes, and I can understand that. Is there a way to import it just if the device is ios6?
I tried this, where ver_float is the ios version:
if (ver_float >= 6.0) {
#import <Social/Social.h>
}
But the app fails to run if I remove the #import from the top of the code page.
|
Just make sure you set the Social.framework as optional under Build Phases.
|
stackexchange-stackoverflow
|
{
"answer_score": 28,
"question_score": 7,
"tags": "ios"
}
|
Eclipse for Java EE on Linux - cannot see Java EE projects?
I just installed eclipse indigo on Ubuntu. After, I went to install new software > WEB, XML, Java EE etc.
When I go to Eclipse plugins, I see they are installed.
But when I try to create a new eg Web Project, I cannot see it! The one and only point to choose is "create new > general > project". Nothing else!
What could I be doing wrong?
|
Even though this does not answer the OP's question, I would recommend installing the latest Java EE version from **here** :
`
Back to your question. Perhaps you could try re-starting eclipse with the `-clean` option just to make sure that it's not obsolete workspace metadata which is at fault. If that does not work, I would reiterate the original suggestion to download the Java EE version to save time.
(Please don't be offended, but to rule out the obvious, you must have restarted Eclipse after installing all the plugins ?)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, eclipse, ubuntu"
}
|
converting the variable datatype
I have a data frame with 25 variables.
I would like to convert the columns 2:8 ; 10:17 ; 24:25 as numeric.
I am using a separate for loops to convert the data type. Is there a way, i could use a single for loop and convert them to numeric.
Also, I wanted to convert 9, 18 in date format.
It would be helpful, if you could help me to minimise my code to single for loop
for (i in 2:8){
claim[,i] <- as.numeric(claim[,i])
}
for(i in 10:17){
claim[,i] <- as.numeric(claim[,i])
}
for(i in 24:25){
claim[,i] <- as.numeric(claim[,i])
}
|
Try this one row code:
claim[,c(2:8,10:17,24:25)] <- lapply(claim[,c(2:8,10:17,24:25)], as.numeric)
Adaptation of this answer.
The same could be done with `date` convertion:
claim[,c(9,18)] <- lapply(claim[,c(9,18)], as.Date)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, optimization"
}
|
Drupal 6 administer nodes permission is ignoring content type permissions
I'm needing to set different 'create content' permissions for different user roles. This only appears to work when a particular role has not been given the "administer node" permission. However, without this permission the role does not have permission to control whether or not the node is published (which I require) or to view the content management table (Home › Administer › Content management).
For example, I want a user role to be able to create new news items and to be able to publish/unpublish them, but not create new pages (but be able to edit existing pages).
Does anyone know a way around this? Or which permissions should be set?
|
Administer Nodes permission gives more access than necessary, and some modules use it as a crutch permission since it exists.
You might want to switch off this permission and implement Override Node Options module which will let users publish unpublish content. These can work in conjunction with the create/edit/delete permissions at the content type level.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "drupal, permissions, drupal 6"
}
|
How to select and print IP address from a set of strings?
I have a sentence whic contains an IP address. For example,
This sentence contains an ip number 1.2.3.4 and port number 50, i want to print the IP address only.
From the above sentence, I want to print the IP address only. How can I do this? I heard that it is possible to do this with `sed`
|
It's possible, but not elegant:
echo 'This sentence contains an ip number 1.2.3.4 and port number 50, i want to print the IP address only.' \
| sed 's/.*\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\).*/\1/'
`[0-9]` matches any digit, `\{1,3\}` means it can be repeated 1 to 3 times. `\.` matches a dot. The whole IP is captured by the `\(...\)` parentheses, what comes before and after is matched by `.*`, i.e. anything repeated zero or more times. The whole matching string (i.e. the whole line) is then replaced by the contents of the first matching group.
You can make it more readable by introducing a variable:
n='[0-9]\{1,3\}'
... | sed "s/.*\($n\.$n\.$n\.$n\).*/\1/"
It prints the whole string if the IP is not found. It also doesn't check for invalid IPs like 256.512.999.666.
|
stackexchange-askubuntu
|
{
"answer_score": 7,
"question_score": 3,
"tags": "command line, scripts, sed"
}
|
Does Anypoint studio 5.2.3 Community Edition with runtime 3.7 CE support Munit?
Please clarify the doubt
I'm going to use 5.2.3 Anypoint studio with 3.7 CE runtime, will it support Munit? Thanks.
|
Here is the compatibility info. As it just mention 3.6 and 3.7, it is available for both CE and EE runtimes. CE compatibility is expected as default and would state otherwise if it was only compatible with EE: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mule, mule studio, mule component, mule el"
}
|
Click desktop icon to execute python script in Raspbian
I am trying to make either a .bat or .exe file to execute a python script in linux (Raspbian). I would want to have an icon on the desktop which will be clicked (touch screen) and will then execute the python script.
The python script would need 'sudo' authorization... so if I wanted to run in terminal:
sudo python filelocation/name.py
Thanks!
|
Use a `.desktop` file as nodakai already mentioned.
To have the python file executed with root permissions, either
* use something like `gksudo python program.py`. This will ask the user for the password in a normal window, no terminal involved.
* if the user shall not be asked for a password, consider an entry in the `sudoers` file, and use the usual `sudo python program.py`. (If you use this, make sure your program doesn't allow the user to do whatever they want, but only does the specific tasks you want the user to be able to do as root.)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, linux, raspbian"
}
|
What's the standard interaction pattern for bulk edit / delete actions on windows phones?
I'm looking for the standard pattern for windows phone for bulk actions like delete, archive or move. I mean, for example: How is the user supposed to delete multiple items at once.
I couldn't find anything in the Windows Phone Guidelines
The known pattern for iOS is to have an edit button:
!iOS bulk action
For Android it is to to a long press to select the one item:
!Android bulk action
Is there a recommended pattern for Windows Phone, that is established? What is it?
|
Check out how the standard Windows Phone Mail application handles it.
Tap any mail item at the lefthand edge of the window - a column of checkboxes will slide into view, with the item you just tapped already selected.
The application bar will alter to show you the available bulk actions - _Delete_ and _Move_ are the two main options, with _Mark as Read_ , _Mark as Unread_ , _Set Flag_ , _Complete_ and _Clear Flag_ listed below.
Here's a screenshot showing the checkboxes in use:
!Mail Multiselect
Original webpage: <
|
stackexchange-ux
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mobile, design patterns, windows phone 7"
}
|
Pass options to the forked JVM
I'm using Grails 2.3.5 and I need to pass an option to the forked JVM. I've tried doing this by setting the JAVA_OPTS environment variable, but that simply gets ignored by the forked JVM. How can I go about passing the forked JVM an option?
I've found this link, which is now dead: < but that's if you're using the Maven plugin I believe. I'm looking for the equivalent but without having to get Maven plugin involved.
|
According to: < (near the bottom of the section) you can use `jvmArgs` in your `grails.project.fork` configuration. In BuildConfig:
grails.project.fork = [
// ...
run: [maxMemory:1024, minMemory:64, debug:false, maxPerm:256, jvmArgs: '..arbitrary JVM arguments..']
// ...
]
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "grails, jvm, fork"
}
|
$|G|= 2^n, o(g)=2~\forall g \in G, g \neq e$ show that G is abelian
Question as in title: I have attempted this question by saying that the homomorpism that maps G to $Z_2$ is onto, $Z_2$ is abelian so G must be abelian.
|
We have, for all $a,b\in G$, $$abba=e=baba$$ Hence $ab=ba$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "abstract algebra, group theory, finite groups"
}
|
Write multiple labels from sql database
I have 2 labels that need to be given value from sql server db
so
sql = "SELECT name FROM table WHERE id=2"
sqldr = sqlcmd.executereader
while sqldr.read
label1.text = sqldr(0)
label2.text = sqldr(0)
end while
now how do i put two different values in these two labels??
|
Try this:
Dim index as integer
while sqldr.read
Select case index
Case 0
label1.text = sqldr(0)
Case 1
label2.text = sqldr(0)
End Select
index += 1
end while
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server, vb.net, label"
}
|
Find all kinds of homomorphisms from $(\Bbb Z_n, +)$ to $(\Bbb C^*, \times)$.
Find all kinds of homomorphisms from $(\Bbb Z_n, +)$ to $(\Bbb C^*, \times)$ and from $(\Bbb Z, +)$ to $(\Bbb C^*, \times)$. Explain why they are the complete collection.
> My intuition is:
1) we can construct $\phi:\Bbb Z_n \to \Bbb C^*$ then $Im(\phi)\le n $
Again $\Bbb Z_n/{\ker \phi} \cong Im(\phi)$.
Some finite subgroups of $\Bbb C^*$ are in $S^1$, i.e.,
$\phi:\Bbb Z_n \to S^1$ s.t $x \mapsto e^{2x\frac{\pi}{n}} $, if $n$ is not prime then we can construct more like this also in each case we have the trivial homomorphism.
So are these the only possibilities or there are more?? Again prove whatever your conclusion is.
2) Same like 1) here we can construct $\phi:\Bbb Z \to S^1$ s.t $x \mapsto e^{2x\frac{\pi}{r}} $ , where $r \in \Bbb R \setminus \Bbb Q$. What next now??
|
Let $\varphi$ such morphism so we have $\varphi(\overline 0)=1$ and let $a=\varphi(\overline 1)$ then we have
$$\varphi(\overline n)=\varphi(n\times \overline 1)=a^n=1\implies a=\exp\left(\frac{2ik\pi}{n}\right),\quad k\in\\{0,\ldots,n-1\\}$$ Finally we verify easily that the $n$ maps defined by $$\varphi_k(\overline1)=\exp\left(\frac{2ik\pi}{n}\right),\quad k\in\\{0,\ldots,n-1\\}$$ are morphism of groups.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "abstract algebra, group theory, finite groups, group homomorphism"
}
|
What exactly is an audio queue processing tap?
These have been around in OS X for a little while now and just recently became available in ios with ios 6. I am trying to figure what they let you do exactly. So the idea is you can tap into an audio queue and process the data before sending it on. Does this mean you can now intercept raw audio coming from different applications and process that (such as the iOS music player) before it plays? In other words is inter-app audio possible? I have read over the audioQueue.h file and can't quite figure out what to make of it.
|
Consider it a mid-level entry for your audio custom processing (e.g. insert effect) or reading (e.g. for analysis or display purposes) of the queue's sample data. A basic interface for reading or processing an AQ's data.
> Does this mean you can now intercept raw audio coming from different applications and process that (such as the iOS music player) before it plays? In other words is inter-app audio possible?
Nope - it's not inter-process; you have no access to other processes' audio queues. These are for _your_ queues' sample data. They can be used to simplify general audio render or analysis chains (the common case, by app count). My guess is that it was provided because a lot of people wanted an _easier_ entry to access this sample data for processing or analysis. Custom processing entries on iOS can also be more complicated to implement (i.e. AudioUnit availability is restricted).
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "ios, core audio, audioqueue"
}
|
Comparing fragments of a single file or parts of two distinct files
In JetBrains' IDEs (PhpStorm) -- is there any way to compare two fragments of a single file or parts of two distinct files?
|
Yes, and it should work for both cases. First select the first text that you want to compare and copy it. Then select the second text, right click and select "compare with clipboard"
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "phpstorm, diff, jetbrains ide"
}
|
How do I roll around?
In Metal Gear Solid 5: Ground Zeroes/The Phantom Pain, how do I roll using a controller & keyboard and mouse?
|
To roll around you need to...
1. Lie down (keep the crouch button pressed)
2. Aim
3. Move either left or right
4. Press the sprint button
You must be moving while pressing the sprint button, and you must be aiming while moving.
|
stackexchange-gaming
|
{
"answer_score": 2,
"question_score": 1,
"tags": "metal gear solid 5 the phantom pain, metal gear solid 5 ground zeroes"
}
|
Problem with fseek
Here is my code.
if(fseek(file,position,SEEK_SET)!=0)
{
throw std::runtime_error("can't seek to specified position");
}
I used to assume that even if `position` is greater than num of characters in file this code would work correct (i.e. throw error), but it wouldn't. So I want to know how can I handle seeking failure when trying to seek out of file range?
|
Well, you can always check for file length before doing the `fseek`.
void safe_seek(FILE* f, off_t offset) {
fseek(f, 0, SEEK_END);
off_t file_length = ftell(f);
if (file_length < offset) {
// throw!
}
fseek(f, offset, SEEK_SET);
}
Be aware though that this is not thread safe.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++, c, file, fseek"
}
|
SQL server express edition a pre-requisite for using a SQL Database
I have created a windows form application which uses an SQL database. The database will be copied by the setup onto the end user's computer. But is it necessary that the end computer should have SQL server express edition installed or just installing the .NET Framework would do?
Need this info for creating the setup file.
|
To use an ".mdf" database file, you need to have SQL Server installed. Either using an Express Edition (and attaching it as a user instance), or one of the more uplevel editions (e.g. Standard, Enterprise).
If you want to avoid an installation, you might be able to use SQL Server Compact, (creates ".sdf" files), which can just be bin deployed.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": ".net, sql server 2008"
}
|
Express.js how to retrieve a request IP securely?
Since I cant use SSL over some servers that are sending sensitive data using `bearer tokens`. I was thinking about assigning an IP address when the user logs in, and attaching it to each JWT in a database, and checking it before refreshing it (short lived access tokens). The problem ive found is that I dont know how to securely retrieve the IP in the backend.
I have seen that you can set a `app.set('trust proxy', true)` to your express initialization and then retrieve ip addresses with `req.ip` , but apparently since app.set trusts proxies, it means that the headers received by express can be modified by an attacker right? So it would be pointless, since anyone could embeed a fake ip.
Is there any alternative to this that is not using ssl, and not using aes to encrypt the bearer tokens?
|
As mentioned by CaptEmulation, you should **always** enable SSL on production servers especially when authenticating users.
That being said, I believe it is not possible to spoof an IP address when sending a request to a server. The IP address is used to route data back to an attacker so it has to be either the attacker’s ISP-assigned, VPN-assigned or proxy-assigned IP.
**IMPORTANT WARNING:** As mentioned by jfriend00, although it is not possible to spoof an IP, without SSL, it is possible to put together a man-in-the-middle attack and intercept or manipulate the data that is sent between users and the server.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "node.js, express"
}
|
Find the angle between vectors a and b
If vectors $\mathbf{a}$ and $\mathbf{b}$ are given and $|\mathbf{a}|=|\mathbf{b}| = 1$, find the angle between $\mathbf{a}$ and $\mathbf{b}$ so that vectors $\mathbf{p}=\sqrt{3}\, \mathbf{a}-\mathbf{b}$ and $\mathbf{q}=-\mathbf{a}+\sqrt{3}\, \mathbf{b}$ are perpendicular.
I don't really know how to begin solving this problem. Any input is appreciated.
The given answer is $\dfrac{\pi}{6}$.
|
So we know that via the inner product; if $\vec{p}$ and $\vec{q}$ are perpendicular, then:
$$\vec{p}\cdot\vec{q}=0$$
Therefore, substituting the given expressions for $\vec{p}$ and $\vec{q}$ into this, we require:
$$(\sqrt{3}\vec{a} - \vec{b})\cdot(-\vec{a}+\sqrt{3}\vec{b}) = 0$$
Expanding this, we have:
$$-\sqrt{3}(\vec{a}\cdot\vec{a}) +(\vec{b}\cdot\vec{a}) + 3(\vec{a}\cdot\vec{b}) - \sqrt{3}(\vec{b}\cdot\vec{b}) = 0$$
However, we also know that for any vector $\vec{v}$, $\vec{v}\cdot\vec{v} = \|\vec{v}\|^{2}$. And we know that $\|\vec{a}\| = \|\vec{b}\| = 1$. Thus:
$$-\sqrt{3} + 4(\vec{a}\cdot\vec{b}) - \sqrt{3} = 0 \implies 4(\vec{a}\cdot\vec{b}) = 2\sqrt{3} \implies \vec{a}\cdot\vec{b} = \frac{\sqrt{3}}{2}$$
Going to our definition of the dot product: $\vec{u}\cdot\vec{v} = \|\vec{u}\|\|\vec{v}\|\cos(\theta_{uv})$. Therefore:
$$\cos(\theta_{uv})=\frac{\sqrt{3}}{2} \implies \theta_{uv} = \cos^{-1}\left(\frac{\sqrt{3}}{2}\right) = \frac{\pi}{6}$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "vectors"
}
|
Unable to understand that why previous view open without any button action perform?
i have two view in my app there are one button in first view so when i click on this button then second view open
My problem is on second view when i horizontally swipe or scroll then why first view open without logout process or back button action perform?
please some one help me
|
You must have push to the second view , This is default behaviour of iOS after iOS 7.
You need to add this code for iOS 8
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return NO;
}
For more information , Please follow this link
Hope this helps!.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, objective c, xcode, xib"
}
|
Go : go get $GOPATH error, when GOPATH is set
When running the go get command :
sudo go get github.com/go-sql-driver/mysql
I get the following error
> package github.com/go-sql-driver/mysql: cannot download, $GOPATH not set. For more details see: go help gopath
**However $GOPATH is already set.**
Running `echo $GOPATH` gives `/Users/userxyz/Desktop/Code`
Running `go env` gives
.....
GOPATH="/Users/userxyz/Desktop/Code"
...
GOROOT="/usr/local/go"
.....
I have already tried setting GOPATH as an environment variable by adding the following lines
export GOPATH="$HOME/Desktop/Code"
export PATH=$PATH:$GOPATH/bin
to the following files, alternatively
~/.profile (/etc/profile)
~/.bashrc
~/.bash_profile
|
sudo go get github.com/go-sql-driver/mysql
This runs `go get` under `root` user, which does not have `$GOPATH` set.
Just do:
go get github.com/go-sql-driver/mysql
Generally, do:
go get
in the project folder, and it will install all dependencies. The following will install dependencies mentioned in tests:
go get -t
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "macos, go, environment variables, osx mavericks"
}
|
Running a command using puppet only if it has not been executed earlier
Suppose I want to make sure that my VM has devstack on it.
exec{ "openstack":
command => "git clone
}
This is the puppet code I write for it and it works fine for the first time. Now I want to put a check. I want to clone the repository only if it has not been done already. How to do that
|
You say
exec { 'openstack':
command => 'git clone
creates => '/path/to/somewhere/devstack',
cwd => '/path/to/somewhere',
path => '/usr/bin',
}
Now if the directory `/path/to/somewhere/devstack` exists the clone command won't run.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "puppet"
}
|
Does the bolt really rise upward?
In this site,when the elevator rises up,the bolt falls downward under the force of gravity . But when distance is measured it is shown that it rises up,velocity becomes 0 & then it falls with respect to the shaft(earth) . One has asked the question in that site but the answer is not satisfactory. The bolt was falling downward so why in measuring distance, it rose up inspite of being under the gravity? What is the cause? Plz help.
|
!enter image description here
Velocity plots of bolt in two frames of reference.
One: with respect to the floor/shaft. Elevator accelerates up and after two seconds it (and the bolt) has velocity of $2.4 m/s$. The bolt now breaks loose: it no longer experiences the upward force from the elevator, so it starts accelerating downwards - it will take about 1/4 of a second to lose its upward velocity ($2.4/9.8$), during which time it continues to move away from the floor. However relative to the elevator it is already dropping.
Two: with respect to the elevator car. The car stands still and the floor is accelerating away at $1.2 m/s^2$. After two seconds the bolt starts falling towards the floor with acceleration $g$. But the floor has a "head start" of two seconds. You can compute the distance from the top of the elevator to the floor as a function of time, and do your calculation that way.
|
stackexchange-physics
|
{
"answer_score": 2,
"question_score": 0,
"tags": "newtonian mechanics"
}
|
How to have a cornerradius on Flex 4 TextInput component
How do I get corner radius on my TextInput component in Flex 4.
<s:TextInput prompt="username" width="150" maxChars="100" id="txt_username"
color="#000000"/>
|
Create a custom skin (possibly by copying spark TextInputSkin) and add a border graphic with rounded corners, like this:
<!-- border -->
<s:Rect id="border" left="0" right="0" top="0" bottom="0"
radiusX="10" radiusY="10">
<s:stroke>
<s:SolidColorStroke id="borderStroke" weight="1" />
</s:stroke>
</s:Rect>
If you want more special rounded corners you can also use these attributes:
topLeftRadiusX="4" topLeftRadiusY="8"
bottomLeftRadiusX="2" bottomRightRadiusY="10"
The default TextInputSkin does not allow for rounded corners, so there is no style that you could set on your TextInput to do it. So, no, there's no other way than creating a custom skin class.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 2,
"tags": "apache flex, flex4"
}
|
Merging development branch after master branch has changed (committed)
I have been working on a `development` branch for some time, meanwhile, another developer has been making changes to the `master` branch (several commits to the master).
The `master` branch now has content that I do not have in my `development` branch.
Can I merge the `development` branch without effecting the new commits in the `master` branch? i.e. not overwrite any new work in the `master`?
What is the best way to handle this?
|
No, the principle of merges in git is additive, you can't "overwrite" commits with a merge.
Initial situation
A---B---C---D <<< master
\
E---F <<< development <<< HEAD
Your coworker has made commits `C` and `D`. Let's now merge `development` into `master`.
git checkout master
git merge development
A---B---C---D---G <<< development, master <<< HEAD
\ /
E-------F
At this point, commits made on your `development` branch are reachable from either branch, but the commits `C` and `D` are still here.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "git, github, git merge, branching and merging"
}
|
Update inside a read uncommitted transaction
I am having an SP with transaction isolation level set as Read Uncommitted. For Example
Create Procedure TrailSP
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
BEGIN TRY
UPDATE TrialTable
SET TrailColumn ='Update'
WHERE TrailID=1
--this is followed by more updates and selects
END TRY
BEGIN CATCH
RETURN -1;
END CATCH
RETURN 0;
what I want to know is that the first update I have given in the SP will it get committed instantly as it executes or will it get committed along with the rest of the logic at the end of Sp.
|
It will get committed, as any update under any transaction isolation level, when the **transaction commits**. This has _nothing_ to do with the stored procedure ending.
If the call to your procedure has a transaction, then the commit will occur when _that_ transaction commits.
If the call to your procedure does not have a transaction but the session has enabled implicit transactions then it will commit when the application explicitly commits.
If the call to your procedure does not have a transaction and session has the auto commit transaction behavior (ie. the most common case) then transaction will commit when the UPDATE statement completes.
Enabling READ UNCOMMITTED for an UPDATE is a no-op.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sql, sql server, tsql, transactions"
}
|
How to apply "hover" and "visited" styles to a hyperlink within an existing style in an external css page in asp.net
I would like to apply styles such as this for hyperlinks :
a:link {
color: lightsteelblue;
text-decoration:none;}
a:hover {
color: black;
text-decoration:none;}
However have it within a existing style on the css sheet. e.g
.menuitems {
padding-top: 13px;
margin-right : 30px;
a:hover
color: black;
text-decoration:none;}
Is there any possible way of doing this
|
.menuitems a:link{color: lightsteelblue;text-decoration:none}
.menuitems a:hover{color: black; text-decoration:none}
Your question should be tagged as css.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css"
}
|
How can I link two objects
I have two separate accounts from the same organizations, Account reps. need these accounts linked but not merged.
|
Why not just make one a child-account of the other, or make both records be children of another "master" account for that organization?
|
stackexchange-salesforce
|
{
"answer_score": 3,
"question_score": -1,
"tags": "custom object"
}
|
Is it possible to upgrade sitecore commerce from 9.0.2 to 9.1
I was trying to upgrade `Sitecore commerce from 9.0.2` to 9.1 but couldn't find any documentation for the direct upgrade. It is suggesting to upgrade from `Sitecore commerce 9.0.2` to 9.0.3 and then from 9.0.3 to 9.1.
Is a direct upgrade not possible?
|
There is **no direct upgrade path from 9.0.2 to 9.1** (for now)
I suggest to install Sitecore Commerce 9.1 from scratch.
Only what you need to do:
* update Visual Studio Nuget Packages references to Sitecore 9.1 versions
* fix and make compatibility for you custom code (if it's needed)
* deploy your customizations
I used this way, instead of migration from version to version and it really saved my time.
More explanation you can find here: Sitecore Commerce Upgrade path
|
stackexchange-sitecore
|
{
"answer_score": 4,
"question_score": 0,
"tags": "sitecore commerce, upgrade"
}
|
Can I override which scripts are loaded by Juice UI?
This is a follow on question to SO Question - enter link description here.
Is it possible to override which scripts are loaded w/o recompiling juice? Or to add a script for a custom jquery-ui based control?
|
If you have a jQuery UI widget that you want to hook up to Juice UI, you can do so very easily. There isn't any documentation for the process as yet, but there are lots of examples you can follow. I'd recommend taking a look at the ProgressBar.cs file and how it matches to the ui-progressbar.js file in the jQuery UI source. You can also have a look at the source code for Wijmo Open for Juice UI - they built an entire extension library using Juice UI to hook up their jQuery UI widget library.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "juice ui"
}
|
"Invalid or incomplete multibyte or wide character" running v4l2-ctl
Using iTerm, I'm SSHing into my raspberry pi (raspbian) to control a home security system I've setup.
I need to change the focus of my camera, so I'm running `v4l2-ctl -c focus_absolute=0` on my terminal.
I've been doing this for weeks, and it hasn't given me any issues. Today, when running the command I've started getting the following error:
VIDIOC_S_EXT_CTRLS: failed: Invalid or incomplete multibyte or wide character
focus_absolute: Invalid or incomplete multibyte or wide character
What could be causing it to suddenly be throwing this error? I've been running the exact same command for weeks without a problem.
|
I found the answer in here: < Turns out that when, for example, the camera's `auto_exposure` setting is set to `1` (`true`) then, whenever you modify settings that are controlled by that "automatic" setting, in this case the `absolute_exposure`, you will get that useless error because you have to first change the `auto_exposure` to `0` (`false`) in order to change the settings controlled by it
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 10,
"tags": "raspberry pi, v4l2, iterm"
}
|
When does magento pull transactional emails from template files vs. CMS?
We have configured our emails in the Magento CMS under
system > transactional emails
However, I've noticed now that after placing an order, the email is using the template file located in
/app/locale/en_US/template/email/sales/order_new_guest.html
Why is Magento pulling the email from this file instead of the CMS?
|
After configuring emails in CMS, you required one more step in order to use those newly created emails. Go to `System > Configuration > Sales > Sales Emails` And select your new email templates. Default email templates will be selected by default already. You have to change it from the given select list(your newly created email will be at the end of list)
|
stackexchange-magento
|
{
"answer_score": 6,
"question_score": 2,
"tags": "magento 1.7, email templates"
}
|
UIBarButtonSystemItemTrash Image
Is it possible to retrieve the image that is displayed on the `UIBarButtonItem` when it's initialized with `UIBarButtonSystemItemTrash`?
|
Well, I took the one from Apple and recreated it using Photoshop.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, uibarbuttonitem"
}
|
Give an Alias to a Joined Table MySQL
Is it possible to give an alias to a joined table in MySQL? For example
Select *
From Customers
Natural Join Transaction as CT
Where (Select Count(CT.Customer_ID) ) >= 2
Would CT reference the joined table or the Transaction table? And if it references the Transaction table how do I reference the joined table in a sub query?
|
No, you cannot do this in MySQL. In other databases, you could use a CTE for this purpose. (And in any database, you could use a temporary table, but that is not a good solution.)
Note: Do not use `natural join`. It is a bug waiting to happen.
To expression your query, use either an `ON` or `USING` clause. For your query, it would be something like this:
Select c.*, ct.*
From Customers c Join
Transaction as CT
ON c.Customer_ID = CT.Customer_ID JOIN
(select t2.Customer_ID, count(*) as cnt
from Transaction t
group by t2.CustomerId
where cnt >= 2
) cct
ON cct.Customer_ID = cct.Customer_Id;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "mysql"
}
|
Group array of objects by key
I've got an array of objects containing IDs (non unique)
[ { a: 1 }, { a: 1 }, { a: 2 }, { a: 1 }, { a: 1 }, { a: 1 } ]
I'm trying to group objects by their keys, for example:
[ [{ a: 1 }, { a: 1 }], [{ a: 2 }], [{ a: 1 }, { a: 1 }, { a: 1 }] ]
Initially I thought to iterate over each object, recursively checking all previous keys - but as the list is going to contain hundreds of objects, that would be inefficient.
Is there an inbuilt lodash method that would be suitable for this? or else what would be the best approach
|
Your question is difficult to understand, but going purely by your single input/output example (without knowing the underlying structure of your data), you could do something like the following:
var input = [ { a: 1 }, { a: 1 }, { a: 2 }, { a: 1 }, { a: 1 }, { a: 1 } ]
// function that compares equality of your objects
function matches(a, b){
return ...
}
var output = [[input[0]]]
var cur = output[0]
for(var i=1; i<input.length; i++){
// if the next item doesn't match the previous,
// create the next sub array
if(!matches(input[i], input[i-1])){
cur = [input[i]]
output.push(cur)
}
cur.push(input[i])
}
* * *
However, by the look of your data and requirement, it would seem like you might need to rethink your data structure.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, lodash"
}
|
File upload via FTP error
Code:
$file = '/export/clients.xml';
$remote_file = '/clients.xml';
$ftp_server = "ftp://my.address.com";
$ftp_user_name = "user";
$ftp_user_pass = "password";
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
ftp_close($conn_id);
Now the original file path is: <ftp://[email protected]/domains/website.com/public_html/export/clients.xml>
How should I write the file path so that it could complete the file transfer? I want the file to be copied into the root directory of my FTP server. But it doesn't work this way.
|
Problem was FTP server name. I removed the ftp:// part and now it's working.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, file, ftp, copy"
}
|
AndAlso/OrElse in VBA
I'm trying to get a lazy evaluation with 'And' in my Excel macro by doing the following:
If Not myObject Is Nothing *And* myObject.test() Then
'do something'
Else
'do something else'
End If
I know lazy evaluation exists in VB.NET as `AndAlso` and `OrElse` but cannot find anything similar in VBA. If lazy evaluation does not exist in VBA, what's the best way to structure the code so that it will evaluate the way I expect?
|
The only short circuiting (of a sort) is within `Case` expression evaluation, so the following ungainly statement does what I think you're asking;
Select Case True
Case (myObject Is Nothing), Not myObject.test()
MsgBox "no instance or test == false"
Case Else
MsgBox "got instance & test == true"
End Select
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 55,
"question_score": 49,
"tags": "vb.net, vba"
}
|
What is the purpose of throwing all caught exceptions?
I'm going through our code for our core programs to refactor and I encountered this weird try/catch block
try {
//Do some socket and network stuff
} catch (NoRouteToHostException e) {
throw e;
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
//Does some counting stuff over here
}
Now I can't understand why on earth someone would do something like this, the people who wrote this code have left the company, but were indeed very skilled.
Is there a purpose to this try/catch block? Would it not be better to just throw these exceptions and do the finally things from where the method is called?
|
Either they didn't know they could write `try-finally` without `catch` or it's a legacy piece and it formerly performed something different for each `catch` block.
Otherwise, it makes no sense and it's identical to
try {
// Do some socket and network stuff
} finally {
// Does some counting stuff over here
}
Even skilled people tend to make mistakes, particularly when a deadline approaches.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, exception"
}
|
Haskell recursion odd
I have to define my own predicate function that recursively searches a list of numbers and returns `True` if it finds an odd number, `False` otherwise.
I have set `X = [1..100]` for test data that I need to show. However, I am a bit unsure about how to get recursion to search the list. I'm not looking for the definitive answer but an explanation on how recursion would go around searching in a list.
|
What you want is the function `any odd`:
any :: (a -> Bool) -> [a] -> Bool
Odd :: Integral a => a -> Bool
any odd :: Integral a => [a] -> Bool
anyOdd :: Integral a => [a] -> Bool
anyOdd = any odd
If you want to define the `anyOdd` function yourself then you would have to use recursion:
anyOdd :: Integral a => [a] -> Bool
anyOdd [] = undefined
anyOdd (x:xs)
| odd x = undefined
| otherwise = undefined
You will need to replace `undefined` with your actual logic.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "list, haskell"
}
|
Curl command no return
Im working with an api, in the documentaion found here: < There is an example curl:
`curl -H “Authentication-Key: {API Key}” -H “Authentication-Secret:{API secret}”
I ran that code like this in terminal:
curl -H “Authentication-Key:XX” -H “Authentication-Secret:XX”
It runs but returns nothing.
|
You are using Header inside `“...”` that is wrong. You have to use double quote `"..."` (not sure what it is called, standard double quote?).
So it should be:
curl -H "Authentication-Key:XX" -H "Authentication-Secret:XX"
As a note, currently your curl is sending the headers as following with extra characters.
“Authentication-Key:XX”
“Authentication-Secret:XX”
But it should be:
Authentication-Key:XX
Authentication-Secret:XX
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "api, curl"
}
|
Same root category, different category structure based on store views
I have 2 store views sharing the same root category.
Is it possible to change the category structure based on store view?
If I drag the category on a store view it makes the change in the other store view.
Maybe there is a setting that I don't know.
To be clearer, I need a sub-category to have different parents based on store view, without duplicating it.
|
This is not possible by default without duplicating the sub category and setting it to display only on the Store View that you want it to display on. Note this will also effect the URL path to the products in the sub categories.
|
stackexchange-magento
|
{
"answer_score": 2,
"question_score": 2,
"tags": "category, catalog"
}
|
C programing, For Loop to get each number without using Array
To write a function to get ages from one user, (user's typing is shown in BOLD) Here is a sample
How many people: **3**
Enter age of person 1: **12**
Enter age of person 2: **10**
Enter age of person 3: **15**
There are 3 People and ages are: 12, 10, and 15
I am confused how to not use array for this kind of question!!! PLZ HELP!!!
|
Lashane suggested:
> Use recursion without array.
It is a fantastic idea. Here's how you could go about it.
#include <stdio.h>
void print_rec(int index, int maxindex)
{
int age;
printf("Enter age of person %d",index);
scanf("%d",&age);
if (index == maxindex)
{
printf("The ages are %d ",age);
return;
}
print_rec(index + 1, maxindex);
printf(",%d",age);
}
int main()
{
printf("Enter the number of people : ");
int num;
scanf("%d",&num);
print_rec(1,num);
return 0;
}
The only shortcoming, though is it prints the age in **reverse order**.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -4,
"tags": "c"
}
|
Why is my Text in center when i did not wrap it with Center Widget?
I am trying to figure out why my Text appears in the top Center of the container when i did not used the Center Widget as the parent widget for Text...
Card(
child: InkWell(
child: Container(
color: Colors.grey[700],
width: 380,
height: 100,
child: Column(children: [
Padding(
padding: EdgeInsets.only(top: 6),
),
Text(
'16:00 - 18:00',
style: TextStyle(
fontFamily: 'Spartan',
fontSize: 30,
color: Colors.yellow[600]),
),
])),
),
elevation: 2.0,
)
|
The Column widget has alignment on his own. Try changing it's `crossAxisAlignment` property to `.start` to align the Text to the left, or `.end` to do it to the right
Column(
...
crossAxisAlignment: CrossAxisAlignment.start,
...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "flutter, dart"
}
|
How to reference a .jar file within a Java program in Eclipse
I have a .jar file which I can run from the Terminal on OS X, which takes input from the Terminal and yields output in the Terminal as well. Is it possible to incorporate this .jar file into an Eclipse Java project, where I can give the input within the Java project that goes to the .jar file and also receive the output as a String or something I can manipulate?
Thanks a lot.
|
The short answer is yes.
The "dumb" approach would be to use a ProcessBuilder to interact with the jar via the command-line programatically.
A better approach would be if the jar exposes an API of some kind. Then you just need to add the jar to the classpath and use the functions like you would any other function.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java, eclipse, jar"
}
|
Choosing between multiple executables with same name in Linux
The system I am using has `gnuplot` installed in `/usr/bin`. I don't have root, but I needed a newer version of `gnuplot`, so I installed it to `$HOME/usr/bin`.
I added `$HOME/usr/bin` to my path, but it still executes the one in `/usr/bin` if I just use the gnuplot command. I'd rather not have to specify `$HOME/usr/bin/gnuplot` every time I have to use it.
How do I tell Linux to use the one in my home directory, and not the one in `/usr/bin`?
|
Executables are found in PATH order. You need to prepend `${HOME}/usr/bin` to your path, like so:
export PATH="${HOME}/usr/bin:$PATH"
|
stackexchange-stackoverflow
|
{
"answer_score": 44,
"question_score": 42,
"tags": "linux, path"
}
|
haskell function declaration
I have been playing around with haskell and I found out that if I write the following function in a code file:
f :: Int -> [a] -> a
f idx str = last $ (take . succ) idx str
then this works totally fine. Naturally, I figured the code would look better without the arguments.
f :: Int -> [a] -> a
f = last $ (take . succ)
But this generates an error when I try to load it into gchi
Couldn't match expected type `[a]'
against inferred type `Int -> [a1] -> [a1]'
In the second argument of `($)', namely `(take . succ)'
In the expression: last $ (take . succ)
In the definition of `f': f = last $ (take . succ)
Failed, modules loaded: none.
I'm kind of confused about how this could be happening...
|
This is what happens when you try to compose `last` with `(take . succ)`
:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
last :: [t] -> t ~ (b -> c)
-- so b ~ [t] and c ~ t
(take . succ) :: Int -> [t] -> [t]
-- so a ~ int and b ~ [t] -> [t]
Type of b is inferred to be `[t]` from `last` but it couldn't match against the type of b in `(take . succ)` which is `[t] -> [t]`
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "haskell"
}
|
Spurious space after command in ConTeXt
Is it possible to define a macro in ConTeXt which gobbles space after the argument? For example, given this input:
\def\thing{\dosingleargument\dothing}
\def\dothing[#1]{thing#1}
\starttext
\thing[hello]
\thing[world]
\stoptext
This produces the following output:
': no suitable method found to override MMCClient.WindowsPhone D:\Projects\NewMMC_WP_Client.Shared\App.xaml.cs 64
If I add new universal application v8.1 project to that solution it built good.
Can sombody help me figure out that problem?
|
I can't find any solution for my problem.
So I uninstall all development stuff (visual studio, emulators, sdk and other) and reinstall VS2015 Community + WP 8.1 SDK. And now my project builds fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "visual studio 2013, visual studio 2015, win universal app"
}
|
Mac OS Lion and Sandboxing
I am developping a file manager app for Mac OS and I was wondering what can be the impact of the new sandboxing function of Mac OS.
Any experience?
Thanks
|
Sandboxing your application is currently optional. You have to put code in your application to sandbox it by using the sandbox_init() function.
**References** :
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "cocoa, macos, sandbox, osx lion"
}
|
printing out a list of string using a for loop and a specified format
so i am supposed to print out a list of string in this format. 2017/2018 , 2018/2019, 2019/2020 up until 2029/2030 in this same format, please i am stuck and have no idea how to go about it.
public List<String> getSessions() {
StringBuilder sb = new StringBuilder();
int a = 0;
int b = 0;
String firstHalf = "2017";
String otherHalf = "2018";
List<String> session = new ArrayList<>();
for(int i = 0; i < 13; i++) {
a = Integer.parseInt(firstHalf) + 1;
sb.append(a);
sb.append("/");
for(int j = i; j < 13; j++) {
b = Integer.parseInt(otherHalf) + 1;
sb.append(b);
}
session.add(sb.toString());
}
System.out.println(session);
return session;
}
however it doesn't do the needed, please help me out. thanks
|
Not sure what you're trying to do, but you can use this to print out values :
List<String> session = new ArrayList<>();
for (int i = 2017; i < 2030; i++) {
session.add(i + "/" + (i + 1) + "\n");
}
System.out.println(session);
You don't need to use a nested loop or even a StringBuilder.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "java"
}
|
Is std::vector X(0) guaranteed not to allocate?
In theory, given:
std::vector X(0);
Then X will allocate memory from the stack for itself, but is it guaranteed not to allocate heap memory?
In other words, since implementations will generally use a pointer for the vector, is this pointer always initially 0?
Note: this is not the same as Initial capacity of vector in C++ since that asks about capacity when no argument is passed to the constructor, not about guarantees on heap allocations when capacity is 0; The fact that capacity can be non-zero in this case illustrates the difference.
|
That constructor calls `explicit vector( size_type count )` which does:
> Constructs the container with count default-inserted instances of T. No copies are made.
The only guarantee you get is that the vector will be empty, its `size()` will be 0. Implementations are allowed to allocate whatever they want for book keeping or whatever on initialization.
So if your question is if you can count on `X` taking up 0 bytes of free store space then the answer is **_no_**.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c++, vector, language lawyer, allocation"
}
|
Adding control to a location on a tabpage which has a scrollbar
I have a TabPage with a number of different slider controls on it (some custom range slider controls some normal TrackBar controls). When the user ticks or de-ticks certain checkboxes it deletes all the controls and re-constructs them again (according to what is required - a amount of range sliders and b amount of Trackbars).
I have a problem though, because the TabPage has a vertical scrollbar, it takes the initial x,y location to be 0,0 at the point where the user has scrolled to. So if the user scrolls down, ticks a box all the controls get located at lower points than where they should be.
Is there a way to change the initial location points to the actual tab page 0,0?
Or is there a way to change a control (which has the same properties) to another control type instead of delete and add one?
|
To answer my own question, I saved the current locations of the current controls and used that to reconstruct the new controls.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": ".net 4.0, c# 4.0, controls, location, tabpage"
}
|
Is there any reason why "inner-flange" style trains are almost universal?
There's basically two ways train wheels can operate, the flanges could be either "inner" or "outer".
](
Is there a technical reason that makes the "inner" style preferable ?
|
If you leave off the flanges and just use cones that are solidly connected to an axle, then cones that taper outward (get _smaller_ as they go out) tend to be self-centering but undamped (or underdamped, I'm not sure which).
This is because if the axle is offset, the wheel that's to the outside has a larger diameter, and tends to drive the axle to turn toward the center. The "outer flange" design you should would do the opposite.
So the "inner flange" picture that you present is mostly not relying on the flanges to keep the axle centered -- it's the taper of the wheels that does that. The flange is there to damp oscillations, and for when the system is overwhelmed by circumstances.
(There's a nice video of this on YouTube, but I'm too lazy right now to find it -- try searching on "train tire design", or maybe those words with the word "stability" tossed in).
|
stackexchange-engineering
|
{
"answer_score": 7,
"question_score": 4,
"tags": "mechanical engineering, rail, transportation"
}
|
Fixing divs with position
How to set which div is over another by position fixed? If I have 3 divs and page is separated with those 3 divs I want to make them all fixed but I one left and right be over the center one I have photo example with two but it same question. Example one Example two With example one when I put img from behind as fixed img over message div...
|
Try giving them z-indexes.
Just add `z-index: (some number)`.
The element with a bigger index will be in front.
Documentation.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css"
}
|
How to "decrypt" linker method names?
I'm using backtrace to print application's stack trace and I'm getting something like
libQtCore.so.4(_ZN11QMetaObject8activateEP7QObjectPKS_iPPv+0x843) [0x7f889d20cf33]
libQtGui.so.4(_ZN7QAction9triggeredEb+0x32) [0x7f889d76c2f2]
libQtGui.so.4(_ZN7QAction8activateENS_11ActionEventE+0xb0) [0x7f889d76d670]
libQtGui.so.4(+0x6242f4) [0x7f889db862f4]
Is there any way to convert "linker-names" to "source-names" and get code line numbers from offsets?
I want to have backtrace, looking like this:
libQtCore.so.4 (QMetaObject::activate(QObject):1022)
libQtGui.so.4 (QAction::triggered()::47)
UPD.
I understand, this technique may work or not work or work bad because of compiler specifics. I want to "demangle" linker symbols at least in gcc and visual c++.
|
* Under gcc you can use **c++filt** to decipher the mangling.
* Under Visual studio you can **undname**
Once you have the function name you at least on Windows you can use **DIA SDK** to get the source file line numbers etc
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "c++, debugging, backtrace"
}
|
Find the gcd and write it a linear combination
$$24,-11$$
So we begin with $gcd(24,-11)$
$$24=-2*-11+2=gcd(-11,2)$$
$$-11=-6*2+1=gcd(2,1)=1$$
So $gcd(24,-11)=1$ now how do I find x,y such that $1=24x-11y$?
|
Easier than back-substitution is too keep track of the linear relations from the start
$$\begin{align} 24 &= \ \ 1(24)+0(11)\\\ 11 &=\ \ 0(24)+1(11)\\\ 2 &=\ \ 1(24)-2(11)\ \ =\ \rm row_1 - 2\cdot row_2\\\ 1 &=\\! -5(24)\\!+\\!11(11)\, = \ \rm row_2 - 5\cdot row_3 \end{align}$$
i.e. we perform the Euclidean algorithm on the LHS _and_ in parallel on the RHS.
See this answer for much more on this version of the extended Euclidean algorithm.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "elementary number theory"
}
|
Add HTML in ItemTemplate from a code behind
I have a repeater control that lists 10 records from a database. What I want to do is to divide that 10 records in two columns, and I don't know how to do that.
The problem is that I can't use <%# if (Container.ItemIndex == 0) %>.
I tried to use ItemDataBound to manipulate the data, but I don't know how to make repeater control to display generated data back to the browser.
Any help or idea will do.
Hope you understood what I was going to say.
Thanks.
|
<asp:Repeater runat="server">
<ItemTemplate>
<div class="<%# Container.ItemIndex % 2 == 0 ? "left" : "right"%>">
<%# Eval("data") %>
</div>
</ItemTemplate>
</asp:Repeater>
Will output:
<div class="left">...</div><div class="right">...</div>
<div class="left">...</div><div class="right">...</div>
<div class="left">...</div>
Now all you need is some CSS (this is obviously just simplified example):
.left {float:left;width:50%;}
.right {float:right;width:50%;}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net"
}
|
Parsing JSON with paragraph breaks in Swift 4
My app grabs a JSON and then parses it to populate the UITableView and the detail view data. One of these fields is designed to contain descriptions, and many of them include paragraph breaks. How should I encode the JSON to include paragraph breaks?
(I am creating the JSON, so I can enter whatever into the JSON file. I'm hoping that there is a way to enter it in JSON that will be processed automatically via the Swift 4 JSONDecoder() method).
|
You can represent newline symbols with escaped character `\\n`. Here's an example of decoding such string:
struct Entity: Codable {
var title: String
var desc: String
}
let testJson = """
{
"title": "Title",
"desc": "first row,\\nsecond row,\\n\\nthird row"
}
"""
let testData = testJson.data(using: .utf8)!
do {
let entity = try JSONDecoder().decode(Entity.self, from: testData)
print(entity)
} catch {
print(error)
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "ios, json, swift"
}
|
Minimum of a function given norm and scalar product in $L_2$
This is a problem I encountered at a math competition for Master's students today, and so far nobody I know has any idea how to approach it. Decided I wanted to share it because I find it completely unobvious that the given constraints are enough to arrive at the answer.
Given $f\in C[-2,1]$ such that $\int\limits_{-2}^1f^2(x)dx=84,\ \int\limits_{-2}^1f(x)(2-x)dx=42$ find $\min\limits_{-2\leqslant x\leqslant 1} (x^2-f(x))$.
|
Well, let $g(x)=2-x$ and note that
$$ \|g\|_{L^2}^2=\int_{-2}^1 (2-x)^2\textrm{d}x=\int_{-2}^1 4+x^2-4x\textrm{d}x=12+\frac{1+8}{3}-2(1-4)=21 $$ Now, applying the Cauchy-Schwarz inequality, we see that $$ 42=|\langle f,g\rangle|\leq \|f\|_{L^2}\|g\|_{L^2}=\sqrt{84\cdot21}=\sqrt{2\cdot 42\cdot \frac{1}{2}\cdot 42}=42 $$ We only have equality in the Cauchy-Schwarz inequality if $f=\alpha g$ almost surely for some appropriate $\alpha\in \mathbb{C}$. Thus, $$ 42=\langle f,g\rangle=\alpha \|g\|_{L^2}^2, $$ so $\alpha=2$. Now, $f$ is assumed continuous, so $f(x)=2g(x)$ for every $x$. Now, it is completely elementary to see that \begin{align} (x^2-f(x))'&=2(x+1)\\\ (x^2-f(x))''&= 2, \end{align} so $x^2-f$ is convex and attains its minimum at $x=-1,$ so $$\min_{-2\leq x\leq 1} x^2-f(x)=(-1)^2-f(-1)=1-6=-5$$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 3,
"tags": "real analysis, optimization"
}
|
How to suppress error in get_headers() without using @
`get_headers()` throws a warning if the URL being checked is invalid. E.g.,
`get_headers('
> Warning: get_headers(): php_network_getaddresses: getaddrinfo failed: No such host is known
Is it possible to suppress this error withou using `@`?
My main goal is to check whether a URL exist or not but I don't want to use the `@` suppressor.
|
You can check with curl and it's not returning any warnings. If you use 'CURLOPT_NOBODY' then it will not try to download whole page.
<?php
$url = "
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
if ($result !== false) {
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 404) {
echo "URL Not Exists";
} else {
echo "URL Exists";
}
} else {
echo "URL not Exists";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php"
}
|
how to iterate over list of lists in scala
I want to iterate over a `list[List[String]]` to subset it into a `list[String]` and then store each list from the list of lists in a `val`. The val's name could be anything but it should include each list index in its name.
For example:
val x: List[ List[String]] = List(List("Nike","Apple"), List("James", "Mike"))
Desired output:
group_0 : List[String] = List(Nike, Apple)
group_1 = List[String] = List(James, Mike)
|
Use `zipWithIndex` and convert into `Map[String, List[String]]`. Each `key` will be of form `group_0`, `group_1` etc
val map = x.zipWithIndex.map(x => s"group_${x._2}" -> x._1).toMap
Access each list using key
map("group_0")
# Scala REPL
scala> x.zipWithIndex.map(x => s"group_${x._2}" -> x._1).toMap
res4: scala.collection.immutable.Map[String,List[String]] = Map(group_0 -> List(Nike, Apple), group_1 -> List(James, Mike))
scala> res4("group_0")
res6: List[String] = List(Nike, Apple)
scala> res4("group_1")
res7: List[String] = List(James, Mike)
@Manoj Kumar Dhakd idea to use `toMap` is better
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "scala"
}
|
Define a function for countdown skip numbers
def count_down_skip(start, skip=0):
"""
Counting down a sequence with a skip value,
from a defined start point in reversed order.
Args:
start: start loop index.
skip: number to skip over.
Returns:
(list): skipped list.
"""
return [num for num in reversed(range(start + 1)) if num != skip]
print("... ".join(map(str, count_down_skip(10,1))) + "!")
this code can output 10 to 0 and without 1 while if 10 to 0 without 1 4 3 (skip these numbers), then how can I do? I tried change the print :
print("... ".join(map(str, count_down_skip(10,1,4,3))) + "!")
but error happened...
define a function for countdown numbers in python
|
Best Solution is,
def count_down_skip(start, *skip):
return [num for num in reversed(range(start + 1)) if num not in skip]
print("... ".join(map(str, count_down_skip(10,1,4,3))) + "!")
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, function"
}
|
How safe is front end with react and redux?
I am wondering this for a while now when I am building react and redux applications. How easy is it for a person to change the redux and/or react state manually? I can't find documentation on this anywhere and would love to know the security issues etc.
**Example of a redux state**
{
firstName: 'Foo',
lastName: 'Bar',
permissions: {
'admin': false
}
}
Would they be able to change or influence something like the `admin` permission and set it to `true`?
And if they can change it, would it be accepted by reducers etc?
|
The frontend is inherently insecure. I can inject my own code any time. Setup breakpoints and manipulate variables during runtime. With that in mind. I could put anything I wanted in a redux store and get any value out of it. This includes setting an `admin` permission/flag to `true`. I could also trigger the reducers to run with the new value.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 7,
"tags": "security, reactjs, redux, react redux"
}
|
The same web part (.wsp) for MOSS 2007 and SP 2010?
Is it possible to have the same web part (.wsp) for both (MOSS 2007 & SP 2010)?
Assume that I want to develop a simple web part, and I want to deploy it on MOSS 2007 and also on SP 2010? So, is this possible? Or are there any issues?
I would greatly appreciate if you explain to me.
|
No problem. You may need to update your installation script though. For details see the series on Porting a SharePoint 2007 WSPBuilder solution to SharePoint 2010.
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 4,
"tags": "2007, web part"
}
|
Autowiring and Dependency Injection
How Request like object are passed in action of controller. Is it some sort of autowiring?
class DefaultController {
public function createAction(Request $request){
}
}
|
This line of code explains how the request object is passed to a controller method:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "symfony"
}
|
Can I overload methods in PHP?
Example:
I want to have two different constructors, and I don't want to use func_get_arg(), because then it's invisible what args are possible.
Is it legal to write two of them, like:
class MyClass {
public function __construct() {
// do something
}
public function __construct(array $arg) {
// do something
}
}
?
|
No, but you can do this:
class MyClass {
public function __construct($arg = null) {
if(is_array($arg)) {
// do something with the array
} else {
// do something else
}
}
}
In PHP, a function can receive any number of arguments, and they don't have to be defined if you give them a default value. This is how you can 'fake' function overloading and allow access to functions with different arguments.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 3,
"tags": "php, oop"
}
|
Is it possible to write to internal storage from my application?
I want to make an Android application which has both an APK and OBB file inside its own resources. The main point is to create a new folder in Android - obb of the internal storage, and then copy the OBB file from the resources to the newly created folder.
Is this possible, or does Android restrict write access to the internal memory? A yes or no would do, that would greatly help. I have read so many different answers, some say that it is only possible to write to external storage (SD-card).
If it is not possible, is there another way I can do this? The purpose is to automate the process for people who do not know how to properly move an OBB file to Android - obb for a game to work.
|
> I want to make an Android application which has both an APK and OBB file inside its own resources
This is the tricky part. Probably the answers here can help.
Regarding whether your application can write to internal or external storage. The answer is yes. Check the documentation on how to go about it. Since you need to write to Android obb folder which is in external storage, you would need to request for storage permissions from user.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, file, storage, internal"
}
|
Inner join within update statement in PostgreSQL
I have table called temp_table which consist of following rows:
cola colb result
----------------
p4 s1 0
p8 s1 0
p9 s1 0
p5 f1 0
p8 f1 0
Now I need to update result column with the count(*) of colb. For which i am trying the following query:
update tem_table
set result = x.result
from tem_table tt
inner join(select colb,count(*) as result from tem_table group by colb) x
on x.colb = tt.colb;
And selecting distinct colb and result from temp_table:
select distinct colb,result from tem_table;
Getting output:
colb result
-----------
s1 3
f1 3
But the expected output is:
colb result
-----------
s1 3
f1 2
I am not getting where I am getting wrong in my query? Please help me.Thanks
|
You should not repeat the table to be updated in the `from` clause. This will create a cartesian self join.
Quote from the manual:
> _Note that the target table **must not appear in the from_list** , unless you intend a self-join (in which case it must appear with an alias in the from_list)_
(Emphasis mine)
Unfortunately `UPDATE` does not support explicit joins using the `JOIN` keyword. Something like this should work:
update tem_table
set result = x.result
from (
select colb,count(*) as result
from tem_table
group by colb
) x
where x.colb = tem_table.colb;
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 7,
"tags": "postgresql"
}
|
Is every compact hypersurface contained in a sphere which it touches twice?
Let $M\subset \mathbb{R}^{n+1}$ be a compact $n$-manifold. There exists, then, a smallest $n$-sphere containing $M$, and it must touch it in one point.
Must it touch it twice?
This seems quite intuitively right to me, but I've no idea how to prove it. It's easy to construct counterexamples where you can't have more than 2 (e.g. an ellipse which is not a circle).
|
Yes. If not, let a smallest sphere containing $M$ touch $M$ at only $P$ and have center $O$. The sphere can be divided into two hemispheres one of which, the northern, say, has $P$ as north pole. The closed southern hemisphere, $S$, does not intersect $M$ so $\epsilon:=d(S,M)>0$. Translate the sphere $\epsilon/2$ in the direction $OP$. The translate of $S$ is still distance $\epsilon/2$ or more away from $M$, so it does not intersect $M$. The translate of the closed northern hemisphere is contained in the region formerly outside the sphere, so it does not intersect $M$ either. Therefore the translated sphere is not smallest, so neither was the original sphere.
|
stackexchange-math
|
{
"answer_score": 9,
"question_score": 12,
"tags": "differential geometry"
}
|
Unbiased estimator of $\mu\ 'S^{-1} \mu$
> $\vec X_1,\cdots ,\vec X_n$ are **iid** $N_2(\mu,\Sigma)$. Find an _unbiased estimator_ of $\mu\ 'S^{-1} \mu$ as a linear function of its _mle_.
My work:
MLE is $\bar X\ 'S^{-1} \bar X$
Now
$$E(\bar X\ 'S^{-1} \bar X)=E(tr(\bar X\ 'S^{-1} \bar X))\\\=tr(E(\bar X\ 'S^{-1} \bar X))\\\=tr(E(S^{-1}\bar X\ '\bar X))\\\=tr(E(S^{-1})E(\bar X\ '\bar X))$$
The last equation is because of the fact that $S$ and $\bar X\ ' \bar X$ are known to be independent.
I know $E(\bar X\ '\bar X)={\Sigma\over n}+\mu'\mu$
But I am not being able to find $E(S^{-1})$. Can someone help me proceed?
|
$S$, properly scaled, is a Wishart matrix. Inverse of a Wishart matrix can be easily computed by going through any standard reference on multivariate statistics.
Alternative easier solution: Recall that mle of $\mu'\Sigma^{-1}\mu$ is $\overline{X}'S^{-1}\overline{X}$ which, after proper scaling, has a $T^2$ distribution, which in turn is an $F$. Expectation of an $F$ s something you can know. Or if you want, write $F=cA/B$ where $A,B$ are independent $\chi$-squared, $c$ is a constant then find $E(F)=cE(A)E(1/B)$. $E(A)$ is straightforward, while $E(1/B)$ has to be computed by finding pdf of $B$, keeping in mind $B$ is chi squared.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "statistics, expectation, parameter estimation"
}
|
Google beta testing: I am not able to see CURRENT/TOTAL INSTALLS for my App at Developers console
Google beta testing: I am not able to see CURRENT/TOTAL INSTALLS for my App at Developers console, though couple of users have already installed the App on their phones for more than 24 hours now.
|
The install/uninstall stats are updated only once a day. Wait for another few hours and it should be there.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "android, console application, beta testing"
}
|
Compute: Warn when low-order truncation occurs
I have a result field specified as
01 MY-RESULT VALUE +0 USAGE COMP-3 PIC S9(13)V99
Imagine I multiply two factors:
COMPUTE MY-RESULT = A * B
What is the best way to detect low-order truncation in `MY-RESULT`? E.g. when `A=B=2.01`.
The `ON SIZE ERROR`clause is not triggered.
|
Something that will work with all vendors and even the oldest compilers (as you did not specified any dialect the seems to be the most important part): if it matters use an additional target field with more decimal positions and check for equality afterwards:
COMPUTE MY-RESULT RESULT-WITH-MORE-DECIMALS = A * B
IF MY-RESULT NOT = RESULT-WITH-MORE DECIMALS
...
END-IF
`ON SIZE ERROR` will _only_ be tracked for the upper truncation.
If this 2014 feature os available for your compiler you could use the `INTERMEDIATE ROUNDING IS PROHIBITED` (the draft had it in as `ROUNDED-MODE PROHIBITED`) which will show you this problem (if `EC-SIZE-TRUNCATION` exception is enabled). Beware of one part: this is an exception with a "fatal" category...
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "cobol"
}
|
ignore parameter in parent css
I'm working on a child theme for wordpress. I need to show a searchbox near the bottom of the header, instead of in the top.
So I need to replace the
#searchform {
top: 2.8em;
in the parent theme, with a
bottom: 2em;
In the child. Is it possibile to do that? (instead of doing top: "total height-2em")
|
Put in your child theme:
#searchform {
top: auto;
bottom: 2em;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, import, parent"
}
|
How to get index of dictionary from an array of dictionary?
I have an array of dictionaries:
var array = [["txt":"5mbps", "value": 2048],["txt":"50mbps", "value": 18048],["txt":"55mbps", "value": 22048]]
here, I want to get the _value_ from that index of dictionaries, which _txt_ is being selected. If I select 50mbps, how can i get that index and display the _value_ of the same index . \- Swift
|
Maybe better use array of tuples
var array: [(txt: String, value: Int)] = [
("5mbps", 2048),
("50mbps", 18048),
("55mbps", 22048)
]
Swift 2.3
array.filter { element in
return element.txt == findingText
}.first?.value
Swift 3
array.first { element in
return element.txt == findingText
}?.value
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "arrays, swift, dictionary"
}
|
How do I delete an object, when something hits it?
This was in reference to a game I was creating. It's a simple game where if the ball hits the block, the block should disappear. If I did something like this:
class Block:
def __init__(self,canvas,color):
self.canvas = canvas
self.id = canvas.create_rectangle(10,10,110,20,fill=color )
and then:
def hit_block(self,pos):
block_pos = self.canvas.coords(self.block.id)
List = [block_pos]
for i in List:
if pos[0] >= i[0] and pos[2] <= i[2]:
if pos[1] >= i[1] and pos[1] <= i[3]:
canvas.delete(block.id)
self.score()
global a
a += 1
return True
return False
The block doesn't get deleted. So what do you have to do to delete the block when the ball hits it?
Thanks!
|
`canvas.delete(block.id)` absolutely will work if `block.id` is a valid id that represents an object on the canvas. If it's not working, than `block.id` likely isn't what you think it is.
The problem in your code is that you were using `canvas.delete` rather than `self.canvas.delete`, and `block.id` rather than `self.block.id`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python, tkinter"
}
|
PHP Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
I have this error on line 28 which is below.
private loadText() { $this->text = $wiki->getpage($this->page);}
The surrounding code can be seen below
public function parse() { $this->parser = new parser($page,$this->getText()); $this->parser->parse();}
// private functions
private loadText() { $this->text = $wiki->getpage($this->page);}
private parseNamespace(){...
I have can't see the problem and my only guess is that it is something to do with $this->
|
Your forgot `function` after _every_ `private`-keyword. Interestingly you did it right for the one `public` method.
|
stackexchange-stackoverflow
|
{
"answer_score": 19,
"question_score": 2,
"tags": "php"
}
|
Antique expressions "tourmenteroit" and "à-peu-près"
I am trying to figure out what is meant by some antiquated expressions found in Mme. Motteville's memoirs, the phrase:
> Laffemas avoit promis au Ministre qu'il le **tourmenteroit** si bien qu'il en tireroit **à-peu-près** ce qu'il en désiroit savoir, & que sur peu de mal il trouveroit les moyens de lui faire son procès...
What is she saying here? To answer any questions about transcription, here is an image of the printed page (1750):

image_link_1 = 'â\x80¦IMAGEâ\x80¦'
image_link_2 = 'IMAGE'
def remove_image(text):
remove_im = ''.join([i for i in text if i not in image_link_1 and image_link_2])
return remove_im
df['title_and_abstract'] = df['title_and_abstract'].apply(lambda x: remove_image(x))
The problem is , that the function removes the first letter of some string. Espcially it seems that the function removes capital letter only. Weird.
Here´s an example
> 'This is an example string. Here is the IMAGE.'
after the function is used:
>
> 'his is an example string. Here is the .'
>
I realy dont get why this function does that.
Thank you in advance!
|
Im also a fresh Python diciple, thats why i want to explain the answer in my own thoughts that might help people who watch the thread in the future.
As the previous answer correctly said, the original funtction only iterated over single chars (I,M,A,G,E) and not over words (IMAGE). This lead also to the removal of all single chars defined in image_link_1 & 2.
text.split() takes care of that problem since the orginial string is splitted into words not chars.
The working code:
def remove_link(text):
remove_im = ' '.join([i for i in text.split() if i not in [image_link_1, image_link_2]])
return remove_im
df['title_and_abstract'] = df['title_and_abstract'].apply(lambda x: remove_link(x))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, data cleaning"
}
|
How to get the position of the last match of a regex?
I have a regex that matches numbers and I want to get the position of the last-matching number.
This is what I got right now:
def find_last_match_pos(pattern, s):
match = None
for match in re.finditer(pattern, s):
pass
return match.start() if match else -1
Can anyone think of a more pythonic way to do it?
|
Why not just use findall?
s.rfind(re.findall(pattern, s)[-1])
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, regex"
}
|
Vim readfile() not working
It seems that I can't use `readfile()` in vim to open anything.
For instance running
let m = readfile('~/.vimrc')
Will throw an error.
E484: Can't open file ~/.vimrc
Is there any configuration that might obstruct readfile from working?
Here is my `.vimrc`, I am using (Mac)Vim 7.4
<
|
Vim doesn't expand shell patterns in strings by default; you need to use the `glob()`) function:
let m = readfile(glob('~/.vimrc'))
Or just use the full path:
let m = readfile('/home/martin/.vimrc')
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "vim, macvim"
}
|
3 div independently relative and top aligned
How to (top) align 3 div that should be relative to a previous div (but not between them)?
I can't use floats or `position:inline-block` (if you set `display:none` on 2 divs the last one shouldn't move).
`position:absolute` neither because there's a relative footer underneath.
`vertical-align:top` doesn't work using spans - any workaround?
I tried using a wrapper but it can't work cause the height of the divs is not fixed.
The height of the wrapper gets completely ignored anyway (by the following footer) unless Im using relative children.
Any ideas?
|
**HTML**
the order is important and the wrapper is optional (to position the side divs)
<div id="wrapper">
<div id="left"></div>
<div id="right"></div>
<div id="middle"></div>
</div>
<div id="footer"></div>
**CSS**
#left {float:left}
#middle {margin:0 auto}
#right {float:right}
#footer {clear:both}
unless someone comes up with something easier ill accept my answer in 24h
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "css, cross browser, alignment"
}
|
delete all documents with doc Id in subcollection across the root collection
I have the following structure
(Employees) -> emailId -> (lists) -> listId .... then all fields
Basically if I need to get all the lists that employees have then I can simply go by the email Id and access all the documents under lists.
Employees can belong to the same list
Now the issue is if a list needs to be deleted. Is there a "query" that I can do to delete listId from all documents with the intended listId from all employees.
If not how would this structure be changed accordingly?
The backup option is have another root collection which has the listId and all its employees. In this case I need to do like 40 deletes (every employee I have to access indivudally to delete the list).
I hope there is a cleaner solution
Thank you
|
It requires one query for each separate collection (or subcollection, it doesn't matter) that you want to read or write in some way. You cannot affect or aggregate across collections in any way.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "android, firebase, google cloud firestore"
}
|
How to input external file in figure caption with tufte-latex?
With the tufte-handout class, I want to insert some text in a figure caption, from an external text file generated with R.
\documentclass[a4paper]{tufte-handout}
\newcommand\nlikely{\input{myvariable.txt}}
\begin{document}
N Likely = \nlikely
\begin{figure*}[h]
\centering
\includegraphics[width=\textwidth]{amce-likely.pdf}
\caption{N Likely = \nlikely}
\label{fig:amce-likely}
\end{figure*}
\end{document}
I can use the command \nlikely without any problem in the text, but when I try to use it in the figure caption I get an error:
Argument of \@iiminipage has an extra }
What's baffling me is that when I define \nlikely manually at the beginning of the document, no problem:
\newcommand\nlikely{190}
Is there a proper way to do this? Is \input inserting weird stuff that breaks the caption?
|
Welcome! I had to fiddle a bit to reproduce the error. I hope I got an appropriate example in the end.
If so, you just need a `\protect`:
\documentclass[a4paper]{tufte-handout}
\usepackage[demo]{graphicx}
\newcommand\nlikely{\input{myvariable.txt}}
\begin{document}
N Likely = \nlikely
\begin{figure*}[h]
\centering
\includegraphics[width=\textwidth]{amce-likely.pdf}
\caption{N Likely = \protect\nlikely}
\label{fig:amce-likely}
\end{figure*}
\end{document}
. On Tuesday, one of the partners leaves the partnership and is replaced by a new partner. On Wednesday, the victim of Monday's tort wants to sue.
Who do they sue? Is it the people who were partners on Monday, or the people who are now partners on Wednesday?
The jurisdiction is Victoria, Australia but the answer in any common law jurisdiction is of interest.
|
Partners are jointly and severally liable for acts and omissions of each partner committed _while_ they _are_ partners.
For a point in time event like you propose, only those who were partners at the time are liable. However, for the specific example (assault), _none_ of the other partners are liable as it is clear the tortfeasor is on a "frolic of his/her own" and the act is not that if the partnership.
For more protracted events, like a contract or negligence, both the outgoing and incoming partners may be liable.
|
stackexchange-law
|
{
"answer_score": 1,
"question_score": 0,
"tags": "australia, partnership"
}
|
Oshitaoshi ukemi name
I am looking for the Japanese (or western) name of the breakfall uke does to escape from oshitaoshi. Basically, this is a half cart wheel that uke does when tori applies oshitaoshi.
In the drawing below, steps 7-9 are the break fall although in this illustration, uke's feet do not rise as much as we do -- probably because the drawing are done from a more static/slow technique instead of the explosive power we tend to use...
!Oshitaoshi
|
In aikido, this is apparently called a "katate (single-handed) sokuten (cartwheel)" ukemi.
Reference: <
Also, in Bujinkan ninjutsu, they refer to this as a "katate oten" ukemi.
Reference: <
There may be other names for it as well, depending on the martial art.
|
stackexchange-martialarts
|
{
"answer_score": 2,
"question_score": 6,
"tags": "aikido, falling"
}
|
Are double splats treated differently in methods?
When I used a double splat for a method, I'm not allowed to define a variable with a type within the method:
def show(**attrs)
place : String = "w"
puts place
end
show(name: "Bobby") # This works.
show(name: "Bobby", place: "World") # This fails:
#
#in tmp.cr:2: variable 'place' already declared
#
# place : String = "w"
# ^~~~~
Is this the expected behaviour when using double splats? I couldn't find anything in the Crystal Book about this: <
|
This is a bug, please report it as such.
Note that declaring local variables with a type is not a recommended practice. Because it was a recent addition, it is not well tested and apparently prone to bugs.
You can see that this works, anyway:
def show(**attrs)
place = "w"
puts place
puts attrs[:place]
end
show(name: "Bobby", place: "World")
w
World
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "crystal lang"
}
|
iOS - Crash on [self.navigationController setToolbarHidden:YES animated:NO] Deallocated error
I have a crash on `[self.navigationController setToolbarHidden:NO animated:YES]` located in my viewWillAppear when I come back to the UIViewController using that toolbar. With this Error `*** -[CALayer retain]: Message sent to deallocated instace 0x5d0e0a0` I am not expressly releasing the toolbar but the class where I am setting it is autoreleased.
Also am I incorrect in assuming that the toolbar is on the navigationController?
|
There was a cheap and easy way to get this to work.
[self.navigationController.toolbar init];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios, ipad, uinavigationcontroller, toolbar"
}
|
Remove or empty content of elements
I have some HTML like this:
<div>TEXT
<span>SPAN</span>
<a href="">LINK</a>
</div>
I would like to remove the contents of the elements, usually I would do something like this:
$('*').empty();
or
$('*').contents().empty();
This however will remove/empty the first span and its content which is the div and link. What can I do to preserve the elements while emptying them? So the end result would be:
<span>
<div></div>
<a href=""></a>
</span>
Please note I'm looking for something 'universal' that can be applied to any HTML. The above is just an example, in reality the HTML structure would contain more data.
Example at JsFiddle
|
Recursively loop through all nodes, and remove all children whose `nodeType` property equals 3 (`Node.TEXT_NODE`). jQuery cannot select just text nodes, so this can be done using vanilla JavaScript.
Example:
function removeText(node) {
if (!node || !node.childNodes || !node.childNodes.length) return;
for (var i=node.childNodes.length-1; i>=0; --i) {
var childNode = node.childNodes[i];
if (childNode.nodeType === 3) node.removeChild(childNode);
else if (childNode.nodeType === 1) removeText(childNode);
}
}
Or, packed in a jQuery plugin:
$.fn.removeText = function() {
for (var i=this.length-1; i>=0; --i) removeText(this[i]);
return this;
};
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 6,
"tags": "jquery"
}
|
Covnerting PDF's to TBitmap image
what is the easiest method to convert a PDF into a TBitmap image in delphi? if there are any commercial available tools for delphi, I can buy one if it is reliable and or not expensive...
I am thinking of some kind of viewer which I can browse pages.. zoom... and export in the desired resolution..
|
I have had good results with QuickPDF. It's relatively inexpensive and there is a trial version available.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "delphi, delphi 7"
}
|
Will these two SQL statements always return the same data in Oracle?
I'm looking to remove the NVL function in a query as the query runs much faster without it. I'm sure something is going on in my execution plan that could be better but this appears to be potentially better sql that produces the same results. The larger query is more complex but here is basically how I'm looking to update the where clause. Will this be a good replacement? If not, why not and what would be better?
Current SQL (With NVL):
SELECT *
FROM oe_order_lines_all ol
WHERE NVL(OL.LINK_TO_LINE_ID, OL.LINE_ID) = OL.LINE_ID
Replacement SQL:
SELECT *
FROM oe_order_lines_all ol
WHERE (OL.LINK_TO_LINE_ID IS NULL OR OL.LINK_TO_LINE_ID = OL.LINE_ID)
|
Yes, these two queries are functionally equivalent, provided OL.LINE_ID is itself never NULL, which is _probably_ a good assumption...
Break it down like this to prove it:
SELECT *
FROM oe_order_lines_all ol
WHERE NVL(OL.LINK_TO_LINE_ID, OL.LINE_ID) = OL.LINE_ID
is the same as
SELECT *
FROM oe_order_lines_all ol
WHERE OL.LINK_TO_LINE_ID = OL.LINE_ID
OR OL.LINK_TO_LINE_ID IS NULL AND OL.LINE_ID = OL.LINE_ID
but since OL.LINE_ID = OL.LINE_ID when OL.LINE_ID is not NULL, that simplifies to your second query:
SELECT *
FROM oe_order_lines_all ol
WHERE OL.LINK_TO_LINE_ID = OL.LINE_ID
OR OL.LINK_TO_LINE_ID IS NULL
of course, if OL.LINE_ID is NULL when OL.LINK_TO_LINE_ID IS NULL, then OL.LINE_ID is not equal to OL.LINE_ID, and you could have different results.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "sql, oracle"
}
|
Cloning existing map to another container using OpenLayers?
I have a map created using OpenLayers 4 ,i want to take a print out of the map , before taking the print , i want to see its preview , So I need to clone the map to another container without making any problem with parent map , so i ve tried all these ,
let map2=this.createMapWithExistingView('previewmap',this.parentMap.getView());
createMapWithExistingView(t,v) {
let mapObj = new olMap({
layers: [
],
target: t,
controls: olControls.defaults({ attribution: false }),
interactions: [
new olDragPanInteraction(),
new olMouseWheelZoomInteraction(),
new dragrotateandzoom()
],
view:v
});
return mapObj;
}
but its not showing the map , only default zoom controls , when i clicked on zoom of preview map, zooming occurs on parent map.
|
You only sent view but not layers. You need to pass layers as well. Layers are empty so the map is empty.
let map2=this.createMapWithExistingView('previewmap', this.parentMap.getLayers(), this.parentMap.getView());
createMapWithExistingView(t, l, v) {
let mapObj = new ol.Map({
layers: l,
target: t,
controls: ol.Controls.defaults({
attribution: false
}),
interactions: [
new olDragPanInteraction(),
new olMouseWheelZoomInteraction(),
new dragrotateandzoom()
],
view: v
});
return mapObj;
}
fiddle: <
|
stackexchange-gis
|
{
"answer_score": 5,
"question_score": 1,
"tags": "openlayers"
}
|
How to put a program in system tray?
Is there a program for hiding programs from taskbar to system tray? I was hoping that Windows 7 will be able to do it itself but I can't find it.
|
## Tray It!
Tray It! is free and seems to work fine on Windows 7 32bit; there are some issues on Windows 7 64bit.
|
stackexchange-superuser
|
{
"answer_score": 8,
"question_score": 11,
"tags": "windows 7, taskbar, notification area"
}
|
Request Query String in Aspx.Page not working
Want to set query string value to hidden field in aspx page. My code is like below :
<asp:HiddenField runat="server" ID="hidden" Value='<%= Request.QueryString["id"]%>' />
Am aware this can be achieved using jquery/ Javascript & also server side programming. But wonder why it wont work. The value of hidden filed am getting is `<%= Request.QueryString["id"]%>` rather than the actual value.
|
The problem is that you cannot mix `runat=server` with `<%= %>`.
You can use: `<%# %>` syntax if you are in a databound control, or you can call `DataBind()` on the control from code-behind or inline server script.
<asp:HiddenField runat="server" ID="hidden" Value='<%# Request.QueryString["id"]%>' />
protected void Page_Load(object sender, EventArgs e)
{
hidden.DataBind();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, jquery, asp.net, hidden field"
}
|
Fetch information from DBPedia service
I am able to get a JSON version of dbpedia resource as below : <
But I am not able to parse it and pull desired result, Abstract and ICD code using JSON to Object method.
,'en')
VALUES ?name { 'Urinary incontinence' @en } }
This seems to be giving me the desired result.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, json, parsing, sparql, dbpedia"
}
|
Можно ли в объявлении функции использовать имена типов, отличные от таковых в определении?
То есть:
int area (int width, int lenght) //Определение
{
return lenght*width;
}
int area (int z, int y); //Объявление
И чем это чревато?
|
У Вас в примере не другие "имена типов", а просто имена переменных другие. На самом деле можно писать даже так
int area (int width, int lenght)
{
return lenght*width;
}
int area (int, int); // прототип
И это будет работать как ожидается.
А вот использовать другие "имена типов" уже нельзя. Либо не скомпилируется, либо будет работать не так как нужно (зависит от компилятора, но современные компиляторы обычно просто ругаются и не компилируют, если типы и порядок не совпадает).
То есть, вот так уже нельзя
int area (int width, int lenght)
{
return lenght*width;
}
int area (int width, string lenght); // прототип
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++"
}
|
What percent of corner kicks turn into goals?
I have looked around for this statistic without luck. I just wondered what percentage of corner kicks actually result in a goal? Not necessarily straight in, but from the same passage of play. I have seen answers (without any references) varying from 2.5% (feels too low) to 32% (surely way too high). Anyone know?
|
The percent of goals from corners is changing from league to league, for one competition to another and for one year to another. For example on 2010 World Cup 1 goal scored for every 70 corners taken,
but generally the ratio of corners to goals is almost **zero**.
Take a look at Ratio of Corners to Goal in the EPL !2010/11 Ratio of Corners to Goal in the EPL
You can see that Fulham who has the best ratio has 0.07 goals for corner.
The most extensive articles I came across it was: soccerbythenumbers and scienceofsocceronline
|
stackexchange-sports
|
{
"answer_score": 11,
"question_score": 21,
"tags": "football, statistics"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.