text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Maximum Q value for new state in Q-Learning never exists
I'm working on implementing a Q-Learning algorithm for a 2 player board game.
I encountered what I think may be a problem. When it comes time to update the Q value with the Bellman equation (above), the last part states that for the maximum expected reward, one must find the highest q value in the new state reached, s', after making action a.
However, it seems like the I never have q values for state s'. I suspect s' can only be reached from P2 making a move. It may be impossible for this state to be reached as a result of an action from P1. Therefore, the board state s' is never evaluated by P2, thus its Q values are never being computed.
I will try to paint a picture of what I mean. Assume P1 is a random player, and P2 is the learning agent.
P1 makes a random move, resulting in state s.
P2 evaluates board s, finds the best action and takes it, resulting in state s'. In the process of updating the Q value for the pair (s,a), it finds maxQ'(s', a) = 0, since the state hasn't been encountered yet.
From s', P1 again makes a random move.
As you can see, state s' is never encountered by P2, since it is a board state that appears only as a result of P2 making a move. Thus the last part of the equation will always result in 0 - current Q value.
Am I seeing this correctly? Does this affect the learning process? Any input would be appreciated.
Thanks.
A:
Your problem is with how you have defined $s'$.
The next state for an agent is not the state that the agent's action immediately puts the environment into. It is the state when it next takes an action. For some, more passive, environments, these are the same things. But for many environments they are not. For instance, a robot that is navigating a maze may take an action to move forward. The next state does not happen immediately at the point that it starts to take the action (when it would still be in the same position), but at a later time, after the action has been processed by the environment for a while (and the robot is in a new position), and the robot is ready to take another action.
So in your 2-player game example using regular Q learning, the next state $s'$ for P2 is not the state immediately after P2's move, but the state after P1 has also played its move in reaction. From P2's perspective, P1 is part of the environment and the situation is no different to having a stochastic environment.
Once you take this perspective on what $s'$ is, then Q learning will work as normal.
However, you should note that optimal behaviour against a specific opponent - such as a random opponent - is not the same as optimal play in a game. There are other ways to apply Reinforcement Learning ideas to 2-player games. Some of them can use the same approach as above - e.g. train two agents, one for P1 and one for P2, with each treating the other as if it were part of the environment. Others use different ways of reversing the view of the agent so that it can play versus itself more directly - in those cases you can treat each player's immediate output as $s'$, but you need to modify the learning agent. A simple modification to Q learning is to alternate between taking $\text{max}_{a'}$ and $\text{min}_{a'}$ depending on whose turn you are evaluating (and assuming P1's goal is to maximise their score while P2's goal is to minimise P1's score - and by extension maximise their own score in any zero-sum game)
| {
"pile_set_name": "StackExchange"
} |
Q:
why am I getting this error
Why Am I getting an error. In eclipse it says constructor call should be the first line. It is the first line. or you can not extend Main?
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//JLabel testLabel1 = new JLabel();
public Main(){
super("title bar");
}
}
}
A:
Your Main constructor should sit outside of the main method. Like so:
public class Main extends JFrame {
public Main() {
super("title bar");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//JLabel testLabel1 = new JLabel();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
VMs are not getting static IP from Vagrantfile
I'm beginner in networking stuff and also I'm just starting with VMs.
I'm doing examples from "Ansible for Devops" and in chapter 3, I'm supposed to create three VMs and set a private network with static ip.
My Vagrant file looks like that:
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "geerlingguy/centos7"
config.ssh.insert_key = false
config.vm.synced_folder ".", "/vagrant", disabled: true
config.vm.provider :virtualbox do |v|
v.memory = 256
v.linked_clone = true
end
config.vm.define "app1" do |app|
app.vm.hostname = "orc-app1.dev"
app.vm.network :private_network, ip: "192.168.60.4"
end
config.vm.define "app2" do |app|
app.vm.hostname = "orc-app2.dev"
app.vm.network :private_network, ip: "192.168.60.5"
end
config.vm.define "db" do |db|
db.vm.hostname = "orc-db.dev"
db.vm.network :private_network, ip: "192.168.60.6"
end
end
Vagrant loges:
❯ vagrant up
Bringing machine 'app1' up with 'virtualbox' provider...
Bringing machine 'app2' up with 'virtualbox' provider...
Bringing machine 'db' up with 'virtualbox' provider...
==> app1: Cloning VM...
==> app1: Matching MAC address for NAT networking...
==> app1: Checking if box 'geerlingguy/centos7' is up to date...
==> app1: Setting the name of the VM: 3_app1_1485309004899_30536
==> app1: Fixed port collision for 22 => 2222. Now on port 2202.
==> app1: Clearing any previously set network interfaces...
==> app1: Preparing network interfaces based on configuration...
app1: Adapter 1: nat
app1: Adapter 2: hostonly
==> app1: Forwarding ports...
app1: 22 (guest) => 2202 (host) (adapter 1)
==> app1: Running 'pre-boot' VM customizations...
==> app1: Booting VM...
==> app1: Waiting for machine to boot. This may take a few minutes...
app1: SSH address: 127.0.0.1:2202
app1: SSH username: vagrant
app1: SSH auth method: private key
app1: Warning: Remote connection disconnect. Retrying...
==> app1: Machine booted and ready!
==> app1: Checking for guest additions in VM...
==> app1: Setting hostname...
==> app1: Configuring and enabling network interfaces...
==> app2: Cloning VM...
==> app2: Matching MAC address for NAT networking...
==> app2: Checking if box 'geerlingguy/centos7' is up to date...
==> app2: Setting the name of the VM: 3_app2_1485309032690_32260
==> app2: Fixed port collision for 22 => 2222. Now on port 2203.
==> app2: Clearing any previously set network interfaces...
==> app2: Preparing network interfaces based on configuration...
app2: Adapter 1: nat
app2: Adapter 2: hostonly
==> app2: Forwarding ports...
app2: 22 (guest) => 2203 (host) (adapter 1)
==> app2: Running 'pre-boot' VM customizations...
==> app2: Booting VM...
==> app2: Waiting for machine to boot. This may take a few minutes...
app2: SSH address: 127.0.0.1:2203
app2: SSH username: vagrant
app2: SSH auth method: private key
app2: Warning: Remote connection disconnect. Retrying...
==> app2: Machine booted and ready!
==> app2: Checking for guest additions in VM...
==> app2: Setting hostname...
==> app2: Configuring and enabling network interfaces...
==> db: Cloning VM...
==> db: Matching MAC address for NAT networking...
==> db: Checking if box 'geerlingguy/centos7' is up to date...
==> db: Setting the name of the VM: 3_db_1485309060266_65663
==> db: Fixed port collision for 22 => 2222. Now on port 2204.
==> db: Clearing any previously set network interfaces...
==> db: Preparing network interfaces based on configuration...
db: Adapter 1: nat
db: Adapter 2: hostonly
==> db: Forwarding ports...
db: 22 (guest) => 2204 (host) (adapter 1)
==> db: Running 'pre-boot' VM customizations...
==> db: Booting VM...
==> db: Waiting for machine to boot. This may take a few minutes...
db: SSH address: 127.0.0.1:2204
db: SSH username: vagrant
db: SSH auth method: private key
db: Warning: Remote connection disconnect. Retrying...
==> db: Machine booted and ready!
==> db: Checking for guest additions in VM...
==> db: Setting hostname...
==> db: Configuring and enabling network interfaces...
And Vagrant SSH-config:
Host app1
HostName 127.0.0.1
User vagrant
Port 2202
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/mst/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
Host app2
HostName 127.0.0.1
User vagrant
Port 2203
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/mst/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
Host db
HostName 127.0.0.1
User vagrant
Port 2204
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/mst/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
So as You can see the machines didn't get those static ips I set for them and I can't connect to them using it. They just got a localhost IP and some high ports. In that example, I should work on that machines using ansible and use that static ips in the inventory file, so they should have it set correctly.
Any ideas?
macOS Sierra
Vagrant 1.9.1
VirtualBox 5.1.14
Thanks
EDIT: The machines are using CentOS and ip addr output is:
[root@orc-app1 vagrant]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 08:00:27:dd:23:fa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
valid_lft 86067sec preferred_lft 86067sec
inet6 fe80::a00:27ff:fedd:23fa/64 scope link
valid_lft forever preferred_lft forever
3: enp0s8: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast state DOWN qlen 1000
link/ether 08:00:27:4d:38:fc brd ff:ff:ff:ff:ff:ff
A:
Try with vagrant 1.9.0 . My co worker had an issue with it that nfs shares would not mount corectly if 1.9.1 and it related to the fact that the box didn't add one necessary interface automatically.
Downgrading to 1.9.0 fixed this.
There are couple of open issues on the vagrants github and they relate to rhel/centos 7 specifically.
This is one of them https://github.com/mitchellh/vagrant/issues/8138
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prove that the sum and product of algebraic integers is an algebraic integer?
I would like to understand why the sum and product of algebraic integers are algebraic integers.
For algebraic numbers (not integers) there is the wonderful website https://www.dpmms.cam.ac.uk/~wtg10/galois.html which uses only basic linear algebra.
A short version of that is in this MSE-answer: https://math.stackexchange.com/a/155153/564656
My Question:
Can this method or something similar be used for algebraic integers?
A:
Yes, the exact same proof (at least, the brief MSE version) shows that the sum/product of algebraic integers is algebraic.
As in the linked post, take $V = F[x,y]/(p(x),q(y))$. Verify that because $p$ is monic, the matrix of the operator $\alpha(x,y) \mapsto x\,\alpha(x,y)$ has integer coefficients. The same holds for $\alpha(x,y) \mapsto y\,\alpha(x,y)$.
Now, the sum/product of matrices with integer coefficients is also matrix with integer coefficients. So, the matrices associated with $x + y,xy$ have integer coefficients. By the Cayley Hamilton theorem, $x + y$ and $xy$ therefore satisfy a monic polynomial with integer coefficients.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why am I getting different output in my java program?
Why am I getting different output in my java program ?
output(what i am getting:)
0.0
0.0
They are equal
output(what it should be:)
91.95
45.975
78.25 is greater
public class myMain {
public static void main(String[] args) {
A v = new A();
v.set(13.7, 78.25);
v.add();
v.half();
v.max();
}
}
public class A {
private double D ,E;
public void set(double d, double e) {
d=D;
e=E;
}
public void add(){
System.out.println(D+E);
}
public void half(){
System.out.println((D+E)/2);
}
public void max(){
if(D>E)
System.out.println(D+" is greater");
else if(E>D)
System.out.println(E+" is greater");
else
System.out.println("They are equal");
}
}
What's wrong in the program?
A:
These are the wrong way around. Write this instead
D=d;
E=e;
The left hand side is the variable you want to change, and the right hand side is the expression you want it to have the result of.
| {
"pile_set_name": "StackExchange"
} |
Q:
Text Meta-label
I'm trying to reproduce the effect pictured here in LaTex. I would like to be able to label parts of a sentence to help my students with grammar.
Is something like this possible? I'm not aware of any packages that do this. {I wasn't sure what tag to give this; if tikz is wrong, please feel free to correct.}
Thanks for your help.
A:
This is not an ideal answer, but since I worked on it, I'll post it. (REVISED to provide two alternatives)
I took David's suggestion and reworked my answer from Rounded box around placeholder text that supports line breaking.
VERSION 1:
What are the drawbacks:
1) because of the way I continue the rule over spaces (using the length \afterspacelap), a negative side effect is that the overrule protrudes into the left margin for continued lines.
2) The label, passed as an argument, is \rlapped 2em to the right of the text marking. If there is not enough room, one can rekern to the left as I did with my "LINEBREAKING" label, but if that is not sufficient room, then there is no remedy.
3) The label does not break up the overline, as in the OP's photo, but only sits atop it.
The good news is that it does line break and paragraph break.
\documentclass{article}
\usepackage{censor}
\usepackage{stackengine}
\usepackage{xcolor}
\usepackage{scalerel}
\newlength\rlwd
\rlwd=.8pt
\makeatletter
\setstackgap{L}{9pt}
\def\stacktype{L}
\def\useanchorwidth{T}
\censorruledepth=\Lstackgap
\periodrlap=0pt\relax
\afterperiodlap=0pt\relax
\lletterlap=0pt\relax
\rletterlap=0pt\relax
\afterspacelap=1.0ex\relax
\renewcommand\censorrule[1]{%
\protect\textcolor{cyan}{\rule[\censorruledepth]{#1}{\rlwd}}%
}
\renewcommand\@cenword[1]{%
\setbox0=\hbox{#1}%
\stackon[0pt]{#1}{\censorrule{\wd0}}%
}
\def\censordot{\textcolor{cyan}{\rlap{\@cenword{\phantom{.}}}}.}
\def\endleft{\rule[\Lstackgap-3pt+.7\rlwd]{\rlwd}{3pt}}
\let\endright\endleft
\newcommand\marktext[2][]{%
\trlap[11pt]{\sffamily\bfseries\scriptsize\textcolor{cyan}{\hspace{2em}{\uppercase{#1}}}}%
\textcolor{cyan}{\llap{\smash{\endleft}}}%
\xblackout{#2}%
\textcolor{cyan}{\rlap{\smash{\endright}}}%
}
\makeatother
\parindent 0in
\parskip 1em
\begin{document}
This shows linebreaking capability: aaa aaa aaa aaa aaa aaa aaa
\marktext[\kern-13pt linebreaking]{bbb bbb bbb bbb. bbb bbb bbb bbb bbb bbb}
ccc ccc ccc ccc ccc ccc
Can this \marktext[phrase]{procedure go across paragraphs boundaries?
Why yes} it can.
But gaps can arise if glue is stretched too far.
\afterspacelap=1.7ex\relax
\marktext[sentences]{%
This tests marking a multiline block of text. This tests marking a multiline block of text.
This tests marking a multiline block of text. This tests marking a multiline block of text.
This tests marking a multiline block of text.}
\end{document}
VERSION 2:
This revised version has the virtue that it extends equally into both the left and right margins for wrapped lines, but it comes at a cost. The cost is that the leading and trailing ends of the blue overline are likewise extended by this amount,
\documentclass{article}
\usepackage{censor}
\usepackage{stackengine}
\usepackage{xcolor}
\usepackage{scalerel}
\newlength\rlwd
\rlwd=.8pt
\makeatletter
\setstackgap{L}{9pt}
\def\stacktype{L}
\def\useanchorwidth{T}
\censorruledepth=\Lstackgap
\periodrlap=.5ex\relax
\afterperiodlap=.5ex\relax
\lletterlap=.5ex\relax
\rletterlap=.5ex\relax
\afterspacelap=.5ex\relax
\renewcommand\censorrule[1]{%
\protect\textcolor{cyan}{\rule[\censorruledepth]{#1}{\rlwd}}%
}
\renewcommand\@cenword[1]{%
\setbox0=\hbox{#1}%
\stackon[0pt]{#1}{\censorrule{\wd0}}%
}
\def\censordot{\textcolor{cyan}{%
\rlap{\@cenword{\phantom{.\hspace{\periodrlap}}}}}.}
\def\endleft{\rule[\Lstackgap-3pt+.7\rlwd]{\rlwd}{3pt}}
\let\endright\endleft
\newcommand\marktext[2][]{%
\trlap[11pt]{\sffamily\bfseries\scriptsize\textcolor{cyan}{\hspace{2em}{\uppercase{#1}}}}%
\textcolor{cyan}{\llap{\smash{\endleft}\hspace{\lletterlap}}}%
\xblackout{#2}%
\textcolor{cyan}{\rlap{\hspace{\rletterlap}\smash{\endright}}}%
}
\makeatother
\parindent 0in
\parskip 1em
\begin{document}
This shows linebreaking capability: aaa aaa aaa aaa aaa aaa aaa
\marktext[\kern-13pt linebreaking]{bbb bbb bbb bbb. bbb bbb bbb bbb bbb bbb}
ccc ccc ccc ccc ccc ccc
Can this \marktext[phrase]{procedure go across paragraphs boundaries?
Why yes} it can.
But gaps can arise if glue is stretched too far.
\periodrlap=.8ex\relax
\afterperiodlap=.9ex\relax
\lletterlap=.8ex\relax
\rletterlap=.8ex\relax
\afterspacelap=.8ex\relax
\marktext[sentences]{%
This tests marking a multiline block of text. This tests marking a multiline block of text.
This tests marking a multiline block of text. This tests marking a multiline block of text.
This tests marking a multiline block of text.}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
MATLAB and Armadillo, hints on translating
i'm rewriting some Matlab code to c++ using armadillo, a libs for linear algebra. really good libs, IMHO. but i had to translate some matlab construct because armadillo isn't matlab.
i want to share my little snippet because i think there should be a better way (in terms of speed, mainly) to solve thoose little problems. i hope someone here could help me to improve my code!
static mat log(mat A) {
/*
* log function operates element-wise on matrix A
* MATLAB code> log(A)
*/
mat X(A);
mat::iterator a = X.begin();
mat::iterator b = X.end();
for(mat::iterator i=a; i!=b; ++i) {
(*i) = log(*i);
}
return X;
}
-
static mat vectorize(mat A) {
/*
* vectorise a matrix (ie. concatenate all the columns or rows)
* MATLAB code> A(:)
*/
mat B = mat(A);
B.reshape(B.n_rows*B.n_cols, 1);
return B;
}
-
static bool any(mat X, double n) {
/*
* check if there are some n in X
* MATLAB code> any(X==n)
* TODO: i'm not sure of description but it works for me
*/
uvec _s = find(, n);
if ( _s.is_empty() )
return true;
else
return false;
}
-
static double sum(mat X) {
/*
* sum a matrix
* MATLAB code> sum(X)
*/
return sum(sum(X))
}
-
static field<rowvec num2cell(mat X) {
/*
* converts matrix X into field by placing each row of X into a separate row
* this method assume that a cell is a field<rowvec>, mayebe a template should be used to generalize..
* MATLAB code> num2cell(X)
*/
field<rowvec> data1(X.n_rows,1);
for (uint r = 0; r < X.n_rows; ++r) {
data1(r,0) = X.row(r);
}
return data1;
}
A:
You're doing a copy in most of those snippets: if it was possible to do without a copy, it could be faster. Libraries such as Boost often offer two version a specific function: one which copies and another one which modifies in place.
*i is enough, you don't need (*i):
*i = log(*i);
This code:
if ( _s.is_empty() )
return true;
else
return false;
can be written as:
return _s.is_empty();
A:
For new users coming to this page, Armadillo has come a long way since 2012. All of these functions have native Armadillo implementations.
Armadillo has had element-wise functions since inception I think (someone please correct me): log(A), log2(A), and log10(A):
using namespace arma;
// Generate a matrix with the elements set to random floating point values
// randu() uses a uniform distribution in the [0,1] interval
mat A = randu<mat>(5,5); // or mat A(5, 5, fill::randu);
mat B = log(A);
Added any and vectorize in version 3.910:
vec V = randu<vec>(10);
mat X = randu<mat>(5,5);
// status1 will be set to true if vector V has any non-zero elements
bool status1 = any(V);
// status2 will be set to true if vector V has any elements greater than 0.5
bool status2 = any(V > 0.5);
// status3 will be set to true if matrix X has any elements greater than 0.6;
// note the use of vectorise()
bool status3 = any(vectorise(X) > 0.6);
// generate a row vector indicating which columns of X have elements greater than 0.7
urowvec A = any(X > 0.7);
Added accu before version 4.6:
mat A(5, 6, fill::randu); // fill matrix with random values
mat B(5, 6, fill::randu);
double x = accu(A);
double y = accu(A % B); // "multiply-and-accumulate" operation
// operator % performs element-wise multiplication
The accu function 'accumulates a sum', while the sum function generates a row or column vector that is the sum of the specified matrix dimension. For a column vector,
the sum of the elements is returned:
colvec v = randu<colvec>(10,1);
double x = sum(v);
mat M = randu<mat>(10,10);
rowvec a = sum(M);
rowvec b = sum(M,0);
colvec c = sum(M,1);
double y = accu(M); // find the overall sum regardless of object type
And Armadillo has its own field class template:
using namespace arma;
mat A = randn(2,3);
mat B = randn(4,5);
field<mat> F(2,1);
F(0,0) = A;
F(1,0) = B;
F.print("F:");
F.save("mat_field");
A:
Cannot say much about the speed, but here are two observations:
Your implementation of any appears to give true and false in the opposite way that Matlab would give them.
If you want to mimic the n dimensional matrix sum in Matlab, the output should not be a number but a n-1 dimensional matrix. In case of a 'regular' matrix the output should be a vector.
| {
"pile_set_name": "StackExchange"
} |
Q:
Require moderators to get agreement with target site moderators for migration actions
I recently came over this question where the decision to migrate it from SE Electrical Engineering to SE Code Review was obviously wrong, as that question doesn't fit for the target site policies.
I don't know how moderators communicate over cross site boundaries, but I'm sure that such migration action should be reviewed and confirmed by the target site moderators and go there in first place.
A:
Actually, the standard recommendation to the moderators (from the CMs) is specifically to not ask a site mod before migrating:
You don't need permission to migrate questions, and definitely shouldn't be pinging moderators on another site every time you have something that needs migration.
While mods are an easy source of knowledge about a site, they're not the all-knowing, final deciders of site scope; the users are. As such, rejecting the migration can be done by any five users closing the question for any reason (duplicates will stay but be marked as duplicates). There's really no reason to get another moderator involved. Shog explains the process for migration here.
That said, like with any migration, the rule for moderators and regular users alike is "Don't migrate crap" and we generally hope that our fellow mods will at least look at the site guidance before migrating, particularly when trying to send something to a site they're unfamiliar with... but it's really not a big deal. But, if a question looks on topic and doesn't look like a horrible question, there's no real reason to wait on migrating it to get a response from a site mod on the target site.
Occasionally I've seen (and have done myself) that mods on a site will come and report in to the migrating moderator to let them know if a the question was a bad fit for the site, particularly when several questions were migrated that were bad fits... but clearing every migration before sending is unnecessary.
A:
Just close and/or delete the question, or if you're not a mod/high rep user flag the post with the "other" option explaining the problem. That'll reject the migration.
If it keeps happening then the site mods can ping the other site's mods in TL to remind them to be careful when migrating that a) the question isn't just a bad question and b) it's actually on topic on the target site.
All mods should take the view that if there's any doubt about a migration then don't do it.
| {
"pile_set_name": "StackExchange"
} |
Q:
knockoutjs call a click method within a with
I have added a click method within a with template.
I keep getting an error that
Uncaught ReferenceError: myMethod is not defined
but Person clearly has that method
Person = (data) ->
name = ko.observable(data.name)
lname = ko.observable(data.lname)
myMethod = (data) ->
console.log 'person.myMethod'
test= ->
console.log 'person.test'
name:name
lname:lname
myMethod:myMethod
test:test
and this is the template
<div id="wrapper">
<h4>Person</h4>
<ul >
<li data-bind="with:person">
<span data-bind="text: name"> </span>
<span data-bind="text: lname"> </span>
<a href="#" data-bind="click: function() { myMethod($data) }" >CLICK </a>
</li>
</ul >
</div>
I don't understand how to call myMethod on the Person object while inside the anonymous template
I have tried things like
$parent.person.myMethod
$root.person.myMethod
this.myMethod
person.myMethod
http://jsfiddle.net/eiu165/a7uTM/3/
many thanks
EDIT
fixed to add the method name to myMethod
A:
You have two problems in your code:
You don't have a myMethod but a methodCall method so myMethod:myMethod should be myMethod:methodCall
Altough there is a myMethod on Person but you don't have a Person object in your person = ko.observable().
Because with the expression person($.parseJSON(data)) you only pass in the raw data. So what you need is to create a Person with person(Person($.parseJSON(data)))
Here is a fixed JSFiddle.
| {
"pile_set_name": "StackExchange"
} |
Q:
how do I know what version of gjslint I have installed?
This may be a dumb question, but I cannot figure it out. Doing gjslint --help does not provide the answer, and --version is not a valid flag.
Any ideas?
A:
Run this command:
cat `which gjslint` | grep [0-9] --color=always
or
cat $(which gjslint) | grep [0-9] --color=always
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows - tray icon to all users?
Is it allowed to have some process's icon to be displayed in all user sessions including terminal/multiple local logons, without spawning another process per each session? I don't need to share any windows between session, just the status icon to be able to check service's status without taking additional actions..
A:
It's not even possible. Shell_NotifyIcon communicates with a single instance of Explorer.EXE, the one running in the current user context.
A:
Processes can only access the interactive window station and desktops in the same session as the process. So this means you need one process per session.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android ClassNotFoundException: Didn't find class on path: Dexpathlist
I am facing the below error, and I have tried almost each and every solution from Stackoverflow. I am new to android, so may be I am not understanding the cause.
I am testing a libgdx project from the by following the instructions: https://github.com/libgdx/libgdx/wiki/Setting-up-your-Development-Environment-%28Eclipse%2C-Intellij-IDEA%2C-NetBeans%29
I installed the the below mentioned tools in the sequence:
JDK (java version 1.8.0.73)
Eclipse IDE for Java Developers Version: Mars.2 Release (4.5.2).
SDK (I have SDK tools 24.4.1 and SDK build tools 23.0.2 and 23.0.1)
Android development tools for Eclipse from the URL within eclipse: https://dl-ssl.google.com/android/eclipse/
Gradle 2.11 - I unzipped gradle-all-2.11.zip and kept on my local machine.
Now, when I generate a very basic sample libgdx project using gdx-setup.jar, and name the package my-gdx-game, it created a desktop version(java application) and an android version(android application)
I use Build tools V 23.0.1 while building the project through the jar. My eclipse screen looks like this:
When I right click on my-gdx-game-desktop and Run as Java application, it runs successfully and displays and image(project is all about displaying an image).
Now, for the android project, I created a AVD - Nexus 5, Android 4.4.2(api 19), CPU: ARM(armeabi-v7a), use host GPU. My manifest.xml file is as follows:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/GdxTheme" >
<activity
android:name="com.mygdx.game.AndroidLauncher"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Project> Properties> Android: only Android 4.4.2 is selected(API 19)
Now, when I right click on project>run as> android application, the AVD opens up and the below error is generated:
03-08 13:44:35.110: W/dalvikvm(1968): Unable to resolve superclass of Lcom/mygdx/game/AndroidLauncher; (3)
03-08 13:44:35.110: W/dalvikvm(1968): Link of class 'Lcom/mygdx/game/AndroidLauncher;' failed
03-08 13:44:35.110: D/AndroidRuntime(1968): Shutting down VM
03-08 13:44:35.120: W/dalvikvm(1968): threadid=1: thread exiting with uncaught exception (group=0xb1ae4ba8)
03-08 13:44:35.140: E/AndroidRuntime(1968): FATAL EXCEPTION: main
03-08 13:44:35.140: E/AndroidRuntime(1968): Process: com.mygdx.game, PID: 1968
03-08 13:44:35.140: E/AndroidRuntime(1968): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mygdx.game/com.mygdx.game.AndroidLauncher}: java.lang.ClassNotFoundException: Didn't find class "com.mygdx.game.AndroidLauncher" on path: DexPathList[[zip file "/data/app/com.mygdx.game-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.mygdx.game-1, /system/lib]]
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.os.Handler.dispatchMessage(Handler.java:102)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.os.Looper.loop(Looper.java:136)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.ActivityThread.main(ActivityThread.java:5001)
03-08 13:44:35.140: E/AndroidRuntime(1968): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 13:44:35.140: E/AndroidRuntime(1968): at java.lang.reflect.Method.invoke(Method.java:515)
03-08 13:44:35.140: E/AndroidRuntime(1968): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
03-08 13:44:35.140: E/AndroidRuntime(1968): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
03-08 13:44:35.140: E/AndroidRuntime(1968): at dalvik.system.NativeStart.main(Native Method)
03-08 13:44:35.140: E/AndroidRuntime(1968): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.mygdx.game.AndroidLauncher" on path: DexPathList[[zip file "/data/app/com.mygdx.game-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.mygdx.game-1, /system/lib]]
03-08 13:44:35.140: E/AndroidRuntime(1968): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
03-08 13:44:35.140: E/AndroidRuntime(1968): at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
03-08 13:44:35.140: E/AndroidRuntime(1968): at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
03-08 13:44:35.140: E/AndroidRuntime(1968): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
03-08 13:44:35.140: E/AndroidRuntime(1968): ... 11 more
03-08 13:49:35.320: I/Process(1968): Sending signal. PID: 1968 SIG: 9
I have tried a lot of answers from stackoverflow, but none seems to work in my case. Please help.
A:
So now the issue is resolved.
My project and external dependencies are checked now.
My manifest.xml has android:name=".AndroidLauncher" now.
Changing the Eclipse java version to 1.7 worked for me. In Eclipse, go to Windows->Preferences->Java->Compiler and set "Compiler compliance level" to 1.7.
3rd step was the game changer for me.
Thank you guys for the help.
| {
"pile_set_name": "StackExchange"
} |
Q:
EF1 SelectMany() left join
Is it possible to use SelectMany() and have it behave like a left join?
I am trying to flatten an Entity Object into a tabular format so I can use it as a data source for an .rdlc report. The SelectMany() works like a charm so long as there is a child object, but I want to see all of the parent objects regardless of whether it has children or not.
public class Owner
{
public int ownerID { get; set; }
public string ownerName { get; set; }
public List<Pet> pets { get; set; }
}
public class Pet
{
public int petID { get; set; }
public string petName { get; set; }
public string petType { get; set; }
}
public void GetOwners()
{
List<Owner> owners = new List<Owner>();
owners.Add(new Owner{ownerID=1, ownerName="Bobby", pets = null});
owners.Add(new Owner
{
ownerID = 2,
ownerName = "Ricky",
pets = new List<Pet>(){
new Pet{petID=1, petName="Smudge", petType="Cat"},
new Pet{petID=2, petName="Spot", petType="Dog"}}
});
var ownersAndPets = owners.SelectMany(o => o.pets
.Select(p => new { o.ownerName, p.petName }));
}
This will make ownersAndPets look like:
ownerName = "Ricky", petName = "Smudge"
ownerName = "Ricky", petName = "Spot"
What I need is:
ownerName = "Bobby", petName = null
ownerName = "Ricky", petName = "Smudge"
ownerName = "Ricky", petName = "Spot"
A:
Make sure the dataset is enumerable and then use "DefaultIfEmpty".
var ownersAndPets = owners
.SelectMany(o => o.pets
.DefaultIfEmpty()
.Select(p => new
{
o.ownerName,
p.petName
}));
NOTE: I didn't test this particular piece of code, but I have used this before so I know the it can be done.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android: is forcing to use ListView
I want to make a menu, which contains 4 different LinearLayouts.
Top one has title, second one has description, the third one has 3 ImageViews, which have event onClick, and the fourth one has a Button which also has onClick event.
Somehow, android doesn't like it, and forcing me to use ListView.
The exception message is: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
I have already tried to use ListView, and it didn't work as I expected. For example, the 3rd layout, which has 3 buttons, the events are not working for each ImageView, but instead on the row of the ListView.
What can be done?
Displaying my layouts xml files:
options.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/optionsLayout"
android:background="@drawable/bg" android:layout_gravity="center">
<include layout="@layout/options_layout1" android:id="@+id/optionsLayout1" />
<include layout="@layout/options_layout2" android:id="@+id/optionsLayout2" />
<include layout="@layout/options_layout3" android:id="@+id/optionsLayout3" />
<include layout="@layout/options_layout4" android:id="@+id/optionsLayout4" />
</LinearLayout>
options_layout1.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/optionsTitleLayout"
android:background="@drawable/options"
android:layout_gravity="center" />
options_layout2.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/chooseThemeTitleLayout"
android:background="@drawable/choose_theme" android:layout_gravity="center"
android:layout_marginTop="70dip" />
options_layout3.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/optionButtonsLayout"
android:layout_gravity="center" android:layout_marginTop="10dip" >
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/theme1Btn"
android:background="@drawable/theme1_off" android:layout_marginLeft="10dip"
android:layout_marginRight="10dip" />
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true"
android:id="@+id/theme2Btn" android:background="@drawable/theme2_off"
android:layout_marginLeft="10dip" android:layout_marginRight="10dip" />
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@id/theme2Btn"
android:id="@+id/theme3Btn" android:background="@drawable/theme3_off"
android:layout_marginLeft="10dip" android:layout_marginRight="10dip"/>
</LinearLayout>
options_layout4.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/saveButtonLayout"
android:layout_gravity="center" >
<Button android:id="@+id/saveBtn" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerHorizontal="true"
android:text="Save" android:layout_marginTop="10dip"/>
</LinearLayout>
Thanks,
Henry.
A:
The problem is not the xml, the problem is somewhere in the code. You use a specific class which expects an ID R.id.list to be in your layout. Probably your Activity still extends ListActivity? This Activity needs an R.id.list in it's layout.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get image transparency working on IE
I have a GIF image that has an alpha set, and when my site loads in Firefox 3.0, it acts transparently on the parts of the image that should. However, when I try to load the GIF image in IE7, it comes back as a solid block. Actually, it is like the color from the image bled into the transparent area.
Do anyone have any suggestions for resolving this kind of problem? Pointers on what to look into, or a route you've used to solve this kind of problem.
I've been controlling this in CSS -- and while I'd like to avoid the conditional comments route and multiple CSSes, I'd be willing if the suggestion tangibly shows how I can resolve the IE compatibility problems.
Thanks,
Sean
A:
I don't recall ever having a problem with transparent gifs in IE (any version).
First off try loading the image on its own - this will tell you if it's the image or some CSS rules going awry.
If it's still wrong, try re-saving it with a different program. The gimp will do.
Edit: It's at the CSS level so I'd check for which rules have the background colour that is appearing... hopefully it should be easy to find a likely candidate. Change the color to #ff0000 and check if the image changes as you expect. Then figure out why that rule shows on IE but not FF. If you have a URL for the page I could take a look.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: String [ [k1:v1, k2:v2], [k3:v3] ] to Object
I'm stuck with an application that outputs the following
[[_type:logs, _id:AVY0ofxOHiyEPsw_vkZS, _index:firewall-all-2016.07.29, _score:13.445344], [_type:logs, _id:AVY1EI1z79siNC3TEi7P, _index:firewall-all-2016.07.29, _score:13.445344]]
I would like to parse this text into an iterable object. But the standards approach using ast.literal_eval doesn't like the input.
Is there something else I can try before I start looking into str replace etc...
Thank you
A:
How about this:
import re
data = "[[_type:logs, _id:AVY0ofxOHiyEPsw_vkZS, _index:firewall-all-2016.07.29, _score:13.445344], [_type:logs, _id:AVY1EI1z79siNC3TEi7P, _index:firewall-all-2016.07.29, _score:13.445344]]"
parsed_1 = re.findall("\[(.*?)\]", data[1:-1])
parsed_list = []
for line in parsed_1:
parsed_dict = {}
for record in line.split(","):
k, v = record.split(":")
parsed_dict[k] = v
parsed_list.append(parsed_dict)
print(parsed_list)
The output is list of dictionaries, you can itarate over it in many ways.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add an item to a list multiple times with list comprehension
I'm making a list in the following way:
lst = ['val1', 'val2', 'val3']
output = [item for it in lst]
...however, I would like to add an arbitrary number of each item to the list, not just one.
Something like this (if I wanted to add 3 elements each time to the list):
output = [item*3 for item in lst]
...so that if lst looks like this:
['val1', 'val2', 'val3']
...output looks like this:
['val1', 'val1', 'val1', 'val2', 'val2', 'val2'...]
How can I accomplish this?
A:
Like this (you'll have to change the code to suit your needs, obviously):
lst = ['val1', 'val2', 'val3']
output = [i for i in lst for x in range(3)]
print(output)
Output (formatted):
[
'val1', 'val1', 'val1',
'val2', 'val2', 'val2',
'val3', 'val3', 'val3'
]
Change 3 to the number of times you want the item to repeat.
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA,drag down formula where there are empty cells
This is my sample in Sheet1,(numbers from B to F are simply =Sheet2!B2 kind of formula)
A B C D E F
11/12/2016 300 4 4 3 85
12/12/2016 23 4 4 2 87
13/12/2016 21 4 4 2 79
14/12/2016 67 4 4 4 76
I am trying to insert below the column A the dates of the next 7 days (which I I have achieved)and consequentially drag down the formula from Column B to F. I cannot use RANGE B1:F7 because the week after i will append to the old 7 days data the new ones, so i need dynamic ranges.
Here is my attempt, however i return on the inRange concatentation in the for Loop (Error= Range ob object_global failed):
Sub test()
Dim r As Range Set r = Intersect(ActiveSheet.UsedRange, Range("A:A")).Cells.SpecialCells(xlCellTypeBlanks)
r(1).Formula = "=Today()"
r(2).Formula = "=Today()+1"
r(3).Formula = "=Today()+2"
r(4).Formula = "=Today()+4"
r(5).Formula = "=Today()+5"
r(6).Formula = "=Today()+6"
Dim inRange As Range
Set inRange = Sheets("Sheet1").Range("B" & i & ":" & "F" & i)
For i = 1 To 7
Sheets("Sheet1").Range("B1:F1").Select
Selection.AutoFill Destination:=Range(inRange), Type:=xlFillDefault
Next i
End Sub
Thanks
A:
I wouldn't use this:
Set r = Intersect(ActiveSheet.UsedRange, Range("A:A")).Cells.SpecialCells(xlCellTypeBlanks)
Because if the intersection returns no cells, it will raise an error. And if this table is the only range in Sheet1, there are rows which you may delete for the sake of performance and file size.
If the formulas in the range (B1,F1) don't vary, I would code it this way:
Sub test()
Dim r As Excel.Range
Dim i As Integer
'I wouldn't use this
'Set r = Intersect(ActiveSheet.UsedRange, Range("A:A")).Cells.SpecialCells(xlCellTypeBlanks)
'Instead:
Range("A1").End(xlDown).Offset(1, 0).Activate
ActiveCell.Formula = "=Today()"
For i = 0 To 6
If i = 0 Then
ActiveCell.Formula = "=Today()"
Else
ActiveCell.Formula = "=Today()+" & i
End If
ActiveCell.Offset(1, 0).Activate
Next i
Range("B1:F1").Copy Intersect(ActiveSheet.UsedRange, Range("B:F")).Cells.SpecialCells(xlCellTypeBlanks)
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
query base on conditions in array of document
db.products
{"product":"iphone",
"people_have_this":[001, 002, 003, 004]} //objectID
{"product":"samsung",
"people_have_this":[001, 004]}
{"product":"nokia",
"people_have_this":[001, 002, 003]}
db.users
{"name":"john",
"id":"001"}
{"name":"peter",
"id":"002"}
How to get a list of product John has?. What I expected is
[{"product":"iphone",
"people_have_this":[001, 002, 003, 004]},
{"product":"samsung",
"people_have_this":[001, 004]},
{"product":"nokia",
"people_have_this":[001, 002, 003]}]
A:
If you know the id for John then it's a simple query like this...
db.products.find( { people_have_this: "001" } );
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementing persistent associative array on top of LMDB
I am new to key-value stores. I would like to try LMDB as persistent associative array and want to be able to use long length keys such as file paths or URLs.
LMDB defines compile-time constant MDB_MAXKEYSIZE=511 imposing a maximum for key length.
What technique should I use to implement persistent long-length key dictionary on top of LMDB? Some kind of hashing and collision resolution? Or recompile with different MAXKEYSIZE, for example 2048? Or LMDB is a wrong tool for this job?
A:
In my own use, I handled a similar case by hashing the arbitrary-length string keys through SHA-256 to produce a fixed-size 32-byte digest key for the B+ tree. This strategy entails the following two caveats:
You do altogether lose the ability to perform prefix string lookups. This isn't usually a significant problem for a use case such as the one you describe.
In case you need to be able to enumerate all the original string keys, you'll need to store the original strings in another LMDB sub-database such that you can perform a lookup based on a SHA-256 digest to retrieve its corresponding original string--which will have been stored as the value of a key/value pair in the sub-database, thus not subject to MDB_MAXKEYSIZE limits. This does increase space requirements, adds an additional tree lookup for every cursor operation in a full scan, and will not yield the strings in lexicographical order. If you can tolerate those limitations, this is a workable approach.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating 4 digits SMS confirmation code
I need to generate simple, 4 digits confirmation SMS code, which based on given information, e. g. username, or birthdate, whatever. So, for two identical inputs, I need two same output codes.
I can't store this code in database.
I'm writing in C#, and have been thinking about GetHashCode method, but he is highly not recommended to use anywhere. Maybe some hashing, but they have much more that 4 character string.
How can I generate such code?
A:
Just take the pieces of info you need, concatenate them together into a string, then hash it with a cryptographic hash function. Take the bottom 4 digits of the hash and call it a day.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript constructor and prototype object
I am curious as to what's going on here. As you can see, I have defined a constructor function called range to build new range objects. I've extended the range constructor through it's prototype, adding a simple includes method. I've created my new object and used the variable of p. When I attempt to use this method with my range objects, all is well and it works as expected. The problem is when I try to look at at p.prototype it tells me that it's type is undefined and p.prototype has no methods... Huh??
What's going on here?? How is p an object and p.prototype is not?
function range(from, to) {
this.from = from;
this.to = to;
}
range.prototype = {
includes: function(x) { return this.from <= x && x <= this.to; },
}
var p = new range(1, 4);
console.log(typeof p) //outputs object
console.log(typeof p.prototype) //outputs undefined
console.log(Object.getOwnPropertyNames(range.prototype)); //outputs includes
console.log(Object.getOwnPropertyNames(p.prototype)); //throws error, p.prototype is not an object
A:
The problem is when I try to look at at p.prototype it tells me that it's type is undefined
That's correct. The objects created by your range constructor do not have a prototype property, but they do have an underlying prototype (which is drawn from the prototype property of the range function).
Let's look at what happens when you do new range():
The JavaScript engine creates a new, blank object.
The JavaScript engine assigns that object's underlying prototype (not prototype) to be the object referenced by range.prototype. (In the spec, this property — which is not directly accessible in code but see below — is called [[Proto]].)
The JavaScript engine calls range with this referring to the new object.
Assuming range doesn't return a different object (which it can do; this is a bit obscure), the result of new range is the new object created in step 1.
Later, when you use this.includes, this is what happens:
The engine looks at the actual object to see if it has an includes property.
Since it doesn't, the engine looks at [[Proto]] to see if it has one.
Since it does, it uses that one (if not, it would have looked at [[Proto]]'s [[Proto]] and so on).
The key things here are:
Objects have underlying prototypes, which are not accessible via any named property on the object itself. (In fact, it used to be we couldn't get to them at all. Now, in ES5, we have Object.getPrototypeOf.)
Objects created via new SomeFunctionName get their prototype from SomeFunctionName.prototype property, which is a perfectly normal property of the SomeFunctionName object (functions are first-class objects in JavaScript).
Side note: You're replacing the prototype of range with your code. In general, although it works, I would avoid that. Instead, augment the existing object referred to by range.prototype. (Add properties to it, rather than replacing it.) But that's not central to your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Secrets in docker compose
My environment is an ubuntu 18.04 VPS.
I can't get file-based secrets to work with mariadb in a docker container.
create docker-compose.yml:
version: '3.7'
services:
db:
image: mariadb:10.4.8-bionic
environment:
- MYSQL_ROOT_PASSWORD_FILE=/run/secrets/password_root
- MYSQL_PASSWORD_FILE=/run/secrets/password_user
- MYSQL_DATABASE=database
- MYSQL_USER=admin
secrets:
- password_root
- password_user
secrets:
password_root:
file: .secret_password_root
password_user:
file: .secret_password_user
create secrets:
echo -n secret > .secret_password_root
echo -n secret > .secret_password_user
chown root:root .secret_password*
chmod 400 .secret_password*
(Note that I can set 444, but that would expose the secrets file on the host which is a very bad idea.)
run:
docker-compose up
Error:
db_1 | /usr/local/bin/docker-entrypoint.sh: line 37: /run/secrets/password_root: Permission denied
According to the docs, the secrets file should be mounted as 0444, but that's obviously not happening.
A:
Apparently this is not supported for "docker compose", only for "docker swarm". The docs are misleading.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sparklines charts coming up different sizes?
I am making a simple weather app and my Sparklines charts are coming up as different sizes even with the same height and width properties, any idea why?
WeatherList container:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
return(
<tr key={name}>
<td>{name}</td>
<td><Chart data={temps} color="orange" units="K" /></td>
<td><Chart data={humidities} color="green" units="%" /></td>
<td><Chart data={pressures} color="black" units="hPa" /></td>
</tr>
);
}
render(){
return(
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Humidity (%)</th>
<th>Pressure (hPa)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps({ weather }) {
return { weather };
}
// Above function can also be written...
/* function mapStateToProps({state}){
return {weather: state.weather};
}*/
export default connect(mapStateToProps)(WeatherList);
Actual Chart component:
import _ from 'lodash';
import React from 'react';
import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines';
// lodash will grab the average
function average(data) {
return _.round(_.sum(data)/(data.length));
}
export default (props) => {
return (
<div>
<Sparklines height={120} width={180} data={props.data}>
<SparklinesLine color={props.color} />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>{average(props.data)} {props.units}</div>
</div>
);
};
I'm thinking it might be in the JSX somewhere within the WeatherList but I have been sitting here with no success so far.
A:
Try
height -> svgHeight
width -> svgWidth
should correct your output
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS orderBy not numerical
Trying to keep the code as minimal as possible (avoiding writing a sort function). I have a simple table of data that is sortable.
The issue in this example is that "score" does not sort numerically. The user 'Julie' has the lowest score of '9.12' however when sorted it appears to be doing so lexically.
The example is a modified version of the example used in the angular docs on orderby
Here is a snippet of the code and associated plunker.
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
<table class="user">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'score'; reverse=!reverse">user score</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="user in users | orderBy:predicate:reverse">
<td>{{user.name}}</td>
<td>{{user.score}}</td>
<td>{{user.age}}</td>
</tr>
</table>
http://plnkr.co/edit/Ytpj3SUgtLKQvQvB4Yhb
A:
The issue is that your score attribute in your data structure is a string. You can:
A) change it to be a number score:9.12 instead of score:'9.12' http://plnkr.co/edit/YItGeFfFLN8OnXeejv7m?p=preview
B) If you can't change the data, write a function ("Getter function. The result of this function will be sorted using the <, =, > operator") for the expression portion of your orderBy that'll return the string to a number for the comparison. <tr ng-repeat="user in users | orderBy:yourfunction:reverse">
| {
"pile_set_name": "StackExchange"
} |
Q:
What is solution of this expression
I am new to logarithms, and I need to find out the solution set of this expression.
$$x^{\log_a x} = (a^\pi)^{(\log_a x)^3} \\ a \in \mathbb{N} , a>0 ,a \neq 1$$
A:
Let $\log_a x=t$, then $a^t=x$. Use this in the equation given to write
\begin{align*}
x^{\log_a x} & = (a^\pi)^{(\log_a x)^3}\\
x^{t}&=a^{\pi t^3}\\
a^{t^2} & = a^{\pi t^3}\\
t^2&=\pi t^3.
\end{align*}
Thus either $t=\log_a x=0$ or $t=\log_a x=\frac{1}{\pi}$. This means $x=1$ or $x=a^{\frac{1}{\pi}}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete file while another process still writes to it
I'm playing around with writing to file with Python:
import time
fo = open("foo.txt", "a+", 1)
while True:
fo.write("Some data to write");
time.sleep(.001)
If I execute this code, and than just manualy delete the "foo.txt" file, the process still writes somewhere.
What happens with the content? The process writes to file, but no file is available.
A:
From The Linux Programming Interface by Michael Kerrisk
In addition to maintaining a link count for each i-node, the kernel also counts open file descriptions for the file (see Figure 5-2, on page 95). If the last link to a file is removed and any processes hold open descriptors referring to the file, the file won’t actually be deleted until all of the descriptors are closed.
Your script have opened the file, thus it holds a open descriptor referring to the file. System won't delete the file just after you have removed it by i.e. use of rm command. But it will delete it after your script close the descriptor.
I have found reference in man, from man remove:
remove() deletes a name from the filesystem. It calls unlink(2) for files, and rmdir(2) for directories.
If the removed name was the last link to a file and no processes have the file open, the file is deleted and the space it was using is made available for reuse.
If the name was the last link to a file, but any processes still have the file open, the file will remain in existence until the last file descriptor referring to it is closed.
Just as @oglu mentioned in his answer, this is not portable behavior. On Windows, you may chose whether it should be possible to remove the file that you have opened.
From CreateFile function at MSDN
FILE_SHARE_DELETE (0x00000004)
Enables subsequent open operations on a file or device to request delete access.
Otherwise, other processes cannot open the file or device if they request delete access.
If this flag is not specified, but the file or device has been opened for delete access, the function fails.
Note Delete access allows both delete and rename operations.
| {
"pile_set_name": "StackExchange"
} |
Q:
Identify this unusual spicy appetizer
A friend of mine years back related a story about an appetizer that he ordered at an Asian restaurant that was apparently quite unusual. It was a bowl of something (possibly peppers or another vegetable) where each piece looked completely identical, but one out of every 15-20 of them was extremely spicy. The rest tasted rather mild, so he and his friends would go around the table basically playing a kind of Russian roulette with spicy food.
Does anybody have any idea of what this could be?
A:
It sounds like it could be Shishito peppers, which about 10% are spicy, and "even experts may not be able to distinguish relative hotness on the same plant.".
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequence contains no elements - LINQ, MVC, Average
I am running into this error. I see that the reason is because the average returned at times is 0.00 which from a data stand point is accurate. This SQL query works fine, but that is because it puts in 0.00 automatically.
LINQ complains and so I tried using DefaultIfEmpty() but it says it is expecting my ViewModel.
Dim ticketCounts = From t In queue _
Where _
(t.StatusId = 2) And _
(t.CloseDate.Year = Convert.ToDateTime(DateTime.Now).Year) And _
(t.ResolutionDays > 0)
Group t By _
Column1 = CType(t.CloseDate.Month, Integer), _
Column2 = CType(t.CloseDate.ToString("MMMM"), String) _
Into g = Group _
Order By Column1 _
Select _
Id = Column1, _
Month = Column2, _
Critical = g.Where(Function(t) t.PriorityId = 1).DefaultIfEmpty().Average(Function(t) t.ResolutionDays), _
High = g.Where(Function(t) t.PriorityId = 2).DefaultIfEmpty().Average(Function(t) t.ResolutionDays), _
Normal = g.Where(Function(t) t.PriorityId = 3).DefaultIfEmpty().Average(Function(t) t.ResolutionDays), _
Low = g.Where(Function(t) t.PriorityId = 4).DefaultIfEmpty().Average(Function(t) t.ResolutionDays), _
Total = g.Where(Function(t) t.Id <> Nothing).DefaultIfEmpty().Average(Function(t) t.ResolutionDays)
UPDATED!
This is the SQL query doing the same thing I need VB to do.
SELECT
DATENAME(MONTH,t.CloseDate) AS 'Month',
AVG(CASE WHEN (t.PriorityId = 1) THEN CAST(t.ResolutionDays AS Decimal(18, 2)) ELSE 0 END) AS 'Critical',
AVG(CASE WHEN (t.PriorityId = 2) THEN CAST(t.ResolutionDays AS Decimal(18, 2)) ELSE 0 END) AS 'High',
AVG(CASE WHEN (t.PriorityId = 3) THEN CAST(t.ResolutionDays AS Decimal(18, 2)) ELSE 0 END) AS 'Normal',
AVG(CASE WHEN (t.PriorityId = 4) THEN CAST(t.ResolutionDays AS Decimal(18, 2)) ELSE 0 END) AS 'Low',
AVG(CAST(t.ResolutionDays AS Decimal(18, 2))) AS 'Monthly Average'
FROM
tblMaintenanceTicket t
WHERE
t.StatusId = 2
AND YEAR(t.CloseDate) = year(getdate())
GROUP BY
MONTH(t.CloseDate),
DATENAME(MONTH,t.CloseDate)
ORDER BY
MONTH(t.CloseDate)
A:
Critical = g.Where(Function(t) t.PriorityId = 1).Select(Function(t) t.ResolutionDays).DefaultIfEmpty().Average()
Reference:
http://geekswithblogs.net/SoftwareDoneRight/archive/2011/02/15/fixing-linq-error-sequence-contains-no-elements.aspx
A:
The problem is that all of the scalar LINQ methods (Average, Max, etc ...) throw an exception if the input IEnumerable(Of T) doesn't have any elements. It looks like the g.Where calls are resulting in an empty collection resulting in the exception.
What you may want to do is write a method which handles the empty case and returns a default value.
| {
"pile_set_name": "StackExchange"
} |
Q:
disable log4net logging in third party dll
I am working on WPF application with log4net logging.
Also using one third party DLL for SWF file reading purpose.
This DLL was developed with log4net logging.
When working with swf reading functionality in my application i have noticed that around 7MB of information logging in to my application logfile by third party dll. Because of this my application logfile size is increasing drastically.
Is there any way to disable that third party dll logging from my application configuration file? I don't have source code of this third party dll.
A:
Download .NET reflector. Use it to determine what's the package root used by third party application. If it's Com.Thirdparty, then put this into your log4net configuration:
<logger name="Com.Thirdparty">
<level value="OFF" />
</logger>
| {
"pile_set_name": "StackExchange"
} |
Q:
Configure Keycloak OTP via Administration REST API
I am evaluating Keycloak for one of our systems where 2FA with TOTPs would be a requirement. I am trying to figure out if there is a way to register a new Authenticator app via the Admin REST API, so our user's wouldn't need to interact with the Keycloak provided account page.
I've spent some time with the reference documentation but got no luck. Is there something I am missing? Is omitting the Keycloak provided UIs a preferred way to use this service?
Thanks!
A:
No, you can't use API for that. You need user UI interaction.
I can't imagine how you will be able to distribute TOTP credentials to the user device. Maybe some high profile enterprise environments (Android Enterprise, ...) can force it, but it won't be very common use case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which components can be added in a JDesktopPane?
I'm having some trouble designing an MDI Application with Swing.
I have no trouble implementing the JDesktopPane & JInternalFrames, my question will be a little more specific. Here is my base container Frame in a glance:
package applicationGUI;
import javax.swing.JFrame;
public class DesktopContainer extends JFrame{
/* Fields */
/* Constructors */
public DesktopContainer(){
setContentPane(new Desktop());
setJMenuBar(AppllicationMenuBar.getMenuBar());
}
/* Public Methods */
public Desktop getDesktop(){
return (Desktop)getContentPane();
}
}
And my Desktop:
public class Desktop extends JDesktopPane{}
Notice that I set a Desktop as a content pane of the DesktopContainer. What I want is, to be able to add JPanels on the Desktop (specificially, just below the JMenuBar). Unfortunately, I wasn't able to do this. And finally, here are my questions:
1-) Can JPanel objects be drawn on a JDesktopPane? I did some digging, I guess it has something to do with the JLayeredPane capabilities, but unfortunately I couldn't implement it.
2-) If JPanel object can't be drawn on a JDesktopPane, how can I manage to do what I want, any advice? I just figured, "add two JPanels to the JFrame, use the one on the top for your needs, and draw JDesktopPane into the second JPanel below". Is this a good approach?
Thank you for your answers..
A:
A JPanel can be drawn and can receive events on a JDesktopPane
public class DesktopContainer extends JFrame {
/* Constructors */
public DesktopContainer(){
setContentPane(new Desktop());
setJMenuBar(createJMenuBar());
APanel a = new APanel();
a.setBounds(0, 0, 200, 200);
a.setVisible(true);
getDesktop().add(a);
}
....
}
class Desktop extends JDesktopPane {
}
class APanel extends JPanel {
public APanel() {
setLayout(new BorderLayout());
add(new JButton("Hello stackoverflow"));
}
}
It works fine.
You should invoke setVisible(true), setBounds() on JPanel as JInternalFrame required.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I edit file permissions (e.g. make script files executable) from within Sublime Text 2?
When writing e.g. shell scripts, I want to change their permissions (primarily the executable permission) from within Sublime Text 2.
How can I accomplish that?
A:
The following is a general purpose permissions editing command for the file currently being edited. For a more detailed explanation on plugins and editing the Sublime Text 2 menu, see this post.
It will add a Change Mode command in the Edit menu. When selected, the user is asked to enter a valid argument string to chmod (e.g. u+rwx or 755; default is the currently set 4 digit octal permissions string like 0644), that is then applied to the file being edited.
Select Tools » New Plugin, insert the following content and save as chmod.py in ~/Application Support/Sublime Text 2/Packages/User/:
import sublime, sublime_plugin, subprocess
def chmod(v, e, permissions):
subprocess.call( [ "chmod", permissions, v.file_name() ] )
def stat(filename):
proc = subprocess.Popen( [ "stat", "-f", '%Mp%Lp', filename ], stdout=subprocess.PIPE )
return str(proc.communicate()[0]).strip()
class ChangeModeCommand(sublime_plugin.TextCommand):
def run(self, edit):
if sublime.platform() != 'osx':
return
fname = self.view.file_name()
if fname == None:
sublime.message_dialog("You need to save this buffer first!")
return
perms = stat(fname)
def done(permissions):
chmod(self.view, edit, permissions)
sublime.active_window().show_input_panel(
"permissions to apply to the file " + fname + ": ", perms, done, None, None)
To insert a menu item for this command, add the following to ~/Application Support/Sublime Text 2/Packages/User/Main.sublime-menu, merging with existing file contents if the file already exists:
[
{
"id": "edit",
"children":
[
{"id": "wrap"},
{ "command": "change_mode" }
]
}
]
A:
It basically works under Linux too, but the stat command works differently and shows numerous information that is not needed.
stat -c %a filename
will do instead and returns something like '644'.
| {
"pile_set_name": "StackExchange"
} |
Q:
Allow only one application instance
I'm sorry about my title may be it make you confusing (it's just I don't know what words should I use). My problem is I don't want to allow user to open my application multiple time. Please help. Thank you in advance.
A:
Use the “Make single instance application” flag; in the solution explorer, right-click the project and select properties. See this question for more details.
MSDN documentation here.
Screenshot:
| {
"pile_set_name": "StackExchange"
} |
Q:
Why system RAM can not have a battery backup in the same way as a CMOS?
This is follow up of Why does RAM have to be volatile ?. While the question answers why the computer main memory can not be non-volatile , it occur to me that Why can't we just back up the DRAM with a battery to preserve it's contents across boots.
But , since this technology is nonexistent , I wondered what were the reasons for the same.
So, What practical reasons are there for being unable to design a battery-backed main memory like those used in the CMOS and game-cartridges?
Note :I would like answers that illustrate the practical problems involved in designing such a system rather than comparing it to existing technologies like suspend / hibernate .
A:
Introducing a power source to RAM is called turning on a computer, what you're talking about is basically just leaving your computer on and pressing the sleep button.
Expanded Answer:
It has already been implemented to the extent current hardware allows, sleep mode shuts down all hardware non-essential to keeping the state of the computer in RAM, so the ideas are the exact same besides the concept of shutting down the machine. To actually reboot the machine into the previous state would rely on having some availible space left in RAM and MAJOR kernel modifications, so unless you reverse engineer the NT Kernel or commission Microsoft to create the feature the software itself makes it impossible.
A:
Adding to what Slowki said, the reason why Sleep works is that you aren't rebooting.
The data in RAM only has meaning if you know what and where it is. As is, there is no explicit rule to, on boot, any program should store it's information anywhere on the RAM (there are of course exceptions).
If what you suggest (retaining RAM information between reboots) went into practice, the OS would have to come as a middle man between every program that was running and the information present in RAM. In order to do this, you would need to store the addresses of every piece of information in RAM and then tell the programs to access them.
This not only requires a full rewrite of memory allocation rules but a dangerous situation where the OS, and not the program, has responsibility for the program's state. Due to the difficult involved in this, and the current practices in programming, these are the reasons I point out for the unfeasibility of your proposal.
Sleep places your computer on a low-power state, such that the computer's state is stored. No RAM or disk activity should happen while the computer is Sleep-ing.
There is also the Hibernate function, where you, instead of using the volatile RAM, use instead a non-volatile storage (your HDD or SDD) to store the contents of the RAM. In this case you don't use any sort of power.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to separate my rendering from game loop?
If I have a (complex) operation that takes a long time for it to finish, for instance, a couple of seconds, my frame rate drops far below the acceptable. How could I still implement it while it is not messing up my frame rate?
A:
It is possible to separate the render thread from the update thread, but it is quiet difficult to make. You'll need a triple-buffer of the render state. For an explanation of the problem and solution check out:
http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part1/
http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part2/
http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part3/
http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part4/
The site contains both source + binary distribution if you're interested.
A:
Without using threads, here are two ways.
do all at once (cLogic)
using something I call a state machine (cLogicStateMachine)
Call cLogic::Update(), check if its member updating is TRUE, if so return or else turn it on. Do the logic. Before exiting the function, turn off updating.
In the state machine you do one thing at each frame. Leaving the state as it is afterwards. So it catch on there where you left off.
A possibility can be, make a variable that catches the time, do some iterations until 0.1 seconds has passed and leave, the states stay as they are.
Not familiar with cocos2-iphone myself I produced a pseudo-code-like example based on c++. As you are asking the principle, I think that would be okay. It surely can use optimizations.
class cLogicStateMachine
{
cLogic()
: // initialize members
Iterating( FALSE ),
IteratorX( -1 ),
IteratorZ( 0 ){};
void Update()
{
if( Iterating )
{
++IteratorX;
if( IteratorX > 31 )
{
IteratorX = 0;
++IteratorY;
if( IteratorY > 31 )
{
// Reset
IteratorX = -1;
IteratorY = 0;
Iterating = FALSE;
return;
}
}
playfield[ IteratorY * 32 + IteratorX ] = TILE_TYPE_NONE;
}
}
BOOL Iterating;
int IteratorX;
int IteratorY;
};
class cLogic
{
cLogic()
: // initialize members
updating( FALSE ){};
void Update()
{
if( updating )
return;
updating = TRUE;
/* do logic */
// loop around the current tile to check walkability
for( int y = 0; y < 32; ++y )
{
for( int x = 0; x < 32; ++x )
{
playfield[ y * 32 + x ] = TILE_TYPE_NONE;
}
}
/* end logic */
updating = FALSE;
};
BOOL updating;
};
class cMain
{
cMain()
: // initialize members
m_timeUpdateGameLogic( 0.0f ){};
void update()
{
/* collect all data you need to know */
m_timeUpdateGameLogic += elapsedTime;
if( m_timeUpdateGameLogic >= 0.5f )
{
m_timeUpdateGameLogic -= 0.5f; // set to 0 but without lagging
if( using_statemachine )
{
if( m_logic.Iterating == FALSE )
{
// start over
m_logic.Iterating = TRUE;
}
} else
// if using cLogic
{
m_logic.Update();
}
}
if( using_statemachine )
{
m_statemachine.Update()
}
/*
handle other stuff like view movement
score update
and such
*/
}
void render()
{
/* conclude the logic, i.e. render everything */
}
float m_timeUpdateGameLogic;
cLogic m_logic;
cLogicStateMachine m_statemachine;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem running thumbs_up gem in Rails 3
I followed the gem installation steps on https://github.com/brady8/thumbs_up but ran into an error when following the usage steps.
This is taken from my User and Comment models:
class User < ActiveRecord::Base
<some devise specific stuff>
acts_as_voter
end
class Comment < ActiveRecord::Base
acts_as_voteable
end
The error I'm getting is the following:
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in 'method_missing'Exiting
: undefined local variable or method 'acts_as_voter' for # (NameError)
Removing the acts_as_voter line in User model eliminates the problem even though there is an 'acts_as_voteable' in the Comment model which seems to work fine then.
Any ideas?
A:
I had the same issue after adding the thumbs_up gem to my application.
Restarting the server cleared it up for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Animate diagonal line query
I was wondering if anyone knows how to create a diagonal line using jquery and animate it so that when it appears its drawn on rather than just appears?
Also need the same for a circle.
A simple jsfiddle would be awesome.
Muchos for the help!!
A:
You could actually do it with pure CSS:
demo
Diagonal
HTML:
<div class='box'></div>
CSS:
.box {
overflow: hidden;
outline: dotted 1px;
width: 8.09em; height: 5.88em;
background: linear-gradient(36deg,
transparent 49.5%, black 49.5%, black 50.5%, transparent 50.5%)
no-repeat -8.09em -5.88em;
background-size: 100% 100%;
animation: drawDiag 2s linear forwards;
}
@keyframes drawDiag {
to { background-position: 0 0; }
}
Circle
HTML:
<div class='circle'>
<div class='cover'></div>
</div>
CSS:
.circle {
overflow: hidden;
position: relative;
width: 10em; height: 10em;
}
.circle:before {
position: absolute;
width: inherit; height: inherit;
border-radius: 50%;
box-shadow: inset 0 0 0 1px black;
content: '';
}
.cover {
position: absolute;
margin: 0 -50%;
width: 200%; height: inherit;
transform-origin: 50% 0;
background: white;
animation: revealCircle 5s linear forwards;
}
@keyframes revealCircle {
to { transform: rotate(180deg); }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Show a sequence of images in WPF then close form
I have a window that shows an open lock.
When the user clicks a button the lock must change to closed, wait a second and then close the windows.
How can I do that using WPF?
Here is my initial xaml:
<Button Grid.Row="2" BorderThickness="0" Background="Transparent" Margin="32"
IsTabStop="False" Click="BtnUnlockClick">
<Button.Content>
<Grid>
<Image Grid.Row="1" Source="/Common.Wpf;component/images/unlocked.png" Visibility="Visible" Name="imgUnlocked"/>
<Image Grid.Row="1" Source="/Common.Wpf;component/images/locked.png" Visibility="Collapsed" Name="imgLocked"/>
</Grid>
</Button.Content>
</Button>
and C#:
private void BtnUnlockClick(object sender, RoutedEventArgs e)
{
//do stuff here
}
A:
Put only one Image element into the Button's Content.
<Button Click="BtnUnlockClick" ...>
<Image Source="/Common.Wpf;component/images/unlocked.png"/>
</Button>
In the Click event handler change its Source, wait a second, then close the Window. The handler method must be declared async.
private async void BtnUnlockClick(object sender, RoutedEventArgs e)
{
var image = (Image)((Button)sender).Content;
image.Source = new BitmapImage(
new Uri("pack://application:,,,/Common.Wpf;component/images/locked.png"));
await Task.Delay(1000);
Close();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Parse multiple doubles from a String
I would like to know how to parse several double numbers from a string, but string can be mixed, for instance: String s = "text 3.454 sometext5.567568more_text".
The standard method (Double.parseDouble) is unsuitable. I've tried to parse it using the isDigit method, but how to parse other characters and .?
thanks.
A:
You could search for the following regex:
Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")
and then use Double.parseDouble() on each match.
A:
After parsing your doubles with the suitable regular expressions like in this code or in other posts, iterate to add the matching ones to a list. Here you have myDoubles ready to use anywhere else in your code.
public static void main ( String args[] )
{
String input = "text 3.454 sometext5.567568more_text";
ArrayList < Double > myDoubles = new ArrayList < Double >();
Matcher matcher = Pattern.compile( "[-+]?\\d*\\.?\\d+([eE][-+]?\\d+)?" ).matcher( input );
while ( matcher.find() )
{
double element = Double.parseDouble( matcher.group() );
myDoubles.add( element );
}
for ( double element: myDoubles )
System.out.println( element );
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Fatal error: Class 'Zend_Pdf_Color_RGB' not found app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php magento using zend library
this code:
$page = $this->newPage();
has been replaced by this:
$pdf->pages[] = $pdf->newPage('4:6:');
but this results in:
Fatal error: Class 'Zend_Pdf_Color_RGB' not found app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
Please tell how can I reduce page size of a pdf in magento?
A:
Actually there is no class Zend_Pdf_Color_RGB. Its Zend_Pdf_Color_Rgb. Check your code and replace Zend_Pdf_Color_RGB with Zend_Pdf_Color_Rgb
| {
"pile_set_name": "StackExchange"
} |
Q:
compilation error in macro
I have downloaded jsvm software, and I am getting many errors while compiling. Few of them is as follows.
/usr/include/c++/4.3/bits/algorithmfwd.h:248:41: error: macro "max" passed 3 arguments, but takes just 2
And the file algorithmfwd.h is as follows
template<typename _Tp>
const _Tp&
min(const _Tp&, const _Tp&);
template<typename _Tp, typename _Compare>
const _Tp&
min(const _Tp&, const _Tp&, _Compare);
// min_element
A:
The error is quite explicit:
/usr/include/c++/4.3/bits/algorithmfwd.h:248:41: error: macro "max" passed 3 arguments, but takes just 2
Before inclusion of that particular header, you have defined a macro max that takes 3 arguments. Macros are evil in that they are applied everywhere that the identifier appears. Review where in the code you are defining that macro and remove it, or at the very least change it into upper case (common convention for macros) so that it does not get expanded in all other headers.
A:
Somewhere, you have defined a macro max, which is not allowed if you
include any headers from the standard library (which has a set of
overloaded functions named max). You'll have to find out where this
macro is defined, and get rid of it. Two immediate possibilities come
to mind:
You've defined it as a macro in one of your headers. Get rid of it.
Microsoft defines (or defined—I've not check VC10) both `min` and
`max` as macros in one of its headers. Add /DNOMINMAX to
your compiler options to suppress this.
Some other library you can't control has defined it. Wrap this
libraries headers in private headers, which include the library header,
then do:
#undef min
#undef max
Use these wrappers instead of the library headers you were given (and
pressure the library provider to correct this).
| {
"pile_set_name": "StackExchange"
} |
Q:
pyspark - Implement helper in rdd.map(...)
I have a rdd with pairs of points.
[(((2, 1), 0.5), ((4, 2), (6, 3))),
(((2, 1), -0.6), (-3, 4)),
(((-3, 4), -0.2857142857142857), (4, 2)),
(((-3, 4), -0.6), (2, 1)),
(((-3, 4), -0.1111111111111111), (6, 3)),
(((4, 2), 0.5), ((2, 1), (6, 3))),
(((4, 2), -0.2857142857142857), (-3, 4)),
(((6, 3), 0.5), ((4, 2), (2, 1))),
(((6, 3), -0.1111111111111111), (-3, 4))]
The target rdd would look like this:
[((2, 1), (4, 2), (6, 3)),
((2, 1), (-3, 4)),
((-3, 4), (4, 2)),
((-3, 4), (2, 1)),
((-3, 4), (6, 3)),
((4, 2), (2, 1), (6, 3)),
((4, 2), (-3, 4)),
((6, 3), (4, 2), (2, 1)),
((6, 3), (-3, 4))]
To get there, I am asked to use the helper function:
def format_result(x):
x[1].append(x[0][0])
return tuple(x[1])
Being the spark-noob I am, I was trying to do this:
rbb.map(lambda x: (format_result(x[0][0])))
Needless to say, it does not work.
Can you please help me to implement the helper in my map (if map is the best method).
Here is my traceback:
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<ipython-input-954-dfb7f775ddfb> in <module>
1 #trythis.map(lambda x: ((x[0][0]) + (x[1]))).collect()
----> 2 trythis.map(lambda x: (format_result(x[0][0]))).collect()
/usr/local/opt/apache-spark/libexec/python/pyspark/rdd.py in collect(self)
814 """
815 with SCCallSiteSync(self.context) as css:
--> 816 sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
817 return list(_load_from_socket(sock_info, self._jrdd_deserializer))
818
/usr/local/opt/apache-spark/libexec/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py in __call__(self, *args)
1255 answer = self.gateway_client.send_command(command)
1256 return_value = get_return_value(
-> 1257 answer, self.gateway_client, self.target_id, self.name)
1258
1259 for temp_arg in temp_args:
/usr/local/opt/apache-spark/libexec/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
326 raise Py4JJavaError(
327 "An error occurred while calling {0}{1}{2}.\n".
--> 328 format(target_id, ".", name), value)
329 else:
330 raise Py4JError(
Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 3 in stage 1387.0 failed 1 times, most recent failure: Lost task 3.0 in stage 1387.0 (TID 6426, localhost, executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/worker.py", line 377, in main
process()
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/worker.py", line 372, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/serializers.py", line 393, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/util.py", line 99, in wrapper
return f(*args, **kwargs)
File "<ipython-input-954-dfb7f775ddfb>", line 2, in <lambda>
File "<ipython-input-926-98b4fd321335>", line 2, in format_result
AttributeError: 'int' object has no attribute 'append'
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:456)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:592)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:575)
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:410)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator$class.foreach(Iterator.scala:891)
at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48)
at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310)
at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302)
at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289)
at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28)
at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$13.apply(RDD.scala:945)
at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$13.apply(RDD.scala:945)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Driver stacktrace:
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1889)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1877)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1876)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at scala.Option.foreach(Option.scala:257)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:2082)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:2101)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:2126)
at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:945)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.RDD.collect(RDD.scala:944)
at org.apache.spark.api.python.PythonRDD$.collectAndServe(PythonRDD.scala:166)
at org.apache.spark.api.python.PythonRDD.collectAndServe(PythonRDD.scala)
at sun.reflect.GeneratedMethodAccessor45.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:238)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/worker.py", line 377, in main
process()
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/worker.py", line 372, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/serializers.py", line 393, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/usr/local/opt/apache-spark/libexec/python/lib/pyspark.zip/pyspark/util.py", line 99, in wrapper
return f(*args, **kwargs)
File "<ipython-input-954-dfb7f775ddfb>", line 2, in <lambda>
File "<ipython-input-926-98b4fd321335>", line 2, in format_result
AttributeError: 'int' object has no attribute 'append'
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:456)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:592)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:575)
at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:410)
at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
at scala.collection.Iterator$class.foreach(Iterator.scala:891)
at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28)
at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48)
at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310)
at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302)
at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28)
at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289)
at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28)
at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$13.apply(RDD.scala:945)
at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$13.apply(RDD.scala:945)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
... 1 more
A:
Suppose,
data = [
(((2, 1), 0.5), ((4, 2), (6, 3))),
(((2, 1), -0.6), (-3, 4)),
(((-3, 4), -0.2857142857142857), (4, 2)),
(((-3, 4), -0.6), (2, 1)),
(((-3, 4), -0.1111111111111111), (6, 3)),
(((4, 2), 0.5), ((2, 1), (6, 3))),
(((4, 2), -0.2857142857142857), (-3, 4)),
(((6, 3), 0.5), ((4, 2), (2, 1))),
(((6, 3), -0.1111111111111111), (-3, 4))
]
A slight change to your function
def format_result(x):
if type(x[1][0]) == tuple:
return tuple([x[0][0]] + [*x[1]])
elif type(x[1][0]) == int:
return tuple([x[0][0]] + [x[1]])
And, to your lambda in the map
data_rdd = spark.sparkContext.parallelize(data). \
map(lambda k: format_result(k))
You were trying to append the values to a tuple or int depending on the value in the row. I simply changed it to list and appended the values. And, passed the whole row data[i] to the function.
# [((2, 1), (4, 2), (6, 3)),
# ((2, 1), (-3, 4)),
# ((-3, 4), (4, 2)),
# ((-3, 4), (2, 1)),
# ((-3, 4), (6, 3)),
# ((4, 2), (2, 1), (6, 3)),
# ((4, 2), (-3, 4)),
# ((6, 3), (4, 2), (2, 1)),
# ((6, 3), (-3, 4))]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set focus on first input field using jQuery in IE?
I can set focus on first input, that works in all browsers(except IE):
$('#login').on('shown', function () {
$(login).find('input:visible:first').focus();
})
I need to call it after Bootstrap modal showing will be finished, so I'm calling it in shown function.
Also tried this code(not working):
$('#sign_up').on('shown', function () {
setTimeout(function () {
$(sign_up).find('input:visible:first').focus();
}, 100);
///working everywhere except explorer
$('#login').on('shown', function () {
$('#user_email').focus();
})
A:
javascript
<script type="text/javascript">
function formfocus() {
document.getElementById('element').focus();
}
window.onload = formfocus;
</script>
JAVASCRIPT DEMO
jquery
$(document).ready(function(){
$('#element').focus();
});
JQUERY DEMO
JQUERY FOR IE 8
$(document).ready(function(){
setTimeout(function() {
$('#element').focus();
}, 10);
});
IE 8 DEMO
HTML
<form>
<input id="element" />
<input />
<input />
</form>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to import new matrialized css 1.0 alpha version to angular 4
Need to import new matrialized css 1.0 alpha version to angular 4. I can write below code to make things work
<a onclick="M.toast({html: 'I am a toast'})" class="btn">Toast!</a>
But i want to import the materialized module into the typescript
import {M} from 'materilized-css';
so that i can use in some function
function test() {
// some condition
M.toast({html: 'I am a toast'})
}
I have added the script file path in .angular-cli.json.
"styles": [
"styles.css",
"../node_modules/materialize-css/dist/css/materialize.min.css"
],
"scripts": [
"../node_modules/materialize-css/dist/js/materialize.min.js"
]
How can i do so. Need help in this or there is any other way to make this work.
A:
That's not how it works.
First, you need to add the JS import, either in your index.html file (and you declare your library as an asset), either in your angular-cli.json file.
You should do the latter one. You must put your script into the scripts property of your angular-cli file.
Once it's done, in your components, you need to declare a global variable as so
declare var M: any;
Now in your component, you will have access to this variable, as you would in JS.
If you have any question, feel free to ask !
EDIT In details
angular-cli.json
"styles": [
"You should have some styles in this property",
"Add your dependency like so"
"../node_modules/PATH/TO/MATERIALIZE.css"
],
"scripts": [
"You should have some scripts in this property",
"Add your dependency like so"
"../node_modules/PATH/TO/MATERIALIZE.js"
],
In your component
// First, you have your import zone
import { ... } from '...';
// You put your declare here
declare var M: any;
// Then you have the component
@Component({...})
export class MyComponent implements onInit { ... }
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple case insensitive like comparisons in mysql
I am trying to create a book store search field that matches keywords in a book's title, subtitle, and author columns. I can get a single case insensitive like statement to work, but it seems to not work when I try under multiple columns. Can anyone help me find what is wrong? Or is there an easier way to accomplish this?
$getbooks= mysql_query("SELECT * FROM books WHERE (
LOWER(title) LIKE LOWER('%,".$_GET['search'].",%')
OR LOWER(author) LIKE LOWER('%,".$_GET['search'].",%')
OR LOWER(subtitle) LIKE LOWER('%,".$_GET['search'].",%')
)
AND status='1'
ORDER BY id DESC");
A:
You need to remove the commas in your LIKE clauses:
e.g., instead of :
LIKE LOWER('%,".$_GET['search'].",%')
do this:
LIKE LOWER('%".$_GET['search']."%')
Otherwise you will only match on items that are surrounded by commas!
You should also give some serious credence to the comments indicating SQL Injection attack vulnerability.
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking for Whitespace in FluentValidation
I'm using FluentValidation and trying to create a rule that throws error if there is any whitespace in the string, i.e. for a username.
I've reviewed these SOs, but doesn't seem to work, I'm sure my syntax is off just a little?
What is the Regular Expression For "Not Whitespace and Not a hyphen"
and
What is the Regular Expression For "Not Whitespace and Not a hyphen"
RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Matches(@"/^\S\z/");
or
RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Matches(@"[^\s]");
Neither of these seem to work. Other rules are not empty and between 3 and 15 characters.
A:
Just modifying your original rule a bit
edit Ok, removing delimiters as suggested.
RuleFor(m => m.UserName).NotEmpty().Length(3, 15).Matches(@"\A\S+\z");
All it does is force there to be non-whitespace in the whole string from start to finish.
Alternatively, I guess you could combine them into 1 match as in
RuleFor(m => m.UserName).Matches(@"\A\S{3,15}\z");
| {
"pile_set_name": "StackExchange"
} |
Q:
vue 2.0 Failed to mount component: template or render function not defined
I am using a Laravel Vue setup and pulling in Laravel Elixir, Webpack and laravel-elixir-vue-2 package.
I have looked at several other SO questions and I know this is usually a problem with not referencing the standalone version of vue.js
However, the laravel-elixir-vue-2 package aliases vue to the standalone version so templates can be loaded from .vue files. Still, I get this error every time:
[Vue:Warn] vue 2.0 Failed to mount component: template or render function not defined. (found in component <top> at ../resources/assets/js/components/top.vue)
I can see that vue.js is being pulled in from vue/dist/vue.js?0598:2611 in the console.
Can anyone see what I'm missing?
app.js
import Vue from 'vue'
import top from './components/top.vue'
new Vue({
el: '#app',
components: { top }
})
//I've also tried this:
// new Vue({
// components: {
// top
// },
// render: h => h(top),
// }).$mount('#app')
top.vue
<template>
<div class="top">
<p>hi</p>
</div>
</template>
<script>
export default {};
</script>
index.blade.php
<div>
<div id="app">
<top></top>
</div>
</div>
{!! HTML::script('js/app.js') !!}
package.json
{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
},
"devDependencies": {
"bootstrap-sass": "^3.3.0",
"gulp": "^3.9.1",
"laravel-elixir": "^6.0.0-9",
"laravel-elixir-vue-2": "^0.2.0",
"laravel-elixir-webpack-official": "^1.0.2"
}
}
gulp.js
var elixir = require('laravel-elixir');
elixir.config.sourcemaps = true;
require('laravel-elixir-vue-2');
elixir(function(mix) {
mix.webpack('app.js', 'public/assets/js');
});
Edit: update
Changing the gulp.js syntax fixed my error.
var elixir = require('laravel-elixir')
require('laravel-elixir-vue-2')
elixir(mix => {
mix.webpack('app.js');
mix.styles([
"normalize.css",
"main.css"
]);
});
edit: I added export default {}; to the template script
A:
Like my comment in the question, I had the same problem.
In my case I had two elixir calls like this:
elixir(mix => {
mix.browserSync({
proxy: 'example.dev',
open: false
});
});
elixir(mix => {
mix.sass('app.scss');
mix.webpack('app.js');
});
I don't know why, but the two elixir calls are breaking webpack.
I change my gulpfile to:
elixir(mix => {
mix.sass('app.scss');
mix.webpack('app.js');
mix.browserSync({
proxy: 'example.dev',
open: false
});
});
@retrograde, thx for your hint in your comment :)
Edit:
See this Laravel Elixir Issue
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the right jquery selector to read an input text in the same html table row?
I have the following html:
<table>
<tr>
<td>
<input type="text" class="myTextA" />
</td>
<td>
<input type="text" class="myTextB" />
</td>
<td>
<input type="text" class="myText" />
<span class="mySpan"></span>
</td>
</tr>
<tr>
<td>
<input type="text" class="myTextA" />
</td>
<td>
<input type="text" class="myTextB" />
</td>
<td>
<input type="text" class="myText" />
<span class="mySpan"></span>
</td>
</tr>
<tr>
<td>
<input type="text" class="myTextA" />
</td>
<td>
<input type="text" class="myTextB" />
</td>
<td>
<input type="text" class="myText" />
<span class="mySpan"></span>
</td>
</tr>
</table>
I have the following jquery where i am looping through the class selector and i need to reference another textbox in the same row and get the val of that other textbox:
$('.myText').each(function (index, data)
{
$(data).val("Test");
//I now need to reference the val() of the "myTextA" that is in the same row as the item
});
How can i reference this inside this loop to grab to respective input text in the same row?
A:
You can use .closest() to find the tr then use .find() to target the desired input element
$('.myText').each(function (index, data) {
$(data).val("Test");
$(this).closest('tr').find('.myTextA').val("Test 2");
//I now need to reference the val() of the "myTextA" that is in the same row as the item
});
Demo:
$('.myText').val(function (i) {
return i;
})
$('.myText').each(function (index, data) {
//value from .myText is copied to .myTextA, just to demonstrate that the element is read
$(this).closest('tr').find('.myTextA').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" class="myTextA" />
</td>
<td>
<input type="text" class="myTextB" />
</td>
<td>
<input type="text" class="myText" /> <span class="mySpan"></span>
</td>
</tr>
<tr>
<td>
<input type="text" class="myTextA" />
</td>
<td>
<input type="text" class="myTextB" />
</td>
<td>
<input type="text" class="myText" /> <span class="mySpan"></span>
</td>
</tr>
<tr>
<td>
<input type="text" class="myTextA" />
</td>
<td>
<input type="text" class="myTextB" />
</td>
<td>
<input type="text" class="myText" /> <span class="mySpan"></span>
</td>
</tr>
</table>
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I parse a YAML file from the web using PyYAML?
I need to get a YAML file from the web and parse it using PyYAMl, but i can't seem to find a way to do it.
import urllib
import yaml
fileToBeParsed = urllib.urlopen("http://website.com/file.yml")
pythonObject = yaml.open(fileToBeParsed)
print pythonObject
The error produced when runing this is:
AttributeError: 'module' object has no attribute 'open'
If it helps, I am using python 2. Sorry if this is a silly question.
A:
I believe you want yaml.load(fileToBeParsed) and I would suggest looking at urllib2.urlopen if not the requests module.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I import .dll library from subfolder in C#
When I have the library in the same folder as app I can simply:
[DllImport("kernel32")]
public extern static IntPtr LoadLibrary(string librayName);
IntPtr iq_dll = LoadLibrary("IQPokyd.dll");
I also have this in my app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="plugins;" />
</assemblyBinding>
</runtime>
</configuration>
I'm able to load this library. Problem is that it is using some config files which needs to be in app run directory. Is there some possibility how to tell the library that files it needs are in the same folder as the library?
A:
Since the DLL searches for the config in the current directory, it makes sense to temporarily change the current directory before loading it:
string saveCurDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(Path.Combine(Application.StartupPath, "plugins"));
IntPtr iq_dll = LoadLibrary("IQPokyd.dll");
Directory.SetCurrentDirectory(saveCurDir);
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL - insert into table if value exists in another table
I am trying to get the sql query below to work but I am getting an error, my problem is as follows:
I need to loop through a results set from a select statement (this part is fine). Inside the loop for each row I need to check if the URL exists in tableA. If it does then insert a mapping into tableB, otherwise insert a new row into tableC.
This is what I have but when I try to execute I get an error on the line with the IF saying ORA-06550: line 8, column 15:PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:( - + case mod new no.....
DECLARE
STANDARD_LINK_ID TABLEB.LINK_ID%type;
BEGIN
FOR LINK_ROW IN ( SELECT LINKTEXT, LINKURL, CORPID FROM OLD_DATA)
LOOP
IF (SELECT COUNT(URL) FROM TABLEA WHERE URL = LINK_ROW.LINKURL) = 1
THEN
SELECT LINKID INTO STANDARD_LINK_ID FROM TABLEA WHERE URL = LINK_ROW.URL;
INSERT INTO TABLEB(LINK_ID, CORP_ID)
VALUES (STANDARD_LINK_ID, LINK_ROW.CORPID);
ELSE
INSERT INTO TABLEB(LINK_ID, LINK_NAME, URL, CORP_ID)
VALUES (SEQ_LINK.NEXTVAL, LINK_ROW.LINKTEXT, LINK_ROW.LINKURL,
LINK_ROW.CORP_ID);
END IF;
END LOOP;
COMMIT;
END;
A:
I've seen it done this way; but not the select with return value embeded in the condition
https://forums.oracle.com/forums/thread.jspa?threadID=177035
DECLARE
STANDARD_LINK_ID TABLEB.LINK_ID%type;
DECLARE W_LINK_COUNT NUMBER (1,0);
BEGIN
FOR LINK_ROW IN ( SELECT LINKTEXT, LINKURL, CORPID FROM OLD_DATA)
LOOP
SELECT COUNT(URL) INTO W_LINK_COUNT FROM TABLEA WHERE URL = LINK_ROW.LINKURL;
IF W_LINK_COUNT = 1
THEN
SELECT LINKID INTO STANDARD_LINK_ID FROM TABLEA WHERE URL = LINK_ROW.URL;
INSERT INTO TABLEB(LINK_ID, CORP_ID)
VALUES (STANDARD_LINK_ID, LINK_ROW.CORPID);
ELSE
INSERT INTO TABLEB(LINK_ID, LINK_NAME, URL, CORP_ID)
VALUES (SEQ_LINK.NEXTVAL, LINK_ROW.LINKTEXT, LINK_ROW.LINKURL,
LINK_ROW.CORP_ID);
END IF;
END LOOP;
COMMIT;
END;
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the phrase "then too" incorrect?
I was told by a school teacher that it was incorrect. I've seen it in articles coming from reputable sources. The general meaning would be similar to the word 'yet', but I can't find any place to confirm whether or not it is correct.
A:
In my dialect I'd say, "then again" but I've seen it as "then too" occasionally. In some contexts I can see them being similar to "yet".
Both are informal and as such I wouldn't call either of them unacceptable if it's an informal context.
I'd recommend neither in a formal setting.
A:
"Then too" is a familiar construction, unexceptional and unexceptionable. Sometimes it is written "Then, too, [...]" but the commas are not necessary.
It functions as a sentence adverb, asking the listener or reader to consider new material in the context of an already established line of discourse. It is, as you say, similar to yet, but has a somewhat less contradictory quality. Consider:
All of us were adept at tennis, squash, and badminton. Then too we didn't limit ourselves to racquet sports.
All of us were adept at tennis, squash, and badminton. Yet we didn't limit ourselves to racquet sports.
No. 1 has a more casual feel to it, as if the new thought introduced by the second sentence was merely an add-on or an afterthought. It is the rhetorical equivalent of thinking out loud.
No. 2 feels more strenuous. It is making a point that should not escape notice, possibly forestalling someone's foolish and ungenerous presupposition that the group was not well-rounded in the matter of sport.
Whatever teacher told you "then too" is "wrong" is falling into the prescriptivist trap that ensnares the minds of so many in that profession. How you deal with it is simple: If you have to hand in a paper to that teacher, avoid using the phrase. For all other matters, use it in good health whenever the hell you feel like doing so.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need a main to create a static library?
I have these modules
sum_module.h
int sum(int x, int y);
tim_module.h
int tim(int x, int y);
I want to create a module called myModule.lib that allows me to use these function in my main program. The idea is to add myModule.lib to the main project and include myModule.h
My question is : When I create the library (myModule.lib), does it contain a main.c and a main.h ? if yes, is main.h equivalent to myModule.h ? What should I put in the main.c ?
A:
your static library is a set of services, so it comes with a header file containing the protoype of the functions you want to expose to the outside. If you don't put a main symbol here, well, noone will put one for you fortunately.
(note that the filename isn't relevant, it's the symbol name which is relevant: main)
It's technically possible to put a main in it (some building tools create a .a file and link with the runtime to create an executable), but as a library of services, that would conflict with any application trying to link with it, that application also having a main.
So leave out the main function as we know it (the famous int main(int argc, char**argv)) out of your library (you can add a selftest entrypoint if you want). Creating a static library doesn't involve any linking, and creating a dynamic library doesn't require a main, just full symbol resolution and entrypoints.
A:
To answer your question it may be worthwile to understand what the basic meaning of compiling and linking a C program from source is, and how libraries come into play.
Compiling a source file creates an object file which you can imagine as "structured machine code". It is structured in that it contains symbols — named variables and named functions. These symbols are essentially labeled memory addresses containing data or machine instructions (namely functions) which can be read or jumped to from other code.
Tools like nm and objdump can be used to inspect object files and list these symbols.
Producing a runnable, statically linked program consists of the two known steps, compiling (producing object files from source files) and linking ("glueing" object files together and performing some magic to produce one runnable entity).1 The linker "resolves" calls to functions in other object files by computing the numerical addresses in the final program to jump to. If such a function is not found, one logically gets the "undefined symbol" error.
A simple static library now is literally nothing more than a concatenation of object files with an index of the symbols it contains. It's that simple. In other words, instead of linking with ld -o output /lib/crt0.o hello.o sum.o tim.o -lc (using the object files coming from an earlier compilation of sum.c and tim.c) you call the archiver ar to produce a static library my_module.a with these two object files in it: ar rcs my_module.a sum.o tim.o Then in the link phase you use this library in place of the two object files: ld -o output /lib/crt0.o hello.o my_modules.a -lc will resolve calls of sum and tim from hello.o with the symbols in that library.
So will you need a main in your library? No. Why would you? You need a main in that library not any more than you need one in sum.c or tim.c (we assume that you have a main in hello.c). Would it hurt? Possibly; linkers complain about "duplicate symbols" because there's no way for them to tell which one is the intended one. Many linkers offer an option to ignore that error and use the first symbol encountered, but normally that's only a workaround until the build process is clean.
1 Often the two steps are controlled by the "compiler driver" program, e.g. gcc, or by a make file or IDE. I haven't actually called the linker ld "manually" in a while. But the purpose here is to give an understanding of the process because that will enable you to answer your own question.
| {
"pile_set_name": "StackExchange"
} |
Q:
DD/DU warnings from PMD
Possible Duplicate:
What is the reason for these PMD rules?
Why do I get DD/DU warnings?
Here's my code:
// DD warning from PMD
public Object foo() {
Object result = null;
if (condition) {
// code block, no accec to result
result = newResult;
}
return result;
}
// DU warning from PMD
List<Object> data = new ArrayList<Object>(anotherList);
anotherList.remove(1);
// some other modification of anotherList
if (condition) {
// some code. no access to data
for (Object o : data) {
// loop for original content of the list
}
}
Is there something wrong here? Or is it a PMD bug? Can I ignore these warnings?
A:
Your DD anomaly can indeed be written better, with less chance of bugs:
return condition? newResult : null;
or, if you are more conservative regarding syntax,
if (condition)
return newResult;
return null;
In the second example you are creating data unconditionally, but using it only conditionally. Rewrite to
if (condition) {
List<Object> data = new ArrayList<>(anotherList);
// or maybe just use anotherList without copying
...
}
else {
anotherList.remove(1);
// some other modifications of anotherList
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isnt else if statement working?
JavaScript
function AdultNumber(){ /* Ticket Number Validation */
var AdInput = $("#adult").val();
if (AdInput > 0 ){
document.getElementById("AdTickError").textContent = "";
return true;
} else if( AdInput > 20) {
confirm("You sure you want 20+ Passengers?");
return true;
} else {
document.getElementById("AdTickError").textContent = "Incorrect Enter Correct Number Of Passengers";
return false;
}
}
HTML:
<label for="Adult-ticket" class="center-label">Adults(+16)</label>
<input type="number" id="adult" name="user_adult">
<label id = "AdTickError"></label>
Why does it not display confirm box if user inputs over 20? I want it that if user chooses 20 or over an confirm box prompts asking user if they want to continue.
A:
You may want to change this condition:
if (AdInput > 0 )
to this:
if (AdInput > 0 && AdInput <= 20){
| {
"pile_set_name": "StackExchange"
} |
Q:
SMPS Error Amplifier Behavior
In case of switch mode power supplies, we uselly use "Error Amplifiers" (Type 1,2 & 3), my question is:
The output voltage of this amplifier (Verr), is it the DC error of the Vref and Vout (i.e: Verr=A(Vout-Vref), A is the DC gain of the error amplifier)? if is not, please explain to me what is it and what is the role of DC gain in that case??
simulate this circuit – Schematic created using CircuitLab
A:
(paraphrased) Is the output of the error amplifier a DC error (i.e., \$ V_{err} = A (V_{out} - V_{ref})\$?
No. Now would be a good time to find some reference material on op-amp circuit design and do some studying.
The "error amplifier" is a PI controller with some band-limiting on the proportional term. The band limiting is almost certainly there to reduce the amount of ripple in the output and avoid sub-harmonic oscillation.
Moreover, the error amplifier is inverting: the higher that \$V_{out} - V_{ref}\$ gets, the faster \$V_{err}\$ will trend downward.
You can tell this by looking at the feedback network: there is not a DC path from \$V_{err}\$ to the \$V_-\$ input of the op-amp: both paths have blocking capacitors. That means that the output always integrates.
It is likely that the R4*C2 time constant is chosen to be longer than the PWM frequency, but shorter than the desired settling time of the power supply. C3 and R4 are chosen to stabilize the supply while having it respond as rapidly as possible to variations in the load.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mercurial Repo Living Archive
We have an Hg repo that is over 6GB and 150,000 changesets. It has 8 years of history on a large application. We have used a branching strategy over the last 8 years. In this approach, we create a new branch for a feature and when finished, close the branch and merge it to default/trunk. We don't prune branches after changes are pushed into default.
As our repo grows, it is getting more painful to work with. We love having the full history on each file and don't want to lose that, but we want to make our repo size much smaller.
One approach I've been looking into would be to have two separate repos, a 'Working' repo and an 'Archive' repo. The Working repo would contain the last 1 to 2 years of history and would be the repo developers cloned and pushed/pulled from on a daily basis. The Archive repo would contain the full history, including the new changesets pushed into the working repo.
I cannot find the right Hg commands to enable this. I was able to create a Working repo using hg convert <src> <dest> --config convert.hg.startref=<rev>. However, Mecurial sees this as a completely different repo, breaking any association between our Working and Archive repos. I'm unable to find a way to merge/splice changesets pushed to the Working repo into the Archive repo and maintain a unified file history. I tried hg transplant -s <src>, but that resulted in several 'skipping emptied changeset' messages. It's not clear to my why the hg transplant command felt those changeset were empty. Also, if I were to get this working, does anyone know if it maintains a file's history, or is my repo going to see the transplanted portion as separate, maybe showing up as a delete/create or something?
Anyone have a solution to either enable this Working/Archive approach or have a different approach that may work for us? It is critical that we maintain full file history, to make historical research simple.
Thanks
A:
You might be hitting a known bug with the underlying storage compression. 6GB for 150,000 revision is a lot.
This storage issue is usually encountered on very branchy repositories, on an internal data structure storing the content of each revision. The current fix for this bug can reduce repository size up to ten folds.
Possible Quick Fix
You can blindly try to apply the current fix for the issue and see if it shrinks your repository.
upgrade to Mercurial 4.7,
add the following to your repository configuration:
[format]
sparse-revlog = yes
run hg debugupgraderepo --optimize redeltaall --run (this will take a while)
Some other improvements are also turned on by default in 4.7. So upgrade to 4.7 and running the debugupgraderepo should help in all cases.
Finer Diagnostic
Can you tell us what is the size of the .hg/store/00manifest.d file compared to the full size of .hg/store ?
In addition, can you provide use with the output of hg debugrevlog -m
Other reason ?
Another reason for repository size to grow is for large (usually binary file) to be committed in it. Do you have any them ?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is my interpretation of the p-value and confidence interval correct?
Background:
let's say I have a website with a big buy button on it and I preformed an A/B testing with the following result:
Version A (control): conversion rate 5%
Version B (variation): conversion rate 8%
Significant level: 5%
Confidence interval: +/- 1%, (8%-5%) = 3% thus the bound is (2%, 4%)
p-value: 0.02
Null hypothesis: the conversion rate of the control group is the same as the conversion rate of the variation.
Alternative hypothesis:the conversion rate of the control group is different from the conversion rate of the variation.
I made up the numbers above but here is how I would calculate these values:
$$ z = \frac{P_{A} - P_{B}} {\sqrt{\frac{P_A(1-P_A)}{n_A} + \frac{P_B(1-P_B)}{n_B}}} $$
$P_A$: the conversion rate for the control
$P_B$: the conversion rate for the variation
$n_A$: the number of visitors who saw the control
$n_B$: the number of visitors who saw the variation
The formula above is based on the independent two-sample t-test:
$$ t= \frac{\bar{X_A} - \bar{X_B}}{\sqrt{\frac{{S_A}^2}{n_A} + {\frac{{S_B}^2}{n_B}}}}$$
Because click conversion rate is essentially a Bernoulli trial, so it follows the Bernoulli distribution.
With Bernoulli distribution, the variance is calculated as $p(1-p)$, thus replacing ${S_A}^2$ with $p(1-p)$ gives the formula for calculating $z$ above.
My interpretation of the p-value:
Assuming there is no difference between the conversion rate of the control and variation, there is only a 2% chance (1 - p-value) that we observe a difference like we have seen. Thus, there are two explanations:
We've only experimented once and we observed something that only happens less than 5% of the time. Theoretically speaking, it is possible to get such extreme data on the first try. If I reject the null hypothesis incorrectly, I am running an extreme low risk of making the type I error.
We've only experimented once and we observed something that only happens less than 5% of the time, so this must not be luck and we should conclude that the difference is real. Thus, the variation group is indeed different from the control group.
My interpretation of the confidence interval:
If we were to repeat the same experiment 100 times (with 100 different group of people testing both versions), then we should expect to see the true difference between the two groups appear in 95 of those experiments.
We think we are the 95%, and if that is true, then the true difference lay somewhere between 2% and 4%.
But there is also a 5% chance that the range (2%, 4%) completely misses the true difference.
We could also be the 5%, such that the range (2%, 4%) does not contain the true difference.
Is my interpretation of the p-value and confidence interval correct?
A:
Your last claim is wrong. There is not a 5% chance that your range 2% to 4% misses the mark. It either misses or it does not, 0% or 100%; you just don't know.
The p-value also assumes you met the assumptions of the statistical test you conducted if you are being pedantic.
For claim number 2, you shouldn't ever conclude definitively from one study. But you have evidence to suggest that the difference is there.
Additionally, this decision to claim there is a difference only happens less than 5% of the time (given an $\alpha$ of .05) only if the effect is literally zero.
The p-value is not the probability of making a type-I error. Before a study is conducted, the chosen $\alpha$-level is. After the study is conducted, you either have made or you have not made a type-I error.
I might rewrite 1 thus:
We've only experimented once and we observed something that only happens less than 5% of the time if the null is true. I may be in the 5% of people who will make an error of claiming a difference from the null when there is none. Thus, if I reject the null, I may have made a type-I error.
I might rewrite 2 thus:
We've only experimented once and we observed something that only happens less than 5% of the time if the null is true. Hence, this is evidence to suggest that the null is unlikely to be true. And we may conclude that there is a difference between the control group and variation group that is not due to sampling error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Interop -- Netty + Clojure
I'm trying to use netty via clojure. I'm able to startup the server, however, it fails to initialize an accepted socket. Below are the error message and code respectively. Does anyone know what is/or could be wrong? I believe the issue is with (Channels/pipeline (server-handler)) Thanks.
Error Message
#<NioServerSocketChannel [id: 0x01c888d9, /0.0.0.0:843]>
Jun 6, 2012 12:15:35 PM org.jboss.netty.channel.socket.nio.NioServerSocketPipelineSink
WARNING: Failed to initialize an accepted socket.
java.lang.IllegalArgumentException: No matching method found: pipeline
project.clj
(defproject protocol "1.0.0-SNAPSHOT"
:description "Upload Protocol Server"
:dependencies [
[org.clojure/clojure "1.2.1"]
[io.netty/netty "3.4.5.Final"]])
core.clj
(ns protocol.core
(:import (java.net InetSocketAddress)
(java.util.concurrent Executors)
(org.jboss.netty.bootstrap ServerBootstrap)
(org.jboss.netty.channel Channels ChannelPipelineFactory SimpleChannelHandler)
(org.jboss.netty.channel.socket.nio NioServerSocketChannelFactory)
(org.jboss.netty.buffer ChannelBuffers)))
(def policy
"<content>Test</content>")
(defn server-handler
"Returns netty handler."
[]
(proxy [SimpleChannelHandler] []
(messageReceived [ctx e]
(let [ch (.getChannel e)]
(.write ch policy)
(.close ch)))
(channelConnected [ctx e]
(let [ch (.getChannel e)]
(.write ch policy)
(.close ch)))
(exceptionCaught [ctx e]
(let [ex (.getCause e)]
(println "Exception" ex)
(-> e .getChannel .close)))))
(defn setup-pipeline
"Returns channel pipeline."
[]
(proxy [ChannelPipelineFactory] []
(getPipeline []
(Channels/pipeline (server-handler)))))
(defn startup
"Starts netty server."
[port]
(let [channel-factory (NioServerSocketChannelFactory. (Executors/newCachedThreadPool) (Executors/newCachedThreadPool))
bootstrap (ServerBootstrap. channel-factory)]
(.setPipelineFactory bootstrap (setup-pipeline))
(.setOption bootstrap "child.tcpNoDelay" true)
(.setOption bootstrap "child.keepAlive" true)
(.bind bootstrap (InetSocketAddress. port))))
A:
There are three problems with your code
Java interop with vararg Channels.channel() method.
you can make a vector of channel handlers and wrap it with (into-array ChannelHandler ..)
You can not write String objects directly to a Netty Channel.
you have to write the string to a ChannelBuffer first and write that buffer or use a StringCodecHandler.
Writing to Netty channel is asynchronus, so you can not close it immediately.
you have to register a future listener and close the channel when its done.
Here is the working code.
(ns clj-netty.core
(:import (java.net InetSocketAddress)
(java.util.concurrent Executors)
(org.jboss.netty.bootstrap ServerBootstrap)
(org.jboss.netty.buffer ChannelBuffers)
(org.jboss.netty.channel Channels ChannelFutureListener ChannelHandler ChannelPipelineFactory SimpleChannelHandler)
(org.jboss.netty.channel.socket.nio NioServerSocketChannelFactory)
(org.jboss.netty.buffer ChannelBuffers)))
(def policy
(ChannelBuffers/copiedBuffer
(.getBytes "<content>Test</content>")))
(defn server-handler
"Returns netty handler."
[]
(proxy [SimpleChannelHandler] []
(messageReceived [ctx e]
(let [ch (.getChannel e)]
(.addListener
(.write ch policy)
(ChannelFutureListener/CLOSE))))
(channelConnected [ctx e]
(let [ch (.getChannel e)]
(.addListener
(.write ch policy)
(ChannelFutureListener/CLOSE))))
(exceptionCaught [ctx e]
(let [ex (.getCause e)]
(println "Exception" ex)
(-> e .getChannel .close)))))
(defn setup-pipeline
"Returns channel pipeline."
[]
(proxy [ChannelPipelineFactory] []
(getPipeline []
(let [handler (server-handler)]
(Channels/pipeline (into-array ChannelHandler [handler]))))))
(defn startup
"Starts netty server."
[port]
(let [channel-factory (NioServerSocketChannelFactory. (Executors/newCachedThreadPool) (Executors/newCachedThreadPool))
bootstrap (ServerBootstrap. channel-factory)]
(.setPipelineFactory bootstrap (setup-pipeline))
(.setOption bootstrap "child.tcpNoDelay" true)
(.setOption bootstrap "child.keepAlive" true)
(.bind bootstrap (InetSocketAddress. port))))
Have a look at Aleph (also uses Netty) which can used to build clients and servers in many different protocols with nice Clojure API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing struct from unmanaged C++ to C#
Note: The final working solution is after the edit!
I hope someone can help me with a problem I've been trying to solve for the last few days.
I am trying to pass a struct from a unmanaged C++ DLL to a C# script. This is what I have so far:
C++
EXPORT_API uchar *detectMarkers(...) {
struct markerStruct {
int id;
} MarkerInfo;
uchar *bytePtr = (uchar*) &MarkerInfo;
...
MarkerInfo.id = 3;
return bytePtr;
}
C#
[DllImport ("UnmanagedDll")]
public static extern byte[] detectMarkers(...);
...
[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 1)]
public struct markerStruct
{
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(0)]
public int Id;
}
...
markerStruct ByteArrayToNewStuff(byte[] bytes){
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
markerStruct stuff = (markerStruct)Marshal.PtrToStructure(
handle.AddrOfPinnedObject(), typeof(markerStruct));
handle.Free();
return stuff;
}
...
print(ByteArrayToNewStuff (detectMarkers(d, W, H, d.Length) ).Id);
The problem is that this works, but the value printed is completely off (sometimes it prints around 400, sometimes max int value).
I'm guessing that there's something wrong with how I marshalled the struct in C#. Any ideas?
Edit:
This is the working solution using ref:
C++
struct markerStruct {
int id;
};
...
EXPORT_API void detectMarkers( ... , markerStruct *MarkerInfo) {
MarkerInfo->id = 3;
return;
}
C#
[DllImport ("ArucoUnity")]
public static extern void detectMarkers( ... ,
[MarshalAs(UnmanagedType.Struct)] ref MarkerStruct markerStruct);
...
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MarkerStruct
{
public int Id;
}
...
detectMarkers (d, W, H, d.Length, ref markerInfo);
print( markerInfo.Id );
A:
You're returning a pointer to a local variable which has already been destroyed before .NET can read it. That's a bad idea in pure C++ and a bad idea with p/invoke.
Instead, have C# pass a pointer to a structure (just use the ref keyword) and the C++ code just fill it in.
A:
The MarkerInfo variable is local and goes out of scope when the function returns.
Don't return pointers to local variables, the objects they point to won't exist anymore.
| {
"pile_set_name": "StackExchange"
} |
Q:
Whitespace woes in Regex
I am using a simple Perl script to parse XML and convert it to usable SQL. My current SQL lines go something like this:
INSERT INTO table VALUES ('data1', 'data2', 'data3', );
Obviously I need to remove the comma at the end there. Sounds simple but I just can't get regex to find it. I tried s/,\s+\)/\)/ but that doesn't change anything when I run it. Strangely, s/,\s+/WTF/ doesn't modify anything either, when it should be replacing all the commas and the spaces next to them. BUT when I run s/\s+\)/something/ it correctly finds and replaces the close parentheses at the end of the line. So apparently the whitespace character right after the commas is some strange ghost character that I can't find by any means. Not even with the . expression.
What's really weird though is when I use Find on the document in Notepad++ with the Regular Expression option, it finds all of them perfectly when I enter ,\s+\) yet the exact same sequence in Perl regex will not find them.
I suspected it was something with \r (I'm using Windows) since I previously removed the \n characters but it won't find a \r in the whole sql file.
Thank you in advance for your help this is really puzzling me.
A:
First off,
$ perl -E 'my $foo = "bar, baz"; $foo =~ s/,\s+/WTF/; say $foo'
barWTFbaz
It does work. (For perl 5.8 and before, change that to -e and print "$foo\n")
Second, you're doing it wrong. Instead of doing something like:
$values = "'$values[0]', ";
$values .= "'$values[1]', ";
⋮
you should do:
$values = join(q{,}, map("'$_'", @values)); # map adds 'quotes'; join adds commas
Third, you shouldn't even do that, you should use placeholders:
# note specifying the column names, its a good idea! Schema change.
my $query = "INSERT INTO table (col1, col2, col3) VALUES (?,?,?)";
my $sth = $dbh->prepare($query);
$sth->execute(@values);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I cancel my plane tickets to Russia after obtaining a Russian visa?
I want to get a Russian tourist visa to take the Trans Mongolian express from Beijing. However I will not book my train tickets in advance.
Can I book flights to get my visa, cancelling them afterwards to enter/exit Russia by train?
A:
You do not need the tickets to obtain your visa, you only need a confirmation that you'll be hosted as a tourist. This usually is a hotel booking voucher or some similar document, you should contact your consulate for more detailed information.
All in all, hotel booking can be easily canceled, usually without any cost, if you do it in advance.
| {
"pile_set_name": "StackExchange"
} |
Q:
call jsp from javascript with parameter
i have created a button on its onclick() event i call a method
<script type="text/javascript">
validate()
{
.....
window.location='reg.jsp';
}
</script>
it doesn't take any value of the textbox to the reg.jsp page
If i use <form action="reg.jsp" method="POST"> it takes the value of textbox to the next page but i can't do the things which are to be executed in validate() method
provide a solution which may help to redirect to next page with value of textbox
A:
Use <form action="reg.jsp" method="POST"> and call validate() function onsubmit of your form.Return true if form is valid else return false.Returning false from validate() will prevent your form from being submitted.
<form action="reg.jsp" method="POST" onsubmit="return validate()">
...
...
<input type="submit" value="Submit">
</form>
| {
"pile_set_name": "StackExchange"
} |
Q:
Arial, Courier New and Times screen fonts suddenly fuzzy/unreadable
UPDATE: thanks to the Rubber Duck effect, I just stumbled upon this note. It is a known problem: if you have Windows XP and either manually or with some "hack" managed to download the Windows Update of February 9th, 2015, Arial and Courier get screwed.
Windows Vista Users: the same applies, but since Vista is still supported, it happens automatically and always (unless you uninstall the KB3013455 update, and disable it from Windows Update before it self-reinstalls).
Original question
I have an older PC with XP Pro SP3 installed.
All of a sudden two fonts (at least), Arial and Courier New, started looking different. Arial is tolerable if a bit fuzzy; curves sprouted extra pixels, and some characters have enlarged elements (for example the horizontal bar of the 4 is two pixels tall, the bar from the 5 is one pixel only). Courier New has become pretty horrible, and seems to be actually missing whole horizontal scan lines.
The extra pixels would make one think of ClearType but those settings are correct (and unchanged since ages ago), and the usual voodoo of setting them to wrong values and then back to the correct ones avails nothing.
I checked several other questions and solutions that looked promising but nothing seems to work.
Thinking that the fonts had gotten damaged somehow (all others appear OK - I switched from Courier New to Consolas wherever possible) I replaced them with backup copies. Then I also reverted the system back to a configuration of one week ago, which was surely working. To no apparent effect.
Deleting the font cache (C:\WINDOWS\system32\FNTCACHE.DAT) has it reappear somewhat smaller (as expected) on next reboot, but does not fix the problem.
The PC is otherwise working properly and all other fonts render as they always did; I managed to retrieve a screenshot of two months ago with some text in several fonts, and by rewriting the same words compared the two images, which are identical pixel per pixel (unfortunately the screenshot did not include either Arial or Courier New - but, to know that those two aren't OK, I need no test).
I'm really at a loss as to what could be causing this.
A:
It turns out that Windows did not parse too accurately all the fields and data structures within True Type fonts, and it is therefore possible for a naughty "font" to present invalid information to Windows and making it crash or, theoretically, seizing control and executing malicious code.
And since it's possible to embed a True Type font in a web site, this has some very disturbing implications - especially since most antiviruses don't usually examine fonts too closely. You visit a web site, or perhaps just a web page containing an advertising HTML banner with its own fonts, and bang!, pwn3d.
So quite correctly KB3013455 fixes this, adding several more checks; and naughty fonts can no longer do anything.
Except that... what would happen if some system fonts failed those same checks, or contained information that was slightly off, and nobody had ever realized it because the required checks and settings were never put in place?
It would happen that those slightly and unintentionally naughty fonts, and no others, would suddenly start misbehaving -- reporting to the system sizes and hints that were never reported before. And they would look slightly bad - Arial - or almost unreadable - Courier New.
Until a new fix supplied a "properly behaved" version of both sets of font files (there's eight of them, I think - normal, italic, bold, and bold italic, two each).
That's what happened.
Until the new fix, the choice is:
Replace the two fonts with suitable alternatives in all affected programs. Segoe UI and Consolas work for me (I've also heard good things of a free font called Inconsolata). For some browsers, it is possible to setup a font replacement via plugins or settings. Wait for the fixed fonts to come up. Ideally, it shouldn't take long. In the interim, the PC is protected against a "font attack". RECOMMENDED.
to fix Firefox: locate the userContent.css file in your Firefox profile. If there is no such file, locate the AppData\Mozilla\Firefox\Profiles\RANDOM_STRING\chrome directory and create a file called userContent.css. In this file place (or add if it already exists)
@font-face {
font-family: 'Arial'; src: local('Segoe UI');
}
@font-face {
font-family: 'Courier New'; src: local('Consolas');
}
@font-face {
font-family: 'Times New Roman'; src: local('Linux Libertine');
}
(Of course the "local" fonts must be installed!).
Uninstall the KB3013455 fix (and remain vulnerable). Except maybe you can't.
easy: KB3013455 is present in Control Panel, Applications, [x] Show Updates, Sort by Date, and look for January or February 2015. Uninstall (*). But depending on (#) it might not be there.
almost as easy: Start > Accessories > System Utilities > System Restore, and restore a previous configuration. You should see "Software Distribution Service". Choose the "System Shutdown" checkpoint before that. Reboot, and you're done (*). Depending on (#) you might not have Restore Points available.
difficult. Retrieve a copy of win32k.sys from before January 2015 from some full backup. Boot from a Linux boot disk or Windows Rescue disk. Rename the existing win32k.sys to win32k.xyz, copy the good win32k.sys into C:\WINDOWS\SYSTEM32, reboot and hope it works.
(*) At the next boot or soon after, the system will ask for an update of one or more packages, and you will need to not install KB3013455 and check "Do not ask me in the future". If (#) forces an update without telling anything, or the fonts look good but revert to being fuzzy after one or more further reboots, (#) is the culprit, but how to make things work out depend on its nature.
(#) Windows XP cannot update since it's end of life. Why is it updating? Because there are ways to keep the thing alive long after it should be dead. One such fix that I found is to have it report being "WEPOS System", a XP flavour used for ATMs that's supported for some more years (?), with a registry "fix". Another way is to have a utility that pulls the updates from somewhere - the WEPOS Windows Update site perhaps, or some virus lord's basement tank - and trick XP into believing it's the official Windows Update service. Whatever it is that updates Windows, you need to tell it to leave KB3013455 alone.
Update: things "fixing/updating" XP you may have to thank for the Arial/Courier/Times mess
This is a list of possible causes of more or less silent update(s) to an end-of-lifed XP:
The "WEPOS" registry hack.
Something related to McAfee (reported by @rboblenz). I've found some articles relating to an "unability to update XP", which would seem to imply that McAfee has some ability of updating XP, but nothing clearly stated in their site. Even so, if you have a McAfee product, that might be the explanation.
A couple of tools that allow(ed) to have a pirated copy of XP and keep it updated and, apparently, keep it updated after EOL downloading updates from... somewhere. (And who wouldn't feel comfortable in trusting their data - bank account credentials possibly included - to such solutions? After all, what's the worst that might happen?)
| {
"pile_set_name": "StackExchange"
} |
Q:
eclipse navigate showing java source in directory hierachy instead of package
Due to some reason I found, when displaying the source ,my navigator changed from the right side (preferred) to the left side , which need more clicks to access the source file. I remembered that I did accept some chance unconsciously which result in this unpleasant change but can not find a way go back...
Thanks for your help!
A:
Your best friend in eclipse is CTRL+3 (quick access), press that and then search for what you want, try perspectives and views, see below.
Perspectives
Check what perspective you are in (now). In the top right of eclipse there is a list of perspectives. Sometimes when you carry out an action it asks you if you want to change perspectives. This can change your views/layouts. You might want the Java or Java EE perspective.
views
There are multiple views of your files. What is the name of the tab where ComputeBench is showing up? Try opening the "Project Explorer" or the "Package Explorer" views.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Categorise Images in GridView to make Custom Gallery
I have made few Gallery modules by using GridView i have used this tutorial: http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/,
but now this time i want to make it more custom for my usage, i want to Categories Images, Please see below Screen Shot
I will be use static images under specific Categories
How to make this kind of Image Gallery:
A:
I have never tried, but i have found this sample code, and please try to custom it as you like:
http://blog.blundell-apps.com/infinite-scrolling-gallery/
| {
"pile_set_name": "StackExchange"
} |
Q:
Need help understanding Windows DNS, DHCP and dynamic PTRs
I have inherited management of a set of AD servers running AD-backed DNS. One of them is running DHCP.
For IP ranges which are served by this Windows DHCP server, the in-addr.arpa zones are being served authoritatively by the AD DNS servers to allow AD to be happy with itself and allow dynamic DNS to work properly.
For each of these in-addr.arpa zones, I am also pulling secondary from my unix/linux name servers running BIND9.
I have begun frequently seeing errors like this in my logs on the *nix servers:
Jun 8 13:40:07 ns1 named[6083]: general: warning: '3.37.19.172.in-addr.arpa/PTR/IN': TTL differs in rdataset, adjusting 900 -> 1200
I understand from a technical, DNS-perspective what is happening here. There are >1 records for the 3.37.19.172.in-addr.arpa and they have different TTLs. BIND is normalizing the TTLs and informing me about it. I have confirmed that this is the case by grabbing a manual AXFR of the zone:
ns1 0 /home/jj33 ># xfer 37.19.172.in-addr.arpa ad-dns | grep '^3\.' <
3.37.19.172.in-addr.arpa. 900 IN PTR 0509-l3-tmbxt.example.ad.
3.37.19.172.in-addr.arpa. 1200 IN PTR 0402-3p2jf41.example.ad.
In looking at the Windows DNS and DHCP tools, it seems very likely based on the lease time that 0402-3p2jf41.example.ad either returned its lease or went away and never came back, allowing the lease to expire. 0509-l3-tmbxt.example.ad came along, picked up the IP, and inserted its name for the 3.37.19.172.in-addr.arpa record.
So, with all the explanation done, I have several questions:
In the DDNS process, who actually defines the TTL of the reverse record? The DNS server, the DHCP server, or the DHCP client?
Why are the stale in-addr.arpa records not being deleted? Should the DNS server know to delete existing DDNS names when a new DDNS name is submitted?
Why would this suddenly start occurring? This system has been running for years with this only happeneing a coupld of times before, and always with the same IP address. In the last few days it has happened multiple times with multiple IPs.
Would scavenging help? We don't currently have it turned on. While I'm going to look into it for its own merits, I'm not sure it would help in this situation since the default seems to be 7 days before scavenging.
Does this situation require action, or if I ignore it will "something" purge the stale records eventually (I really, really hate waiting for divine intervention, but it seems odd that we wouldn't have faced this before).
Aside from the questions, can anyone share any hard-won experience related to this issue? Thanks.
UPDATE 1: It appears that, on a per-RR level, scavenging is actually turned on. It is turned on at the DNS server level, it is turned off at the zone level, and now that I have the advanced view turned on I can see that it's turned on for dynamically-inserted records as well. So, it's not an issue of scavenging not working, it's an issue of the 7 day lag plus the (apparently new?) TTL differences.
UPDATE 2: The DHCP scope also has "Discard A and PTR records when lease is deleted" checked. This feels like a failure on the part of the DHCP server since the lease for the original PTR is gone from the DHCP server...
Thanks for your answers so far. I'm digesting them and gathering information to see if the noise I'm seeing is a lot of records generating a few logs each or a few records generating a lot of logs each. Also, auditing my PTRs to see if this double-record thing is common but I'm only noticing it because the TTLs have started to mismatch. I'm leaning toward this being a non-issue that scavenging will address but I'd still like to understand where the differing TTLs come from
A:
Here's an article from Microsoft that describes the dynamic DNS process with their DHCP server: http://technet.microsoft.com/en-us/library/cc787034(WS.10).aspx
The stock behaviour of W2K and up is for the client to request the DHCP server register the PTR record on behalf of the client, and the client registers the A record itself. The DHCP server can be made to register the A record and the PTR record (including for pre-Windows 2000 clients that can't make DDNS registrations themselves).
There is an optional setting to have the DHCP server delete the A and PTR records when a lease is discarded. If the lease hasn't time-out, though, the records won't be deleted.
You absolutely should be aging and scavenging your DDNS zones. If you're aging and scavenging, this will eventually "purge". If you're not, it won't.
This Microsoft support article explains how to set the TTL value for DNS resource records registered by DHCP servers (originally in a hotfix, now just built-in to the OS): http://support.microsoft.com/kb/322989
To alter the behaviour of client computers in DNS registrations, have a look in Group Policy in the DNS Client node under the Network subnode of the Administrative Templates node of the Computer Configuration. In there, you'll find that you can force the clients to register their PTR records, rather than having it done by the DHCP server (if you so desire), and you can set the TTL on records registered by clients.
I'm not sure why this would suddenly start occurring. Some configuration had to change, but I'm at a loss as to tell you where. Start talking to your co-admins about any changes they might've made in the DHCP server configuration or in the group policy settings for clients' dynamic DNS behaviour.
I can't say I've seen the behaviour of multiple clients registering the same PTR record. That's odd. I'll have to defer to someone else on that. I will say that all of my reverse-zones are always AD integrated and require secure updates, but I don't know that that would have an effect on this.
In my experience, just having aging and scavenging turned on makes a world of difference in eliminating stale records. The default 7 day interval has worked well for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Submitting app on App Store
I had uploaded an app on app store with version 1.1.0.
It was accepted and is now on sale.
Now I have made small fixes and need to submit the app again.
Will I be able to submit the app on store, if I keep the same version.
A:
Build version is not the version that app-store uses. It's just for the purpose of developers to refer for themselves. Both values needs to be incremented for application to upload.
Bundle version is the important one and should be updated if you want to update your app in app-store. It will also be shown in app-store.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can PHP be inserted into a javascript call in my header?
I have a wordpress theme that I like to duplicate. To make things easier on myself, I'm trying to use the bloginfo function to call my jquery file..like this:
<script type="text/javascript" src="<?php echo bloginfo("template_url"); ?>/js/jquery-1.4.2.min.js"></script>
I just can't get it to work. When I check my source file it looks exactly like the code above.
Can this even be done, or should I just forget it? Thanks guys!
A:
Are you sure the above code is actually in a PHP-file and gets parsed by the server? I can't think of a different reason why PHP-code should just be printed and not executed.
| {
"pile_set_name": "StackExchange"
} |
Q:
PowerShell get weekday name from a date
Using powershell I want to get the week day name (Friday) from a date. Been googling and cant find this one. It so I can do an IF statement to do something if the date is a Friday.
Can anyone help?
A:
Use Get-Date to produce a DateTime object, then call its DayOfWeek method. For example:
(get-date 01/01/2016).DayOfWeek
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is "iff" used instead of "if" Xcode Docs
Why does the documentation use "iff" instead of "if"?
A:
iff is used for if and only if statement.
Statement enclosed is going to executed if both condition must be true.
ie. either both are true or none.
| {
"pile_set_name": "StackExchange"
} |
Q:
UIPickerView throws -[__NSArrayM objectAtIndex:]: index 0 beyond bounds when data source is not empty in iOS 8
We have an app which works without any issues in iOS 7, but when running on iOS 8 it crashes with the following error:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** - [__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
0 CoreFoundation 0x03361df6 __exceptionPreprocess + 182
1 libobjc.A.dylib 0x026fca97 objc_exception_throw + 44
2 CoreFoundation 0x03238073 -[__NSArrayM objectAtIndex:] + 243
3 eAlth Devel 0x0022f13e -[NSArray(TKCategory) firstObject] + 62
4 UIKit 0x00f411ee -[UITableView reloadData] + 443
5 UIKit 0x00f45ede -[UITableView _reloadDataIfNeeded] + 78
6 UIKit 0x00f4bec7 -[UITableView layoutSubviews] + 36
7 UIKit 0x00ec19c0 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 608
8 libobjc.A.dylib 0x02712771 -[NSObject performSelector:withObject:] + 70
9 QuartzCore 0x0055a27f -[CALayer layoutSublayers] + 152
10 QuartzCore 0x0054e105 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 397
11 QuartzCore 0x0054df60 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
12 QuartzCore 0x004ac676 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 284
13 QuartzCore 0x004ada3c _ZN2CA11Transaction6commitEv + 392
14 QuartzCore 0x004ae108 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
15 CoreFoundation 0x03284fbe __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
16 CoreFoundation 0x03284f00 __CFRunLoopDoObservers + 400
17 CoreFoundation 0x0327a93a __CFRunLoopRun + 1226
18 CoreFoundation 0x0327a1ab CFRunLoopRunSpecific + 443
19 CoreFoundation 0x03279fdb CFRunLoopRunInMode + 123
20 GraphicsServices 0x04aa924f GSEventRunModal + 192
21 GraphicsServices 0x04aa908c GSEventRun + 104
22 UIKit 0x00e36e16 UIApplicationMain + 1526
23 eAlth Devel 0x000f1c5c main + 76
24 libdyld.dylib 0x02a53ac9 start + 1
25 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
The method which was called before the error is:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
NSObject * sel = [pickerData objectAtIndex:row];
return sel.description;
}
pickerData array object is not nil and it has following objects in it:
self->pickerData:
<__NSArrayM 0x7c130080>(
All,
Br Clinic,
Clinic 2,
EssHth,
GC Clinic,
HHolistics,
K5003 - HHD3112,
K5003 - HHD3112 - Gp2,
NEW DEMO CLINIC,
Nursing Home Visits,
PR Accupuncture,
PP,
RB Therapy,
SC Clinic,
S Clinic,
TW Practice
)
Any suggessions on how to fix the issue ?
Thanks in advance !
A:
Please refer to the following line of my question.
3 eAlth Devel 0x0022f13e -[NSArray(TKCategory) firstObject] + 62
In iOS 8 apple has implemented the method for
- (id)firstObject
But one of the libraries which I used in my project is implementing a Category for NSArray with the above method. The library which I was using was TapkuLibrary.
When initiating the UIPickerView, iOS gets confused about which "firstObject" method to be used. Is it from the core libraries or the one from the TapkuLibrary.
Due to that app crashes.
Exceptions was not clear for me to figure it out. An expert pointed me in the right direction after he so the exception. (Thank you expert ! you save me three more days of head scratching !)
Any how if you are getting a similar exception in iOS 8, check whether you have a "Category" for NSArray.
Remedy is remove the category from your project if it only implements "firstObject" method.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pros/Cons of a Health Savings Account (HSA) in the USA?
I am wanting to know the real benefits or pros/cons of a HSA in the USA. I have now been given the option of signing up for one due to healthcare changes. I understand some of the basics, but after reading some of the limitations and restrictions, I am not sure if it is the best option for me. What is the advantage outside of using pre-tax dollars for healthcare expenses? Is this a better way to approach health care costs instead of itemizing health care expenses on yearly federal taxes?
A:
Benefits:
As fennec mentions, this is literally a savings account that you can use for qualified medical expenses, with no time limitation (unlike an FSA where you must use the money by the end of the year)
The tax benefits for can be large. if you're in the 25% federal tax bracket and your state charges you an additional 7% taxes in your income bracket, if you put $3,000 into an HSA in a year, $3000 will be knocked off your AGI for taxes and so you'll owe 32%*$3000 =$960 less money in taxes come tax day (assuming you don't adjust your witholdings).
If your employer offers it, you can put money in your HSA just like a 401k - PRE tax. That means you get the tax savings of putting money in an HSA over the year instead of in a lump sum at the end of the year.
If you're well off and healthy, this is a great investment vehicle. You can put money into a Vanguard HSA or a HSA savings account with a higher interest
Premiums are often lower for HSA's than other types of insurance.
Often preventative coverage is completely covered (doctors visits, immunizations etc).
Costs:
By law HSA's must have a high deductible - $1200 for singles or $2,400 for families according to this source.
From what I've seen of HSA's, you're on the hook for any drugs you buy until your deductible is met. Depending on how many drugs you are on this could get costly.
It can take time to find a good HSA account that gives you a good return at a reasonable cost. Check out investment vehicle links above for some good options IMO.
If you or someone in your family gets injured or goes to the ER/hospital a lot, you'll chew right through your deductible.
It takes time to manage the inflow/outflow of money into and out of your HSA. You have ultimate flexibility and the ultimate responsibility of proving to the IRS (if they audit you) that you used the money for qualified medical expenses.
Tax laws changing makes the viability of these accounts uncertain. Perhaps something that is allowable as a qualified medical expense now, will not be considered a qualified medical expense later - like over the counter drugs next year, due to some stupid changes (in my opinion). see Wikipedia:
However, beginning in early 2011 you
will no longer be able to pay for OTC
(over the counter) medications with
HSA dollars
Notes:
I've found it easiest to pay for expenses through a credit card and then keep track of those which are reimbursable in a spreadsheet, and take a HSA withdrawl to cover my expenses. Other options include paying for large health care expenditures (e.g. getting LASIK) directly out of your HSA.
State income taxes may or may not exclude HSA's
You have to make sure when you use healthcare that you bill it to your insurance, otherwise it isnt counted as part of your deductible (even if you are fully responsible for the bill).
A general thought - HSA's fit the classical model of "insurance", which is, to insure against very bad things happening (car accident, cancer etc). You're on the hook for the first $X,000 (the deductible) for that year, but typically everything after is covered by the insurer.
HSA's are good if you actually investigate the costs associated with healthcare - don't go to an ER if urgent care will do, or if you don't need to go to urgent care, forego it.
A:
The big benefit of a health savings account is the savings aspect. HSAs let you save up and invest money for your health care expenses. You don't just pay for medical care with pretax dollars - you get to invest those pretax dollars (possibly until you've retired). If you can afford to put money in the plan now, this can be a pretty good deal, especially if you're in a high tax bracket and expect to remain there after retirement.
There are a lot of obnoxious limitations and restrictions, and there's political risk to worry about between now and when you spend the money (mostly uncertainty about what the heck the health insurance system will look like after the fight over ObamaCare and its possible repeal.)
A:
CrimsonX did a great job highlighting the primary pros and cons of HSAs, so I won't go into detail there. However, I did want to point out another pro - HSAs are (or can be) easy to manage. You said:
Is this a better way to approach health care costs instead of itemizing health care expenses on yearly federal taxes?
I'm not sure which company you are looking at establishing your HSA with, but with mine I have a debit card that I use when paying for medical care and then at the end of the year I get a 1099-SA that provides the amount of money spent on qualified purchases that calendar year. Yes, there are a few extra boxes I need to fill in for my 1040 come tax time, but I don't need to itemize my healthcare costs over the year. It really is pretty simple and straightforward.
Also, one con that is worth noting is that you become much more sensitive to healthcare costs due to the high deductible healthcare plan an HSA requires. For example, in all the years we've had an HSA we've not yet met our deductible, which means we pay out of pocket for any non-routine doctor visits. (The health insurer pays 100% of routine visits, like my wife's annual, well-baby check ups for the little one, and so on.)
So, when you're feeling really sick and think a doctor's visit would be warranted, you have to make a decision:
Do I go to the doctor's - which will cost $150?
Do I go to CVS Minute Clinic, or something similar, which will run $45-$60 but be less thorough? Or
Do I just tough it out?
After being faced with this decision a time or two you will start to envy those who have just a $20 copay!
Of course, that's just an emotional con. Each year I run the numbers on how much we spent per year on out of pocket plus premiums and compare it to what it would cost in premiums for an HMO-type plan, and the HSA plan always comes ahead. (In part because we are a pretty healthy family and I work for myself so do not get to enjoy group discount rates.) But I thought it worth mentioning because there are certainly times when I know I need to see a doctor or specialist and I cringe because I know I am going to be slapped with a big bill in the not too distant future!
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX Slider with 2 different colors , for example green for selected area and red for unselected area
What i want to achieve is the have a JavaFX Slider like the below :
I want the selected are to be green and the unselected area to be red :
Can this be done with let's say simple css because JavaFX is awesome i am sure it can but now how :_)
What i was doing till ....
Until now i was just adding a StackPane and behind that a ProgressBar , synchronized with the value of the Slider , what i mean? :)
, but hey now i need two colors and i have to create two ProgressBars in a StackPane with different colors (RED and Green) .... to much code ...
A:
1 slider and 2 progress bars , I will post below the .fxml code , .java code and the needed .css for look and feel :)
Any question feel free to answer :)
As for the code , this is created for XR3Player (Open Source Github Project)
.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.String?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.ProgressBar?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>
<fx:root prefHeight="389.0" prefWidth="228.0" style="-fx-background-color: #202020;" stylesheets="@../../style/application.css" type="StackPane" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/9.0.1">
<children>
<BorderPane fx:id="borderPane" minHeight="0.0" minWidth="0.0">
<bottom>
<StackPane minHeight="0.0" minWidth="0.0" BorderPane.alignment="CENTER">
<children>
<HBox alignment="CENTER" maxHeight="-Infinity" minHeight="0.0" minWidth="0.0" prefHeight="15.0">
<children>
<ProgressBar fx:id="volumeProgress1" maxWidth="1.7976931348623157E308" minHeight="0.0" minWidth="0.0" mouseTransparent="true" prefHeight="15.0" progress="1.0" HBox.hgrow="ALWAYS">
<styleClass>
<String fx:value="transparent-progress-bar" />
<String fx:value="transparent-volume-progress-bar2-nostrip" />
</styleClass>
</ProgressBar>
<ProgressBar fx:id="volumeProgress2" layoutX="10.0" layoutY="10.0" maxWidth="1.7976931348623157E308" minHeight="0.0" minWidth="0.0" mouseTransparent="true" prefHeight="15.0" progress="1.0" HBox.hgrow="ALWAYS">
<styleClass>
<String fx:value="transparent-progress-bar" />
<String fx:value="transparent-volume-progress-bar3-nostrip" />
</styleClass>
</ProgressBar>
</children>
</HBox>
<Slider fx:id="masterVolumeSlider" majorTickUnit="15.0" max="150.0" maxWidth="1.7976931348623157E308" minorTickCount="55" value="75.0">
<styleClass>
<String fx:value="transparency-slider" />
<String fx:value="timer-slider" />
</styleClass>
</Slider>
</children>
<BorderPane.margin>
<Insets left="5.0" right="5.0" />
</BorderPane.margin>
</StackPane>
</bottom>
</BorderPane>
</children>
</fx:root>
.java
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import main.java.com.goxr3plus.xr3player.application.tools.InfoTool;
public class MixTabInterface extends StackPane {
//--------------------------------------------------------------
@FXML
private BorderPane borderPane;
@FXML
private ProgressBar volumeProgress1;
@FXML
private ProgressBar volumeProgress2;
@FXML
private Slider masterVolumeSlider;
// -------------------------------------------------------------
/**
* Constructor.
*/
public MixTabInterface() {
// ------------------------------------FXMLLOADER ----------------------------------------
FXMLLoader loader = new FXMLLoader(getClass().getResource(InfoTool.PLAYERS_FXMLS + "MixTabInterface.fxml"));
loader.setController(this);
loader.setRoot(this);
try {
loader.load();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Called as soon as fxml is initialized
*/
@FXML
private void initialize() {
//masterVolumeSlider
masterVolumeSlider.boundsInLocalProperty().addListener((observable , oldValue , newValue) -> calculateBars());
masterVolumeSlider.valueProperty().addListener((observable , oldValue , newValue) -> {
calculateBars();
});
}
/**
* Calculate bars positioning
*/
private void calculateBars() {
//Variables
double value = masterVolumeSlider.getValue();
double half = masterVolumeSlider.getMax() / 2;
double masterVolumeSliderWidth = masterVolumeSlider.getWidth();
//Progress Max1
volumeProgress1.setProgress(1);
volumeProgress2.setProgress(1);
//Below is mind tricks
if ((int) value == (int) half) {
volumeProgress1.setMinWidth(masterVolumeSliderWidth / 2);
volumeProgress2.setMinWidth(masterVolumeSliderWidth / 2);
} else if (value < half) {
double progress = 1.0 - ( value / half );
double minimumWidth = masterVolumeSlider.getWidth() / 2 + ( masterVolumeSlider.getWidth() / 2 ) * ( progress );
volumeProgress1.setMinWidth(masterVolumeSliderWidth - minimumWidth);
volumeProgress1.setMaxWidth(masterVolumeSliderWidth - minimumWidth);
volumeProgress2.setMinWidth(minimumWidth);
} else if (value > half) {
double progress = ( value - half ) / half;
double minimumWidth = masterVolumeSlider.getWidth() / 2 + ( masterVolumeSlider.getWidth() / 2 ) * ( progress );
volumeProgress1.setMinWidth(minimumWidth);
volumeProgress2.setMinWidth(masterVolumeSliderWidth - minimumWidth);
volumeProgress2.setMaxWidth(masterVolumeSliderWidth - minimumWidth);
}
}
/**
* @return the borderPane
*/
public BorderPane getBorderPane() {
return borderPane;
}
/**
* @return the masterVolumeSlider
*/
public Slider getMasterVolumeSlider() {
return masterVolumeSlider;
}
}
.css
.transparent-volume-progress-bar2-nostrip > .bar,.transparent-volume-progress-bar2-nostrip:indeterminate .bar,.transparent-volume-progress-bar2-nostrip:determinate .track,.transparent-volume-progress-bar2-nostrip:indeterminate .track{
-fx-accent:rgb(0.0, 144.0, 255.0);
-fx-background-color: -fx-accent;
-fx-background-radius:0.0;
-fx-border-radius:0.0;
}
.transparent-volume-progress-bar3-nostrip > .bar,.transparent-volume-progress-bar3-nostrip:indeterminate .bar,.transparent-volume-progress-bar3-nostrip:determinate .track,.transparent-volume-progress-bar3-nostrip:indeterminate .track{
-fx-accent:#fc4f4f;
-fx-background-color: -fx-accent;
-fx-background-radius:0.0;
-fx-border-radius:0.0;
}
.progress-bar > .bar {
-fx-accent:firebrick;
/*-fx-background-color:firebrick;*/
-fx-background-color: linear-gradient(
from 0.0px 0.75em to 0.75em 0.0px,
repeat,
-fx-accent 0.0%,
-fx-accent 49.0%,
derive(-fx-accent, 30.0%) 50.0%,
derive(-fx-accent, 30.0%) 99.0%
);
-fx-background-insets: 3.0;
-fx-padding: 0.2em;
}
.transparent-progress-bar:determinate .track,.transparent-progress-bar:indeterminate .track{
-fx-background-color:rgb(0.0,0.0,0.0,0.5);
}
/* .transparent-progress-bar */
.transparent-progress-bar > .bar,.transparent-progress-bar:indeterminate .bar{
-fx-accent:firebrick;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Select column values alternatively with predefined value order
I have a table with these values and i want to show result with alternative values and also i want to change the order of values like customer 1, customer 3 ,customer 2 but they must be in alternative order.
customername .
CREATE TABLE TEST (
customername varchar(50)
);
INSERT INTO TEST VALUES('CUSTOMER 1');
INSERT INTO TEST VALUES('CUSTOMER 1');
INSERT INTO TEST VALUES('CUSTOMER 1');
INSERT INTO TEST VALUES('CUSTOMER 2');
INSERT INTO TEST VALUES('CUSTOMER 2');
INSERT INTO TEST VALUES('CUSTOMER 2');
INSERT INTO TEST VALUES('CUSTOMER 3');
INSERT INTO TEST VALUES('CUSTOMER 3');
INSERT INTO TEST VALUES('CUSTOMER 3');
Desired Result:
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
I have tried:
SELECT customername
FROM TEST
ORDER BY ROW_NUMBER() OVER ( PARTITION BY customername ORDER BY customername)
This returns,
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
N.B Value can be integer like 3,2,1 because above is just an example
A:
You need an additional table which defines the desired order:
create table dict(customername varchar(50), priority int);
insert into dict values
('CUSTOMER 2', 1),
('CUSTOMER 1', 2),
('CUSTOMER 3', 3);
select customername
from test
join dict
using (customername)
order by
row_number() over (partition by customername),
priority;
customername
--------------
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
(9 rows)
| {
"pile_set_name": "StackExchange"
} |
Q:
discuss about the differentiability of $g(x)=|f(x)|$, where $f$ is a differentiable function
I want to discuss about the differentiability of $g(x)=|f(x)|$, where $f$ is a differentiable function
Example 1
Take $f(x)=|x|$, function is clearly not differentiable at $x=0$.
Example 2
Take $f(x)=|\sin(x)|$, function is clearly not differentiable at the point $x=n\pi$
After taking few more examples like $|x-1|, |\cos(x)|$, it always seems to be the case that $|f(x)|$ is not differentiable at the points where $f(x)=0$
Observation: One thing is common in all the examples that some portion of $f(x)$ lies below $x$ axis.
So I took another example
$f(x)=x^2$ but $|f(x)|$ is differentiable at the point where $f(x)=0$
Question 1:
Am I right in concluding that we can not just say in general setting that $|f(x)|$ is not differentiable at the points where $f(x)=0$?
When can we(I mean under what conditions can we )conclude that $|f(x)|$ is differentiable at points where $f(x)=0$. My hypothesis is that graph of $f$ should lie below $x$ axis.
Question 2:
Let $f(x)$ and $g(x)$ be two differentiable function, when can we conclude that $|f(x)|+|g(x)|$ is not differentiable at the points where $f(x)=0$ and $g(x)=0$
Example $|sin(2-x)|+ |cos(x)| $ are not differentiable at $x=2+2\pi, x=(2n+1)\frac{k}{2}$
Edits
As mentioned by @Torsten Schoeneberg in comments, my hypothesis fails!!
Grand Edit:
$f(x)=|x|$ then $f'(x)=\text{sign}{(x)}$
So let $f(x)$ be a differentiable function, and let $g(x)=|f(x)|$, then $$g'(x) =\text{sign}(f(x))f'(x)$$
Note that $\text{sign}{(f(x))}=\begin{cases}{ -1 \quad \text{if } f(x)<0\\+1 \quad \text{if } f(x)>0 } \\{ 0 \quad \text{if } f(x)=0} \end{cases}$
Am I going in right direction?
A:
Hint: Try to show that if $f(x_0)\ne 0,$ then $f'(x_0)$ exists iff $|f|'(x_0)$ exists. And if $f(x_0)= 0$ and $f'(x_0)$ exists, then $|f|'(x_0)$ exists iff $f'(x_0)=0.$
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there more 40-moves chess games than atoms in the universe?
I read this tweet recently:
"There are more possible games of
chess lasting 40 moves than there are
atoms in the entire universe.
Intriguing to know."
I find this highly doubtful.
Could anyone verify this for me please?
A:
There are vastly many more 40-move chess games than atoms in the visible universe, which we will prove below. But first, some clarification:
Earlier posts mention the Shannon number, which is his estimate for the game-tree complexity of chess (i.e., the number of possible games). Shannon gave the estimate 10120 as a remark in "Programming a Computer for Playing Chess". Another estimate by Victor Allis was 10123 (this is mentioned in his PhD thesis linked from the Wikipedia page). He writes:
The game-tree complexity of chess, 10123 is based on an average branching factor of 35 and an average game length of 80"
(In fact, there are an infinite number of possible games of chess, provided no player claims a draw through repetition nor the 50 move rule. The above estimates are based on more practical numbers.)
The above seems to be confused with the state space complexity, i.e., the number of possible legal and reachable positions on a chess board (which is a drastically different number than asked for in the question). In fact, a strict upper bound for this was derived by Allis (op. cit.) as 5 * 1052 , which is greatly less than the number of atoms in the visible universe (estimated at 1080; cf. Wikipedia).
Notation: A move in chess consists of two ply, one ply by white and one ply by black. Thus we have the "two move mate" (1. f3 e5 2. g4 Qh4#). The notation used here is algebraic notation.
We will give a constructive proof that there are more 40-move chess games than atoms in the visible universe. Consider the following set of possible 40-move chess games starting with:
e4 e5
d4 d5
c3 c6
Now, for the remainder of the game white can make one of the following moves:
The white white-squared bishop can move to any square on the f1-a6 diagonal (6 squares => 5 possible moves).
The white black-squared bishop can move to any square on the c1-h6 diagonal (6 squares => 5 possible moves).
The white queen can move to any square on the d1-a4 diagonal (4 squares => 3 possible moves).
The white knight on g1 can move to any square in the set {g1,f3} (2 squares => 1 possible move).
The black pieces are restricted symmetrically. Continue this for the next 74 ply. Then the white player resigns.
We observe that:
The pieces never obstruct one another. Captures are never made. Check never occurs. Hence, for each ply, there are 14 legal moves.
We have used very few of the actual possible moves available to us. There will be vastly many more possible 40-move games than in this class.
These games last exactly 40 moves. (If you count resigning as a ply, then you can have black resign on the previous ply.)
Hence we have constructed a set of 1474 distinct 40-move games of chess. Moreover, 1474 > 1084, while 1080 is an estimate of the number of atoms in the observable universe.
Some comments:
In chess, players may claim a draw through the "three move rule", although are not obliged to claim. (This leads to cases where players play on indefinitely, sometimes caused by chess coaches insisting that their students do not accept nor offer a draw, sometimes caused by players unaware of the rules.) Also, typically, the three move rule is ignored in theoretical studies.
These positions end with a player resigning, but they could probably be modified to end in helpmate if required. However, this would reduce the overall number (and you'll probably need to use a more clever argument).
There are probably better constructions around than what I give here.
A:
Edit 2019-01: answering this question boils down to knowing how many possible ways there are to play 40 move games of chess and how many atoms there are in the universe. The latter is known, and all of these answers ultimately cite chess experts, only varying in their interpretation of their figures.
I like the answer from Douglas S. Stones the most as it is the most original. It constructs a move tree that by itself exceeds the number of atoms in the universe, thus directly answering the question.
DavePhD also has the quotes laid out most explicitly, showing that my reliance on the Wolfram site was wrong.
Edit: I'll leave the original as it stands, but want to add a correction thanks to Mike Dunlavey's comment. I misread the question and thus if the question is, indeed, asking whether games lasting 40 moves or less (I read 40 moves or more) is greater than the number of atoms in the universe, I'm switching my answer to disagree. The numbers are all there below, but now we're comparing 10^80 (# of atoms) vs. 10^43 (# of 40 move or less chess games). Thus the number of atoms is greater.
I would agree.
First, Wiki provides this figure on the number of atoms in the universe:
Two approximate calculations give the number of atoms in the observable universe to be close to 10^80.
Next, Wiki provides the Shannon number as the number of possible chess games that can be played:
The game-tree complexity of chess was first calculated by Claude Shannon as 10^120, a number known as the Shannon number.
Lastly, Wolfram Mathworld provides a figure for the number of games less than 40 moves:
The number of possible games of 40 moves or less P(40) is approximately 10^40 (Beeler et al. 1972) ...Shannon (1950) gave the estimate: P(40) = 64! / (32! * 8!^2 * 2!^6) = 10^43.
I see some other answers have come in while I've been typing. They seem to compare total possible games (10^120) to the number of atoms in the universe (10^80), but you're looking for the number of atoms compared to games longer than 40 moves. In that case, we look at:
10^80 vs. 10^120 - 10^43 (to be conservative)
To be fair, the poster's (@Vian) own answer is correct, as 10^43 doesn't even dent 10^120 and thus it's still essentially comparing 10^80 and 10^120. Just wanted to spell out why I think the question is slightly different than just comparing # of atoms and # of all possible chess games.
A:
The accepted answer is wrong, due to the fallacy of accepting a link to a another website as the truth, rather than actually doing the math.
Particularly, the site http://mathworld.wolfram.com/Chess.html confused the number of positions, with the number of 40-move games.
Though mathworld says
The number of possible games of 40 moves or less P(40) is approximately 10^(40) (Beeler et al. 1972)
The Beeler reference itself is very clear that it means positions, not games:
There are about 10^40 possible positions
and though mathworld says
Shannon (1950) gave the estimate ... 10^43
Shannon really wrote in XXII. Programming a Computer for Playing Chess Philosophical Magazine, Ser.7, Vol. 41, No. 314 - March 1950 :
In typical chess positions there will be of the order of 30 legal
moves. The number holds fairly constant until the game is nearly finished as shown in fig.
1. This graph was constructed from data given by De Groot, who averaged the number of
legal moves in a large number of master games (De Groot, 1946, a). Thus a move for
White and then one for Black gives about 1000 possibilities. A typical game lasts about 40
moves to resignation of one party. This is conservative for our calculation since the
machine would calculate out to checkmate, not resignation.
However, even at this figure there will be 10^120 variations to be calculated from the initial
position.
...
Another (equally impractical) method is to have a "dictionary" of all possible positions of
the chess pieces. For each possible position there is an entry giving the correct move
(either calculated by the above process or supplied by a chess master.) At the machine's
turn to move it merely looks up the position and makes the indicated move. The number of
possible positions, of the general order of 64! / 32!(8!)^2(2!)^6, or roughly 10^43
In chess, "40 move game" means each player moves a piece 40 times: 80-ply or 80 half moves.
in standard chess terminology, one move consists of a turn by each player; therefore a ply in chess is a half-move. Thus, after 20 moves in a chess game, 40 plies have been completed—20 by white and 20 by black.
So for a 40 move game, if it is approximated that there is some constant (c) number of legal half-moves, the approximation of the number of 40 move games is of the form:
c ^ 80
So as long as "c" is greater than 10, the number of 40 move games is greater than the number of atoms in the universe.
For example, there are 20 possible first half-moves (16 pawn moves and 4 knight moves), and 20 possible second half moves.
So Shannon, citing to De Groot uses the estimate of "30" for "c" and therefore:
30^80 = ~1.5 x 10^118
So, yes, there are more exactly 40 move (80-half move) games than the number of atoms in the universe.
| {
"pile_set_name": "StackExchange"
} |
Q:
How should mulitiple query string parameters be presented in swaggers?
I want the api to be able to accept multiple query strings, for example:
GET /{id}?expand=property1,property2
I have the api defined as:
public Task<IActionResult> GetAsync([FromRoute] string id, [FromQuery] Expandable expand)
And Flag Enum Epandable defined as:
[Flags]
[JsonConverter(typeof(StringEnumConverter))]
public enum Expandable
{
None = 0x0,
Property1= 0x1,
Property2 = 0x2,
Property3 = 0x3
}
And the swagger for parameter "expand" generated as
{
"name": "$expand",
"in": "query",
"description": "",
"required": true,
"type": "string",
"default": "None",
"enum": [
"none",
"property1",
"property2",
"property3"
]
},
But with this swagger, the auto-gen client takes in a string, I am not sure how the swagger should be presented so the auto-generated client would also take in a Flag Enum?
A:
you should make expand parameter Expandable[] also your flag is declared incorrectly What does the [Flags] Enum Attribute mean in C#?
| {
"pile_set_name": "StackExchange"
} |
Q:
Как окрасить блок по нажатию в обе стороны?
Мне нужно окрасить блоки как на фотографии.
Только нужно учитывать то что действия нужно выполнять в обе стороны.
При клике окрашиваем, ещё раз кликаем окраску снимаем.
Помогите разобраться, пожалуйста!
$(document).ready(function() {
/* Клик на услуги - удобства */
document.getElementById('order').onclick = function(event) {
var target = event.target;
if (target.className == '.drive__order_items') {
var color = getComputedStyle(target).backgroundColor;
if (color == "rgb(0, 0, 0)") {
target.style.backgroundColor = ""
} else {
event.target.style.backgroundColor = "black"
}
}
}
});
.drive__suite_first {
float: left;
margin-left: 157px;
}
.drive__par {
font-size: 1.125em;
font-weight: 400;
margin-top: 26px;
margin-bottom: 22px;
}
.drive__order {
list-style: none;
}
.drive__order_block {
border-radius: 3px;
border: 1px solid black;
padding: 13px 13px;
font-size: 1.125em;
}
.drive__order_items {
position: relative;
font-size: 0.875em;
font-weight: 200;
text-align: center;
display: inline-block;
margin-left: 29px;
}
.drive__order_items:first-of-type {
margin-left: 0px;
}
.drive__order_par {
position: absolute;
top: 55px;
left: 50%;
transform: translate(-50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="drive__order" id="order">
<li class="drive__order_items">
<div class="drive__order_block"><i class="fas fa-parking"></i></div>
<p class="drive__order_par">
Парковка
</p>
</li>
<li class="drive__order_items">
<div class="drive__order_block"><i class="fas fa-concierge-bell"></i></div>
<p class="drive__order_par">
Питание
</p>
</li>
<li class="drive__order_items">
<div class="drive__order_block"><i class="fas fa-hot-tub"></i></div>
<p class="drive__order_par">
Сауна
</p>
</li>
<li class="drive__order_items">
<div class="drive__order_block"><i class="fas fa-drumstick-bite"></i></div>
<p class="drive__order_par">
Мангал
</p>
</li>
</ul>
A:
Решение не моё то есть мне помогли - делается это вот так
let icon = document.querySelectorAll(".icon");
let last;
for (let i = 0; i < icon.length; i++) {
icon[i].onclick = e => {
if (last && last != icon[i]) last.classList.remove("active");
icon[i].classList.toggle("active");
last = icon[i].classList.contains("active") ? icon[i] : null;
}
}
:root {
--color: #fff;
--hover: gold;
}
body {
background: blue;
}
.fas {
display: block;
font-size: 100px;
color: var(--color);
border-radius: 10px;
transition: 0.34s linear;
}
.icon {
border: 3px solid var(--color);
display: inline-block;
padding: 16px 20px;
border-radius: 10px;
transition: 0.34s linear;
}
.icon.active .fas {
color: var(--hover);
}
.icon.active {
border: 3px solid var(--hover);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css">
<div class="doc">
<div class="icon">
<i class="fas fa-parking"></i>
</div>
<div class="icon">
<i class="fas fa-concierge-bell"></i>
</div>
<div class="icon">
<i class="fas fa-hot-tub"></i>
</div>
<div class="icon">
<i class="fas fa-drumstick-bite"></i>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it correct to concatenate (pseudo-)random byte values before testing them with the NIST suite or tools like dieharder?
Let's assume I have thousands of (pseudo-)random 4-byte values. The values are 4 byte random values which a blackbox device gave me. I got these values by requesting them. In between others might have requested them too (I don't know about that). Now I'd like to test them for randomness. There are tools for this like dieharder or the NIST Statistical Test Suite.
Is it valid to just concatenate the thousands of 4-byte values so that I end up with one very long byte (n * 1000 * 4 byte) stream which I then feed into these tools?
Is it correct that it doesn't matter for the tests how long the individual values (4-byte) were before? (Because the test tool wouldn't know that I had 4-byte values in the beginning, once I concatenated them?).
Edit:
The question is meant as a general question. The actual underlying problem is how to examine seed values for randomness, which I obtained via UDS Security Access (see https://en.wikipedia.org/wiki/Unified_Diagnostic_Services#Services $27).
A:
Is it valid to just concatenate the thousands of 4-byte values so that I end up with one very long byte (n * 1000 * 4 byte) stream which I then feed into these tools?
Is it correct that it doesn't matter for the tests how long the individual values (4-byte) were before?
Yes for both. The fact that others may have obtained (and removed) randomness from the source while it was sampled, or/and that the samples are grouped in some particular way for testing, does not prevent from testing what's obtained. And that can not cause a valid test to fail more often, assuming the source's full output is indistinguishable from random (including for said others trying to make the test pass, or fail).
On the other hand, those same facts could make the test become arbitrarily less capable of detecting some faults. As an extreme example, a source that always repeat each byte that it outputs might become indistinguishable from true random if we sub-sample its output, keeping every odd byte.
The actual underlying problem is how to examine seed values for randomness.
Dieharder or the NIST Statistical Test Suite alone can't give any assurance of that. At best, they can indicate a fail with high confidence, which saves from performing further work (beyond checking that the test was correctly performed/works). If they indicate pass, no other firm conclusion can be reached on that basis alone. It is needed to know how the seed values are generated, and that can't be determined by a test of the seed values.
As a proof that these tests can not validate the fitness for cryptographic purposes of a source of unknown build, consider a RNG with:
a real-time clock keeping UTC time in second, initializing 128-bit register at startup after a delay of 1 second
with the register then repeatedly encrypted using AES-256 and a key to produce the next register value, which concatenated 128-bit values form the bulk of the output, queried over a gigabit Ethernet interface.
This source will pass any black-box testing that does not reject a good generator, including tests scrutinizing power-on, as long as the test does not use AES-256 and the correct key.
But this source is disastrous from a cryptographic perspective. Given the key and when the black box was started, its output is predictable. Given the key and a fragment of a sequence, all the rest can be computed. Some party eating bytes from the source in the background can even decide what another party using the source will get!
As pointed by others, many statistical tests, including some of the DieHarder suite, require megabytes of input. The full Dieharder needs gigabytes.
However, in the context of a cryptographic RNG of proper structure, these tests requiring a lot of input are not needed. The tests that make sense are those on the unconditioned (or lightly conditioned) entropy source, used to seed a CSPRNG. The source is validated by tests which purpose is to ensure that it delivers some entropy. The CSPRNG is validated by examination of its design, and Known Answer Tests. Some monitoring in the RNG should detect a fault in the source and in this case prevent output. The combination might be checked by an extra test of the whole thing, but that's meaningful only if there is some assurance, obtained otherwise, that the overall structure really is the source seeding the CSPRNG, and being monitored.
A:
Thousands of bytes isn't nearly enough samples for any powerful statistical test. The fewer samples you have the less sensitive a given test can be.
If you concatenate statistically independent uniform samples then tests should pass the resulting byte stream. It doesn't matter how the bits are rearranged as long as order doesn't depend on the value of those bits. (Reversing and bit interleaving but not rearranging bytes into ascending order.)
Some statistical tests aren't sensitive to order. Basic frequency tests and tests based on mean, median, variance, for example. However test suites include many different types of tests, some of which are order sensitive. Rearranged bits from an ideal random source should pass both order-sensitive and order-insensitive tests.
Different methods involving reordering are used in testing Non-Cryptographic RNGs. One improvement over a single pass over test data is to repeat the test with bit order reversed within each 32-bit word. This is documented in Sebastiano Vigna's papers involving RNG testing. This is done because the tests are less sensitive to patterns in low order bits and also because non-cryptographic RNGs are often "more" random in high bits and "less" random in low bits.
Round-robin interleaving of samples from multiple generators was done in a paper, "Better Splitable Pseudorandom Number Generators
(and Almost As Fast)" as hack to test RNGs from the same family for correlations. It isn't a totally reliable method for detecting such correlations.
Other kinds of modifications to the test suites' inputs will have the same effect as reordering as long as they do not introduce bias. For example, negating each bit of output, XORing the stream by a constant, or using modular addition with a constant.
A Good RNG Will Pass no matter how you mutate (without bias) its output. A bad RNG Might fail or Might Not before or after transforming (scrambling) its output some way.
Such transformations Do Not Turn an Insecure RNG into a Secure RNG. A bad RNG can pass all or some statistical tests after applying various mutations. That does not mean that the input is actually random or unpredictable.
Positive RNG test suite results (failing a "randomness" test) usually indicate data is not random. There are false positive but they can be detected by running the tests multiple times with different data. False negatives, however, are a very serious flaw in RNG test suites.
Passing any number of statistical tests will not tell you if an RNG or cipher is secure. It is Very Easy to make an algorithm with enough apparent randomness to pass any black-box statistical tests you subject it to, but it's Much Harder to design a secure algorithm.
The same applies to output from a hardware TRNG. In fact you cannot tell the difference between truly random output and output generated from, say, a counter encrypted with a secret key known only to the manufacturers of the device. (As in a backdoored RNG.) Statistical tests cannot tell you how much entropy a hardware RNG produces. Nor can they tell you whether a noisy source is actually unpredictable.
In summary:
Passing RNG tests Does Not mean the output is actually pattern-free, statistically unbiased, or secure.
Failing the tests persistently indicates a definite problem.
An unbiased transformation applied to a uniform IID bit string results in a new string which is also unbiased.
Scrambling output can hide statistical artifacts but it Cannot turn insecure RNGs into secure RNGs.
RNG test suites are practically Useless for cryptography
Something can be apparently random without actually being unpredictable.
| {
"pile_set_name": "StackExchange"
} |
Q:
how do i use alexa's data.alexa.com url
i want to read the country of any website from Alexa's Data from XML
so i tried
http://data.alexa.com/data?cli=10&url=http://www.flipkart.com
but this just returns the following for all domains
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ALEXA VER="0.9" URL="alexa.com/" HOME="0" AID="=">
<RLS TITLE="Related Links" PREFIX="http://" more="0">
<RL HREF="www.alexa.com/blocker?tag=pfcp2YmYvjxYjfxUj=0000000000000&ref=data.alexa.com/" TITLE="Please click here to continue using Alexa"/>
</RLS>
</ALEXA>
is there another way to axes alexa data
A:
You need to sign up with Amazon Web Information Service at https://aws.amazon.com/awis/
| {
"pile_set_name": "StackExchange"
} |
Q:
Pushing elements into array leads to modification of the previous elements
I am pushing elements into array, and the problem is that each time I push a new element, all the previous elements become equal to the last one.
I have come across this post, but I still can't see how to fix the issue
Please see this jsFiddle. As the post suggests, I moved the declaration of instance to the for-loop, but I've still got the same problem. Namely, the output of the code looks like this: [46, 46]. However, I would expect it to be [23, 46].
I am really going crazy. Any ideas???
$(document).ready(function() {
var json = {'name': 'Anna', 'counter': 1}
var counters = [23, 46];
var result = [];
$(counters).each(function() {
var instance = json;
instance.counter = this;
result.push(instance);
});
$(result).each(function(){
$('#test').append('<li>' + this.counter + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'>
</ul>
A:
You should do deep copy using var instance = jQuery.extend(true,{},json);
$(document).ready(function() {
var json = {'name': 'Anna', 'counter': 1}
var counters = [23, 46];
var result = [];
$(counters).each(function() {
var instance = jQuery.extend(true,{},json);
instance.counter = this;
result.push(instance);
});
$(result).each(function(){
$('#test').append('<li>' + this.counter + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Create an new column in data frame : index in group (not unique between groups)
I have a data frame with two columns: the first column contains the group to which each individual belongs, and the second the individual's ID. See below:
df <- data.frame( group=c('G1','G1','G1','G1','G2','G2','G2','G2'),
indiv=c('indiv1','indiv1','indiv2','indiv2','indiv3',
'indiv3','indiv4','indiv4'))
group indiv
1 G1 indiv1
2 G1 indiv1
3 G1 indiv2
4 G1 indiv2
5 G2 indiv3
6 G2 indiv3
7 G2 indiv4
8 G2 indiv4
I would like to create a new column in my data frame (retaining the long format) with the index of each individual in the group, that is:
group indiv Ineed
1 G1 indiv1 1
2 G1 indiv1 1
3 G1 indiv2 2
4 G1 indiv2 2
5 G2 indiv3 1
6 G2 indiv3 1
7 G2 indiv4 2
8 G2 indiv4 2
I have tried with the data.table .N or .GRP methods, without success (nice work on data.table by the way!).
Any help much appreciated!
A:
You could use the new rleid function here (from the development version v >= 1.9.5)
setDT(df)[, Ineed := rleid(indiv), group][]
# group indiv Ineed
# 1: G1 indiv1 1
# 2: G1 indiv1 1
# 3: G1 indiv2 2
# 4: G1 indiv2 2
# 5: G2 indiv3 1
# 6: G2 indiv3 1
# 7: G2 indiv4 2
# 8: G2 indiv4 2
Or you could convert to factors (in order to create unique groups) and then convert them back to numeric (if you using the CRAN stable version v <= 1.9.4)
setDT(df)[, Ineed := as.numeric(factor(indiv)), group][]
# group indiv Ineed
# 1: G1 indiv1 1
# 2: G1 indiv1 1
# 3: G1 indiv2 2
# 4: G1 indiv2 2
# 5: G2 indiv3 1
# 6: G2 indiv3 1
# 7: G2 indiv4 2
# 8: G2 indiv4 2
A:
In 1.9.5 (current development version), the function frank (and frankv) are exported. With that, you can do:
require(data.table) ## 1.9.5+
setDT(df)[, col := frank(indiv, ties.method="dense"), by=group]
df
# group indiv col
# 1: G1 indiv1 1
# 2: G1 indiv1 1
# 3: G1 indiv2 2
# 4: G1 indiv2 2
# 5: G2 indiv3 1
# 6: G2 indiv3 1
# 7: G2 indiv4 2
# 8: G2 indiv4 2
You can install it by following the instructions here.
| {
"pile_set_name": "StackExchange"
} |
Q:
\widetilde{} alternative for formula over the tilde
I'd like to put some formula over the tilde in math mode and adjust the tilde length to the length of that formula. It seems that \widetilde{} is almost what I need, however it puts the formula below the tilde. Is there a way to actually put the formula above?
An example of the formula to put above is:
\widetilde{(p_1',p_2') \in C}
Edit: I wasn't exactly clear with the expected effect. I'd like to have tilde in the middle of line (like \sim does), however with the formula above.
A:
I took my answer at Big tilde in math mode and made two changes: 1) I changed it from an overstack to an understack; and 2) I increased the vertical stacking gap to \LMpt, which is 1pt scaled to the local mathstyle.
\documentclass{article}
\usepackage{scalerel}[2014/03/10]
\usepackage{stackengine}
\newcommand\reallywidetilde[1]{\ThisStyle{%
\setbox0=\hbox{$\SavedStyle#1$}%
\stackengine{\LMpt}{$\SavedStyle#1$}{%
\stretchto{\scaleto{\SavedStyle\mkern.2mu\sim}{.5467\wd0}}{.7\ht0}%
% .2mu is the kern imbalance when clipping white space
% .5467++++ is \ht/[kerned \wd] aspect ratio for \sim glyph
}{U}{c}{F}{T}{S}%
}}
\def\test#1{$%
\reallywidetilde{#1}\,
\scriptstyle\reallywidetilde{#1}\,
\scriptscriptstyle\reallywidetilde{#1}
$\par}
\parskip 1ex
\begin{document}
$x = \reallywidetilde{(p_1',p_2') \in C}$
$\scriptstyle x = \reallywidetilde{(p_1',p_2') \in C}$
$\scriptscriptstyle x = \reallywidetilde{(p_1',p_2') \in C}$
\end{document}
If, by some chance, you actually wanted the text over the tilde (rather than the tilde under the text), that is also easy:
\documentclass{article}
\usepackage{scalerel}[2014/03/10]
\usepackage{stackengine}
\newcommand\reallywidetilde[1]{\ThisStyle{%
\setbox0=\hbox{$\SavedStyle#1$}%
\stackengine{\LMpt}{%
\stretchto{\scaleto{\SavedStyle\mkern.2mu\sim}{.5467\wd0}}{.7\ht0}%
}{$\SavedStyle#1$%
% .2mu is the kern imbalance when clipping white space
% .5467++++ is \ht/[kerned \wd] aspect ratio for \sim glyph
}{O}{c}{F}{T}{S}%
}}
\def\test#1{$%
\reallywidetilde{#1}\,
\scriptstyle\reallywidetilde{#1}\,
\scriptscriptstyle\reallywidetilde{#1}
$\par}
\parskip 1ex
\begin{document}
$xyz \reallywidetilde{(p_1',p_2') \in C} abc$
$xyz {\scriptstyle\reallywidetilde{(p_1',p_2') \in C}} abc$
$xyz {\scriptscriptstyle\reallywidetilde{(p_1',p_2') \in C}} abc$
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Switching the language directly in the application
Have been trying to localize my app into 7 languages, but all tutorials that I found only display how to on a single page, not through out the app.
I am now at the point where the localization works when device is of that language, but need to have ability to change languages via button.
EDIT: The below code works fine for anyone looking for a similar solution.
Notes about below:
The below groups of code create an in app language change, including the tab bar names.
You MUST put all data in the localize.strings as the main.strings will NOT work with this. That means you will need to programmatically add all "back", "cancel" and navigation titles, as well as menu items.
The NSNotificationCenter inside each of the "changeToXX" func is set to notify the tabBarViewController (or any controller you need) that the language has changed.
i
import UIKit
let AppLanguageKey = "AppLanguage"
let AppLanguageDefaultValue = ""
var appLanguage: String {
get {
if let language = NSUserDefaults.standardUserDefaults().stringForKey(AppLanguageKey) {
return language
} else {
NSUserDefaults.standardUserDefaults().setValue(AppLanguageDefaultValue, forKey: AppLanguageKey)
return AppLanguageDefaultValue
}
}
set(value) {
NSUserDefaults.standardUserDefaults().setValue((value), forKey: AppLanguageKey)
}
}
let languageChangedKey = "languageChanged"
class SettingsLanguageVC: UIViewController
{
@IBOutlet weak var languageENButton: UIButton!
@IBOutlet weak var flagENImageView: UIImageView!
@IBOutlet weak var languageENTitleLabel: UILabel!
@IBOutlet weak var checkmarkEN: UIImageView!
@IBOutlet weak var languageDEButton: UIButton!
@IBOutlet weak var flagDEImageView: UIImageView!
@IBOutlet weak var languageDETitleLabel: UILabel!
@IBOutlet weak var checkmarkDE: UIImageView!
@IBOutlet weak var languageFRButton: UIButton!
@IBOutlet weak var flagFRImageView: UIImageView!
@IBOutlet weak var languageFRTitleLabel: UILabel!
@IBOutlet weak var checkmarkFR: UIImageView!
@IBOutlet weak var languageESButton: UIButton!
@IBOutlet weak var flagESImageView: UIImageView!
@IBOutlet weak var languageESTitleLabel: UILabel!
@IBOutlet weak var checkmarkES: UIImageView!
var tabBar = TabBarController()
var MyDelegateClass = ""
override func viewDidLoad()
{
super.viewDidLoad()
configureView()
print(appLanguage)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back".localized, style: .Plain, target: self, action: #selector(SettingsLanguageVC.back(_:)))
navigationItem.title = "Select a language".localized
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func setTranslatedText(){
if appLanguage == "es" {
checkmarkShowES()
} else if appLanguage == "de" {
checkmarkShowDE()
} else if appLanguage == "fr" {
checkmarkShowFR()
} else {
checkmarkShowEN()
}
}
func configureView(){
let localeEN = NSLocale(localeIdentifier: "en")
let English = localeEN.displayNameForKey(NSLocaleIdentifier, value: "en")
languageENTitleLabel.text = English
flagENImageView.image = UIImage(named: "flag-en.png")
languageENButton.addTarget(self, action: #selector(self.changeToEN), forControlEvents: .TouchUpInside)
//German
let localeDE = NSLocale(localeIdentifier: "de")
let German = localeDE.displayNameForKey(NSLocaleIdentifier, value: "de")
languageDETitleLabel.text = German
flagDEImageView.image = UIImage(named: "flag-de.png")
languageDEButton.addTarget(self, action: #selector(self.changeToDE), forControlEvents: .TouchUpInside)
//French
let localeFR = NSLocale(localeIdentifier: "fr")
let French = localeFR.displayNameForKey(NSLocaleIdentifier, value: "fr")
languageFRTitleLabel.text = French
flagFRImageView.image = UIImage(named: "flag-fr.png")
languageFRButton.addTarget(self, action: #selector(self.changeToFR), forControlEvents: .TouchUpInside)
//Spanish
let localeES = NSLocale(localeIdentifier: "es")
let Spanish = localeES.displayNameForKey(NSLocaleIdentifier, value: "es")
languageESTitleLabel.text = Spanish
flagESImageView.image = UIImage(named: "flag-es.png")
languageESButton.addTarget(self, action: #selector(self.changeToES), forControlEvents: .TouchUpInside)
if appLanguage == "es" {
checkmarkShowES()
} else if appLanguage == "de" {
checkmarkShowDE()
} else if appLanguage == "fr" {
checkmarkShowFR()
} else {
checkmarkShowEN()
}
}
func changeToEN(sender: UIButton)
{
checkmarkShowEN()
appLanguage = "en"
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self)
[self.viewDidLoad()]
}
func changeToDE(sender: UIButton)
{
appLanguage = "de"
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self)
[self.viewDidLoad()]
}
func changeToFR(sender: UIButton)
{
checkmarkShowFR()
appLanguage = "fr"
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self)
[self.viewDidLoad()]
}
func changeToES(sender: UIButton)
{
checkmarkShowES()
appLanguage = "es"
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self)
[self.viewDidLoad()]
}
func checkmarkShowEN (){
self.checkmarkEN.hidden = false
self.checkmarkDE.hidden = true
self.checkmarkFR.hidden = true
self.checkmarkES.hidden = true
}
func checkmarkShowDE (){
self.checkmarkEN.hidden = true
self.checkmarkDE.hidden = false
self.checkmarkFR.hidden = true
self.checkmarkES.hidden = true
}
func checkmarkShowFR (){
self.checkmarkEN.hidden = true
self.checkmarkDE.hidden = true
self.checkmarkFR.hidden = false
self.checkmarkES.hidden = true
}
func checkmarkShowES () {
self.checkmarkEN.hidden = true
self.checkmarkDE.hidden = true
self.checkmarkFR.hidden = true
self.checkmarkES.hidden = false
}
@IBAction func back (sender: AnyObject) {
//back one VC
navigationController?.popViewControllerAnimated(true)
}
}
All text needing to be localized, need to have the suffix .localized, along with the following inside StringExtension.swift
extension String {
var localized: String {
return localized(appLanguage)
}
var localizeStringUsingSystemLang: String {
return NSLocalizedString(self, comment: "")
}
func localized(lang:String?) -> String {
if let lang = lang {
if let path = NSBundle.mainBundle().pathForResource(lang, ofType: "lproj") {
let bundle = NSBundle(path: path)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
return localizeStringUsingSystemLang
}
}
return localizeStringUsingSystemLang
}
}
Here is the TabBarController code:
Note: The tabs "search", "Favorites" and "More" are system tabs. I had to change them to custom and manually add the names to the tabs and add my own icons. Otherwise the they would not be localized.
import UIKit
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setTabViewControllerParams(0, tabBarItemTitle: "Species".localized, navigationItemTitle: filterBy)
setTabViewControllerParams(1, tabBarItemTitle: "Regions".localized, navigationItemTitle: "My Regions".localized)
setTabViewControllerParams(2, tabBarItemTitle: "Favorites".localized, navigationItemTitle: "Favorites".localized)
setTabViewControllerParams(3, tabBarItemTitle: "Search".localized, navigationItemTitle: "")
setTabViewControllerParams(4, tabBarItemTitle: "More".localized, navigationItemTitle: "Reef Life Apps")
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TabBarController.languageChangedTrigger), name: languageChangedKey, object: nil)
}
func languageChangedTrigger () {
[self.viewDidLoad()]
}
func setTabViewControllerParams(index: Int, tabBarItemTitle: String, navigationItemTitle: String) {
if let tabBarItems = tabBar.items {
if index < tabBarItems.count {
tabBarItems[index].title = tabBarItemTitle
}
}
if let viewControllers = viewControllers {
if index < viewControllers.count {
if let navigationController = viewControllers[index] as? UINavigationController {
if navigationController.viewControllers.count > 0 {
let viewController = navigationController.viewControllers[0]
viewController.navigationItem.title = navigationItemTitle
}
}
}
}
}
}
Lastly, I added the below to the AppDelegate's "didFinishLaunchingWithOptions" so that when a non English based phone launches, the app will launch in their language, rather than the default English.
if NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String == "es"
{ appLanguage = "es"
}else if NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String == "fr" {
appLanguage = "fr"
}else if NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String == "de" {
appLanguage = "de"
}else {
appLanguage = "en"
}
Hope this helps.
A:
Try this sample:
ViewController.swift
import UIKit
let AppLanguageKey = "AppLanguage"
let AppLanguageDefaultValue = "en"
var appLanguage: String {
get {
if let language = NSUserDefaults.standardUserDefaults().stringForKey(AppLanguageKey) {
return language
} else {
NSUserDefaults.standardUserDefaults().setValue(AppLanguageDefaultValue, forKey: AppLanguageKey)
return AppLanguageDefaultValue
}
}
set(value) {
NSUserDefaults.standardUserDefaults().setValue((value), forKey: AppLanguageKey)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSLog("title user lang: \("Title".localizeString)")
NSLog("title En: \("Title".localizeString("en"))")
NSLog("title Ru: \("Title".localizeString("ru"))")
NSLog("title Fr: \("Title".localizeString("fr"))")
NSLog("title ??: \("Title".localizeString("blabla"))")
NSLog("title sysem lnag: \("Title".localizeStringUsingSystemLang)")
// Do any additional setup after loading the view, typically from a nib.
}
}
StringExtension.swift
import Foundation
extension String {
var localizeString: String {
return localizeString(appLanguage)
}
var localizeStringUsingSystemLang: String {
return NSLocalizedString(self, comment: "")
}
func localizeString(lang:String?) -> String {
if let lang = lang {
if let path = NSBundle.mainBundle().pathForResource(lang, ofType: "lproj") {
let bundle = NSBundle(path: path)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
return localizeStringUsingSystemLang
}
}
Localizable.strings (Russian)
"Title" = "Привет";
Localizable.strings (English)
"Title" = "Hello";
Localizable.strings (French)
"Title" = "Salut";
Result:
| {
"pile_set_name": "StackExchange"
} |
Q:
is there any bound on the absolute number of algebraic integer in terms of its degree?
If Z is a sum of t distinct roots of unity and |Z| is a rational integer, can someone find a bound on |Z| in terms of k=deg(Q(Z):Q))?
Clearly we need to have distinct roots of unity otherwise this won't work!
Correction: Let assume that Z is not rational itself otherwise obviously it's wrong. Here I hope to extend the proof of Kronecker thm!
I have "Z is a sum of t distinct roots of unity and |Z| is a rational integer" I conjecture that either Z is rational or a root of unity!
A:
If you multiply all the primitive roots of unity for the first $n$ primes by $-i$, then add them, you get $in$, whose degree is $2$ and whose absolute value is $n$, rational and unbounded.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there some kind of functionality, where a pointer dereference gives an rvalue?
Is there some kind of functionality, where a pointer dereference gives an rvalue?
So, a usual pointer gives an lvalue:
Foo *p = ...;
fn(p[42]); // p[42] is an lvalue
I'd like to have p[42] return an rvalue, so a fn(Foo &&) can be called for fn(p[42]):
<some_pointer_type> p = ...;
fn(p[42]); // I'd like to have p[42] be an rvalue, so an fn(Foo &&) would be called
Note: I'd like to have p has this functionality, the pointer type should have this information, that dereferencing it should give an rvalue.
A:
By means of std::move() you can perform an unconditional cast to a rvalue.
fn(std::move(p[42]));
The name move is actually misleading here: nothing is being moved, but a cast is being performed.
Consider then writing a pointer template Ptr whose operators * and [] are overloaded to return a rvalue:
#include <utility>
class Foo {};
template<typename T>
class Ptr {
public:
Ptr(T* ptr): ptr_{ptr} {}
T&& operator*() { return std::move(*ptr_); }
T&& operator[](int idx) { return std::move(*(ptr_ + idx)); }
private:
T* ptr_;
};
void fn(Foo&& x) { return; }
void fn(const Foo& x) { return; }
int main()
{
Foo foo[50];
Ptr<Foo> p{&foo[0]};
// call void fn(Foo&&)
fn(p[42]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What can we infer about archangel(s) from the text of the Bible?
Among the Christians I know it is believed that Michael is the only Archangel because only he is mentioned as being one (I realize the flaw, but believed nonetheless).
However, there are several other schools of thought that say he is only one of an unknown number. Roman Catholics say Gabriel is one as well. The much less common Jehovah's Witnesses claim that Michael and Jesus are one and the same, therefore, Jesus is the Archangel.
Now here is what I know or assume:
Angel means messenger. I assume it is not used quite as a title but more like a description (is it though?).
Arch is a prefix usually used to imply that one is the greatest of them all. What does the original word imply and has it been used differently or similarly elsewhere in the Bible?
In the Bible, it is true that that only Michael is actually called 'Archangel', however, this does not mean he is the only one.
I primarily what to know if the use of this word in the Bible implies that there is only one Archangel or not.
I should clarify that for personal reasons I prefer the 66 book Protestant version of the Bible but I am marginally interested in the Catholic additions and the Apocrypha.
A:
Textual Usage
The word 'archangel' (lemma: ἀρχάγγελος) appears twice in the New Testament, at least once in the LXX translation of the book of Enoch (which mentions numerous angels and their duties and authority - I would read it here or here if this topic interests you), and also in a highly disputed verse in 2 Esdras. It should be noted that after the fourth century, few Christians considered Enoch to be canonical.
2 Esdras 4:36 - "And unto these things Uriel[*] the archangel gave them answer, and said, Even when the number of seeds is filled in you: for he hath weighed the world in the balance." *The RSV renders the archangel's name as Jeremiel (an alternate transliteration). It should be kept in mind that this is a highly disputed text (both the KJV and RSV w/apocrypha call this book '2 Esdras,' some scholars and other traditions call it 4 Esdras or 'Latin Esdras,' as the only copy preserved is in Latin).
Enoch 20:7 - All of the main Greek texts conclude this verse with ἀρχαγγέλων ὀνόματα ἑπτά. However, no English translation that I've found translates this phrase, which could be translated, "Of archangels there are seven names," or potentially also "There are seven names of archangels." See Swete's 1909 LXX critical text and apparatus for this verse. There may actually be seven archangels (although I will not assert this as it is purely speculation). Various church traditions include up to 14 archangels.
Enoch 9:1, 4 - The word 'archangel' only appears in what Swete labels as alternate texts - it is not in the primary texts that he chose for his critical edition of the LXX. I still wanted to mention this because the alternate texts would potentially be labeling "Michael, Gabriel, Raphael, and Uriel" as archangels, which would mean that there is more than one (other manuscripts appear to also include Suryal). See Swete's 1909 LXX critical text and apparatus for these verses here and here.
1 Thessalonians 4:16 - "For the Lord himself shall descend from heaven with a shout, with the voice of the archangel, and with the trump of God...." There is no definite article prefacing 'archangel' in the Greek, so this text should not be construed to imply that there is only one archangel.
Jude 9 - "Yet Michael the archangel, when contending with the devil he disputed about the body of Moses, durst not bring against him a railing accusation, but said, The Lord rebuke thee." It should be noted that Jude 14-15 is a quotation from Enoch 1:9 (a non-related section), and so it is significant to use evidence in Enoch since Jude quotes from the book. Jude 9 may also have been alluding to Enoch 9 since the angels (including Michael) did not directly accuse Azazel and Semjaza, but rather went to the Lord. However, most Christian scholars ascribe this to a questionable work entitled The Assumption of Moses (or Testament of Moses). With any discussion of Jude, we should also examine possible "parallel" verses in 2 Peter (for this reason). 2 Peter 2:11 says, "Whereas angels, which are greater in power and might, bring not railing accusation against them before the Lord." This is also likely an allusion to Enoch 9. Jude and Peter are traditionally said to be discussing the punishment for the angels responsible for the Nephilim in Genesis 6 (historically thought to be an instance of incubus).
Disclaimer / Limitation: I am working with a critical text of the book of Enoch from 1909 (Swete). I do not have any critical texts for Enoch that are more recent. I found the Skeptik Greek text for Enoch online when researching this which supports my finding for Enoch 20:7. However, it seems that many English translations had to have been working from different manuscripts, as there is an additional name in 9:1 and other phrases throughout Enoch that were not in the Greek manuscripts that I had available (unless these translations are faulty, which is also a possibility - but I have not conducted enough research to make this assertion). But the main translation that differs from Swete's Greek text (by R.H. Charles) was published in 1913, so theoretically the same manuscripts should have been available. It should also be noted that I did not have a Greek manuscript for the verse in 2 Esdras (there may not be one), I used the English KJV translation.
Meaning of the Word
The ἀρχ- prefix is associated with the Greek word ἄρχων, meaning "ruler" (a substantival participle literally meaning "ruling one"). It is used in interesting ways throughout scripture and early Christian history in reference to angels. The word derives from ἀρχή, which is usually translated as "beginning" (which is the gloss), but can also mean,
"an authority figure who initiates activity or process, ruler,
authority.... Also of angelic or transcendent powers, since they were
thought of as having a political organization (Damascius, Princ. 96
R.) Ro 8:38; 1 Cor 15:24; Eph 1:21; 3:10; 6:12; Col 1:16; 2:10,
15..."1
(such as its peculiar use in Jude 6 which is relevant to this discussion).
The word also appears in other early Greek literature in case you're interested in the references:
ἀρχάγγελος, ου, ὁ (s. ἀρχή, ἄγγελος; En 20:8; TestSol; TestAbr A B;
TestLevi 3:5 v.l.; ParJer 9:5; GrBar; ApcEsdr 1:3 p. 24, 7 Tdf.;
ApcSed 14:1 p. 135, 33 Ja.; ApcMos; AssMos Fgm. k; Philo, Confus.
Lingu. 146, Rer. Div. Her. 205, Somn. 1, 157; Porphyr., Ep. ad
Anebonem [GParthey, Iambl. De Myst. Lib. 1857 p. xxix–xlv] c. 10; cp.
Iambl., Myst. 2, 3 p. 70, 10; Theologumena Arithmetica ed. VdeFalco
1922, p. 57, 7; Agathias: Anth. Pal. 1, 36, 1; ins in CB I/2 557 no.
434 ὁ θεὸς τῶν ἀρχαγγέλων; Gnost. ins, CIG 2895; PGM 1, 208; 3, 339;
4, 1203; 2357; 3052; 7, 257 τῷ κυρίῳ μου τῷ ἀρχαγγέλῳ Μιχαήλ; 13, 257;
328; 744) a member of the higher ranks in the celestial hierarchy,
chief angel, archangel PtK 2 p. 14, 27. Michael (En 20:5; 8; ParJer
9:5) is one of them Jd 9. He is also prob. the archangel who will
appear at the last judgment 1 Th 4:16 (the anonymous sing. as PGM 4,
483, where the archangel appears as a helper of Helios Mithras).—See
WLueken, D. Erzengel Michael 1898; Rtzst., Mysterienrel.3 171, 2;
UHolzmeister, Verb. Dom. 23, ’43, 176–86; s. on ἄγγελος.—149–53. M-M.
TW.2
Jesus = Michael?
Concerning the equation of Jesus with Michael, some scholars3 believe that the early Christian book The Shepherd of Hermas (which was considered canonical by many Christians in the second and third centuries, although not without much controversy) equates Jesus with Michael (this is disputed among historians)4. Primitive Christology understood Christ as the "prince of angels," but this debate was refuted by later debates in Christian history and The Shepherd of Hermas was rejected as heretical (both for teaching Adoptionism and for equating Jesus with Michael), especially on the basis of Hebrews 1 which had much greater support in post-Nicene Christianity.5 The equation of Jesus with Michael did not become a topic of contention in Christian history again until the 19th century.
Conclusion
The answer to your question really depends on what books you consider to be the Bible. Assuming you are operating with a mainstream historic Christian understanding of the biblical canon6 (which would exclude Enoch), the Bible does not specifically name any other archangels other than Michael. However, on the basis of other Christian texts such as Enoch as well as Jewish and Christian history, it would not be advisable to consider Michael to be the only archangel. The Biblical text does not imply this anywhere (it makes no implications one way or the other), nor is it supported by other texts and historic traditions.
1 William Arndt, Frederick W. Danker and Walter Bauer, A Greek-English Lexicon of the New Testament and Other Early Christian Literature, 3rd ed. (Chicago: University of Chicago Press, 2000), 138.
2 Ibid., 137.
3 Jaroslav Pelikan, The Christian Tradition: A History of the Development of Doctrine: Volume One - The Emergence of the Catholic Tradition (100-600), (Chicago: University of Chicago Press, 1971), 183.
4 cf. Shepherd of Hermas 69:3. Relevant quote produced below:
"And the great and glorious angel Michael is he who has authority over this people, and governs them; for this is he who gave them the law into the hearts of believers: he accordingly superintends them to whom he gave it, to see if they have kept the same."
"The Pastor of Hermas", trans. F. Crombie, in The Ante-Nicene Fathers, Volume II: Fathers of the Second Century: Hermas, Tatian, Athenagoras, Theophilus, and Clement of Alexandria (Entire), ed. Alexander Roberts, James Donaldson and A. Cleveland Coxe (Buffalo, NY: Christian Literature Company, 1885), 40. This can be read online.
5 Pelikan, 183-184.
6 It is regarded as canonical by the Ethiopian Orthodox Tewahedo Church and the Eritrean Orthodox Tewahedo Church. The Church of Jesus Christ of Latter-day Saints (LDS/Mormons) does not consider it to be canonical but does consider it to be inspired. Everyone else excludes it (including most of the Eastern Orthodox Church except for those noted above).
| {
"pile_set_name": "StackExchange"
} |
Q:
new kinect-PC tutorial
I am trying to build a game for kinect which has been just released on this Feb.
I was trying to find the tutorial for this because I am really new to this platform.
Could anyone please tell me some good tutorials for this?
Thank you
A:
For kinect sdk official apps, you have to look for channel 9. There is no a lot tuttorial right now (books..etc) But if you want to look another frameworks like OpenNi (The OpenNI organization is an industry-led, not-for-profit organization formed to certify and promote the compatibility and interoperability of Natural Interaction (NI) devices, applications and middleware.)you can check kinecthacks which is non official. There is only one book at the market right now, named meet the kinect which is not only about kinect sdk but its good for starting, but after 1 month there will be more good books about hacking kinect sdk.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java - JSONArray has 10 objects but only display first two
I'm new to Android and Java so I'm building a demo app of book listing to learn about parsing JSON data. I use log to check how many books there are on data (which is 10 ) but only get 2 first books on the list displayed when running it on an emulator... Hope anyone can tell me where I should change?
Thanks for any opinion!
E/QueryUtils: length of array: 10
The API link: https://www.googleapis.com/books/v1/volumes?q=search+terms
QueryUtils.java
private static List<BookItem> extractItemFromJson(String bookJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(bookJSON)){
return null;
}
// Create an empty ArrayList that we can start adding books to
List<BookItem> bookItems = new ArrayList<>();
// Try to parse the JSON response string. If there is a problem with the way the JSON is formatted,
// a JSONException exception object will be thrown.
// Catch the exception so the app doesnt crash, and prent the error message to the logs.
try {
JSONObject baseJsonresponse = new JSONObject(bookJSON);
JSONArray bookItemArray = baseJsonresponse.getJSONArray("items");
Log.e("QueryUtils", "length of array: " + bookItemArray.length());
for (int i = 0; i < bookItemArray.length(); i++) {
JSONObject currentBook = bookItemArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
String title = volumeInfo.getString("title");
String subtitle = volumeInfo.getString("subtitle");
String previewLink = volumeInfo.getString("previewLink");
JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
String thumbnail = imageLinks.getString("smallThumbnail");
BookItem book = new BookItem(/**author, */title, subtitle, thumbnail, previewLink);
bookItems.add(book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
return bookItems;
}
A:
The third book in your list does not cointain the field imageLinks, and that causes an exception.
You should add a check:
String thumbnail = "";
if (volumeInfo.has("imageLinks")) {
JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
thumbnail = imageLinks.getString("smallThumbnail");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding dynamic row to ngTable not displaying
I have created an application with ngTable using grouping functionality, The application is working fine but the problem is that when I add dynamic data (rows) to the table, its not reflecting dynamically, unless or otherwise when we click the table title for sorting or when we click the pagination
I have recreated the problem within a plunker, there you can find a button, when clicked one Dynamic row is added but not reflecting within the table
PLUNKER
<body ng-app="main" ng-controller="DemoCtrl">
<button ng-click="addDynamicDatas()">Add Datas</button>
<table ng-table="tableParamsOne" class="table">
<tbody ng-repeat="group in $groups">
<tr class="ng-table-group" ng-hide="group.data[0].role==='None'">
<td>
<strong>{{ group.value }}</strong>
</td>
</tr>
<tr ng-repeat="user in group.data">
<td sortable="name" data-title="'Name'">
<span ng-class="{'bold-text': user.role=='None'}" ng-show="user.role==='None'"> {{user.name}}</span>
</td>
<td sortable="age" data-title="'Age'">
{{user.age}}
</td>
</tr>
</tbody>
</table>
</body>
add function
$scope.addDynamicDatas = function()
{
$scope.myDataOne.push({name: "Abcd", age: 10, role: 'Administrator'});
}
Can anyone please tell me some solution for this?
A:
This is probably not an ideal solution but is the only one that I could find.
You can add $scope.tableParamsOne.reload(); after you update your array.
Also currently when your grid is updating when you click a header it is not updating the amount of pages in the pagination. To solve this you can add $scope.tableParamsOne.total($scope.myDataOne.length);
| {
"pile_set_name": "StackExchange"
} |
Q:
variadic function in C
1) Why code under /* test1 */ chunk do not print out anything, but code under /* test2 */ print correctly?
2) How to use va_arg(va, char*) in /* test 1 */ code chunk.
void rdfDBG(int dbglevel, const char *fmt, ...) {
va_list va;
#if 1 /* test 1 */
char* logbuf;
if ((logbuf = calloc(0x0, LOGBUFFERSIZE))== NULL)
fprintf(stderr, "out of memory\n"); /* 1. Is there a better way instead of using fprintf? */
va_start(va, fmt);
(void) vsnprintf(logbuf, strlen(logbuf), fmt, va); /* 2. print nothing */
va_end(va);
free(logbuf);
#endif
#if 0 /* test 2 */
va_start(va, fmt);
vprintf(fmt, va); /* 2. print "pinfile pings6.txt" */
va_end(va);
#endif
}
int ptInitialize(){
char* pinfile;
pinfile = "pings6.txt";
rdfDBG(kINFO, "pinfile %s\n", pinfile);
return 0;
}
A:
The code under /* test 1 */ doesn't print anything because the vsnprint() function doesn't print to stdout; it just writes its output into the provided buffer.
It's pure luck if the code didn't crash, though, because the line:
if ((logbuf = calloc(0x0, LOGBUFFERSIZE))== NULL)
actually tells calloc() to allocate 0 bytes of memory. Because of this, I don't think it's guaranteed that the memory logbuf points at is zeroed either -- so not only is your buffer zero bytes long, but calling strlen() on it could crash or give you an invalid result.
Also, the second argument to vsnprint() is supposed to be the size of the buffer, that is the size you've allocated for logbuf, not the length of any string already in it; it's to limit the number of bytes written to the buffer to avoid a buffer overrun.
So to get everything working, you need to change:
if ((logbuf = calloc(0x0, LOGBUFFERSIZE))== NULL)
..to..
if ((logbuf = calloc(1, LOGBUFFERSIZE))== NULL)
..to allocate space for 1 item of LOGBUFFERSIZE bytes. And also change:
(void) vsnprintf(logbuf, strlen(logbuf), fmt, va);
..to..
vsnprintf(logbuf, LOGBUFFERSIZE, fmt, va);
..to pass it the size of your buffer and remove the useless (void) cast. And also add a line to print logbuf, such as:
fputs(logbuf, stderr);
after it.
A:
This:
vsnprintf(logbuf, strlen(logbuf)...
Will never format anything, because logbuf is all zeros (having been allocated by calloc, and so strlen will return zero, which makes vsnprintf never format anything because you told it to print at most zero characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP classes and static variables - Should I use __destruct()?
I have a class that's similar to the following:
class Person
{
private static $_sqlData;
public function __construct($id)
{
if (!self::$_sqlData)
{
self::$_sqlData = // GET THE DB STUFF
}
}
public function getName()
{
return self::$_sqlData['name'];
}
}
This has been working fine until I needed to place it in a loop.
foreach ($ids as $id)
{
$person = new Person($id);
echo $person->getName();
}
This continues to return the first persons name rather than all the names for the given IDs. The reason being the static variable.
I've overcome this by adding in a __destruct() function to set $_sqlData to false then calling unset() on $person in the foreach() loop.
Is this a good way of handling this? Should I be approaching this differently?
A:
Why are you using a static variable? Is there something that you need this for? It seems like not using a static var for the $_sqlData, just using an instance variable, would give you the same result, unless there is something your not showing us.
A instance variable will destruct, just like you are doing manually to your static variable.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to inject toaster library into logging module without getting circular dependency error in exception handler
I have added the AngularJS-Toaster library to my index.html:
<link href="lib/angularjs-toaster/toaster.min.css" rel="stylesheet" />
<script src="lib/angularjs-toaster/toaster.min.js"></script>
<toaster-container
toaster-options="{'position-class': 'toast-bottom-center'}">
</toaster-container>
And in my angular app:
//app.js
(function () {
angular
.module('app', ['toaster','blocks.logger',/*etc*/]);
})();
//blocks/logger/logger.module.js
(function () {
angular.module('blocks.logger', ['toaster']);
})();
//blocks/logger/logger.js
(function () {
'use strict';
angular
.module('blocks.logger')
.factory('logger', logger);
logger.$inject = ['$log', 'toaster'];
function logger($log, toaster) {
var service = {
error: error,
info: info,
success: success,
warning: warning,
log: $log.log // straight to console;
};
return service;
function error(message, title, data) {
toaster.error({ title: title || 'Error', body: message, timeout: 6000 });
$log.error(message, data);
}
//etc
}());
But when I do this I get a circular dependency error from the injector: Uncaught Error: [$injector:cdep]
What am I doing wrong?
EDIT
I have discovered that the problem is related to an exception handler that I have used:
//code lifted from https://github.com/johnpapa/ng-demos (modular)
(function () {
'use strict';
angular
.module('blocks.exception')
.provider('exceptionHandler', exceptionHandlerProvider)
.config(config);
function exceptionHandlerProvider() {
/* jshint validthis:true */
this.config = {
appErrorPrefix: undefined
};
this.configure = function (appErrorPrefix) {
this.config.appErrorPrefix = appErrorPrefix;
};
this.$get = function () {
return { config: this.config };
};
}
function config($provide) {
$provide.decorator('$exceptionHandler', extendExceptionHandler);
}
//function extendExceptionHandler($delegate, exceptionHandler, logger) {
function extendExceptionHandler($delegate, exceptionHandler) {
return function (exception, cause) {
var appErrorPrefix = exceptionHandler.config.appErrorPrefix || '';
var errorData = { exception: exception, cause: cause };
var logMessage = appErrorPrefix + exception.message;
$delegate(exception, cause);
//logger.error(logMessage, errorData);
};
}
})();
By commenting out the use of the logger, I can use logging elsewhere. But I'd like to use my logger here too. So what is going on and how do I fix it?
A:
I found a solution - use $injector in the exception handler:
//blocks/exception/exception.module.js
(function () {
'use strict';
angular.module('blocks.exception', ['blocks.logger']);
})();
//blocks/exception/exceptionHandlerProvider.js
(function () {
'use strict';
angular
.module('blocks.exception')
.config(exceptionConfig);
exceptionConfig.$inject = ['$provide'];
function exceptionConfig($provide) {
$provide.decorator("$exceptionHandler", exceptionHandler);
}
exceptionHandler.$inject = ['$delegate', '$injector'];
function exceptionHandler($delegate, $injector) {
return function (exception, cause) {
var logger = $injector.get('logger');
logger.error(exception.message);
$delegate(exception, cause);
};
}
})();
References:
$log decorator with a service dependency causes circular dependency error
Angular style guide - exceptions
| {
"pile_set_name": "StackExchange"
} |
Q:
use i tag in @Html.ActionLink
I want to use same HTML design in my ASP .Net MVC application
<li>
<a href"#">
<i class="fa fa-cog"></i>
"Account Settings"
</a>
</li>
This must show the settings icon and "Account Settings" in same line but using this in ASP.Net shows the icon and text in different lines
<li>
<i class="fa fa-cog">
</i>
@Html.ActionLink("Account Settings", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
i need help that to use this tag with @Html.ActionLink function?
A:
This is not possible with an ActionLink.
You could use URL.Action instead like so.
<a href="@Url.Action("Index", "Manage")"><i class="fa fa-cog"></i> Account Settings</a>
Or just use a standard link
<a href="~/manage"><i class="fa fa-cog"></i> Account Settings</a>
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing x position of SKSpriteNode
I am running a for loop in my game that would generate SKSpriteNodes.
I want my first block to start at (20, 40) and add 20 to the x position and 40 to the y position for every new block.
First block (20, 40)
Second block (40, 80)
Third Block (60, 120)
And so on.
The y position is behaving the way I want to, however the x position would randomly start anywhere on my screen then add 20 for every new block generated.
Below is my code.
func generateBlocks() {
for _ in 1..<5 {
xP += 20
yP += 40
let xx = CGFloat (xP)
let yy = CGFloat (yP)
print("x position: \(xx)")
print("y position: \(yy)")
let resourcePath = NSBundle.mainBundle().pathForResource("Blocks", ofType: "sks")
let blocks = MSReferenceNode(URL: NSURL (fileURLWithPath: resourcePath!))
blocks.goals.position = CGPoint (x: xx,y: yy)
addChild(blocks)
}
}
I also added the print statement of how it would look like when I run the code.
Below is the print statement of the x and y positions of the blocks.
I tried switching the order of the xP and yP initializing. That didn't work.
Any suggestions?
A:
I would prefer to use while loops for this kind of operations where you must impose a condition from start, for example limits:
class GameScene: SKScene {
let deltaX:CGFloat = 20.0
let deltaY:CGFloat = 40.0
override func didMoveToView(view: SKView) {
let widthLimit = self.frame.width-40
let heightLimit = self.frame.height-140
let startX:CGFloat = 80.0
drawStair(startX,limits:CGSizeMake(widthLimit,heightLimit))
}
func drawStair(startFromX:CGFloat,limits:CGSize) {
var currentX:CGFloat = startFromX
var currentY:CGFloat = startFromX+deltaY
while currentX<limits.width && currentY<limits.height {
drawBlock(CGPointMake(currentX,currentY))
currentX += deltaX
currentY += deltaY
}
}
func drawBlock(position: CGPoint,size:CGSize = CGSizeMake(40,40)) {
let block = SKSpriteNode(color: UIColor.redColor(), size: size)
block.position = position
block.name = "block"
addChild(block)
}
}
Output:
| {
"pile_set_name": "StackExchange"
} |
Q:
Increment variable in ruby
In Java, something like i++ would increment i by 1.
How can I do in Ruby? Surely there has to be a better way than i = i + 1?
A:
From the documentation,
Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse
So, you can do
i += 1
which is equivalent of i = i + 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Where is the command `gnome-display-properties`
After upgrading from Ubuntu 11.04 to 13.10, the command gnome-display-properties is gone. I can open it via gnome-control-center.
How can I open this dialogue just with a command?
A:
You can use:
gnome-control-center display
See man gnome-control-center for more info.
| {
"pile_set_name": "StackExchange"
} |
Q:
Optimal SQL Server Reporting Services setup
I'd like to determine an optimal setup for SQL Server Reporting Services to use as the integrated reporting tool for SaaS web-based applications. All reports are pre-defined, so users pick a report and enter some parameters in a web-based front end. Parameters are then passed to the report, which pulls the data, formats the results, and returns a PDF or Excel file to the web application.
While we have existing SQL Servers supporting our web apps, none have Reporting Services installed. Options include:
1) add Reporting Services to an existing SQL Server instance
2) create a new instance on a physical server that already runs SQL Server and use that new SQL instance for Reporting Services
3) have a separate physical server for Reporting Services
While #3 is optimal, it also costs an additional SQL Server license, which is not cheap. I don't know if I gain much with option #2, other than some stability. Option #1 may be the path of least resistance, but I understand that there's some considerable overhead caused by SSRS and I don't want too much of a performance hit.
Anyone need to do something like this? Anecdotes and opinions welcome.
A:
You didn't indicate what version of SQL Server. Keep in mind SSRS 2005 requires IIS installed on the box as well. SSRS 2008 does not. It uses HTTP.SYS natively. The optimal answer is #3, however, it really depends on the existing load on the physical server as well as the type of reports you would be running. #1/#2 are essentially the same option with respect to performance.
The truth is, without knowing the performance characteristics, no one here can tell you the best option. Your best path is to get a good idea of how your SQL Servers are performing today, to set up a small dev SSRS environment and profile it as you test the reports, and then make the decision for there. If you're not sure where to start on getting a performance profile on your SQL Servers, allow me to recommend:
Brent Ozar's posts on Performance Tuning
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.