text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Probabilities, Unigram and Bigram
Assume that we have these bigram and unigram data:( Note: not a real data)
bigram:
#a(start with a) =21
bc= 42
cf= 32
de= 64
e#= 23
unigram:
# 43
a= 84
b=123
c=142
f=161
d=150
e=170
what is the probability of generating a word like "abcfde"?
I think for having a word starts with a the probability is 21/43. How about bc? is it like bc/b?
A:
Augment the string "abcde" with # as start and end markers to get #abcde#. Now, as @Yuval Filmus pointed out, we need to make some assumption about the kind of model that generates this data. Because we have both unigram and bigram counts, we can assume a bigram model. In a bigram (character) model, we find the probability of a word by multiplying conditional probabilities of successive pairs of characters, so:
$\Pr[\#abcde\#] = \Pr(a|\#)*\Pr(b|a)*\Pr(c|b)*\Pr(d|c)*\Pr(e|d)*\Pr(\#|e) $
To find the conditional probability of a character $c_2$ given its preceding character $c_1$, $\Pr(c_2|c_1)$, we divide the number of occurrences of the bigram $c_1c_2$ by the number of occurrences of the unigram $c_1$.
So, for example $\Pr(e|d) = count(de)/count(d) = 64/150$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
computing recall and precision with tensorflow
I am running a NN model with TF which runs smooth (this code can be found at https://pythonprogramming.net/). I would like to add a few lines to compute true and false positive/negative together with precision and recall. I tried many sum functions but objects in Python are not that familiar to me. I cannot run sk since I want to work with TF and that brings limitations on the version of Python that I use. Thanks for help.
import pandas as pd
import tensorflow as tf
import numpy as np
import random
from random import shuffle
train_x = pd.read_csv('train_x.csv')
train_y = pd.read_csv('train_y.csv')
test_x = pd.read_csv('test_x.csv')
test_y = pd.read_csv('test_y.csv')
n_nodes_hl1 = 30
n_nodes_hl2 = 30
n_nodes_hl3 = 30
n_classes = 2
batch_size = 2000
x = tf.placeholder('float', [None, 61])
y = tf.placeholder('float')
def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([61, n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes])),}
l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']), hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)
l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)
output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']
return output
def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)
hm_epochs = 10
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epochs):
epoch_loss = 0
i = 0
while i < len(train_x):
start = i
end = i + batch_size
batch_x = np.array(train_x[start:end])
batch_y = np.array(train_y[start:end])
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
epoch_loss += c
i += batch_size
print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:',accuracy.eval({x:test_x, y:test_y}))
train_neural_network(x)
I tried the following:
argmax_prediction = tf.argmax(prediction, 1)
argmax_y = tf.argmax(y, 1)
TP = tf.count_nonzero(argmax_prediction * argmax_y, dtype=tf.float32)
TN = tf.count_nonzero((argmax_prediction - 1) * (argmax_y - 1), dtype=tf.float32)
FP = tf.count_nonzero(argmax_prediction * (argmax_y - 1), dtype=tf.float32)
FN = tf.count_nonzero((argmax_prediction - 1) * argmax_y, dtype=tf.float32)
precision = TP / (TP + FP)
recall = TP / (TP + FN)
print ("Precision", precision)
print ("Recall", recall)
And I get
Precision Tensor("truediv:0", dtype=float32)
Recall Tensor("truediv_1:0", dtype=float32)
A:
Since you are formulating Precision and recall as tensor you need to use tensorflow session to get the values
how did you get prediction?
prediction = some_function(x)
# x is your input placeholder for prediction
# y is the input placeholder for ground-truths
sess=tf.Session()
precision_, recall_ = sess.run([precision, recall], feed_dict={x: input, y: ground_truths})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PowerShell Invoke-WebRequest uncorrect results with the parameter page for Boursorama
I'm trying to get data from the boursorama website, but when I send the request with the parameter "page", the result is the same if page = 1 or page = 50.
The URL is the following : http://www.boursorama.com/bourse/derives/turbos/
My goal is to get a list of products which are in the webpart called "Rechercher des Turbos, Call ou Put".
Following is the request :
$Data = Invoke-WebRequest -Method Post -URI "http://www.boursorama.com/ajax/ui/refresh.phtml/boursorama/block/bourse/derives/search/turbos?page=30" -Headers @{"X-Brs-Xhr-Request"="true";"X-Requested-With" = "XMLHttpRequest"} -body "parameters[page]=30&class=Boursorama_Block_Bourse_Derives_Search_Turbos"
$Data.content
A:
Not sure but you can try :
$r=iwr http://www.boursorama.com/bourse/derives/turbos/?page=30
$r.ParsedHtml.getElementsByTagName('td') |?{$_.classname -eq 'tdv-isin'} |select innerHTML
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to integrate Balloonpanel plugin into my editor?
I try to integrate balloonpanel plugin to my editor.
I use the code from the docs.
editor.on( 'instanceReady', function() {
var toolbar = new CKEDITOR.ui.balloonToolbar( editor );
toolbar.addItems( {
link: new CKEDITOR.ui.button( {
command: 'link'
} ),
unlink: new CKEDITOR.ui.button( {
command: 'unlink'
} )
} );
editor.on( 'selectionChange', function( evt ) {
var lastElement = evt.data.path.lastElement;
if ( lastElement ) {
toolbar.attach( lastElement );
}
} );
} );
But, when I click on the editor it will give the below error message.
And the doc link is provided below
Balloonpanel Docs Link
I don't know what it means.
Update:(Attache code)
My Original code Looks like this,
<body>
<textarea id="editor1"></textarea>
<script>
CKEDITOR.replace('editor1', {
toolbarGroups: [{
name: 'basicstyles'
}, {
name: 'authorgroup'
}],
removePlugins: 'indent,indentblock,indentlist,list,removeformat,table,tabletools,entities,menu,find,font,iframe,pagebreak,flash,print,preview,save,smiley,pastetext,crossreference,youtube,footnotes,dragdrop,basket,horizontalrule,indentlist,image,format,selectall,specialchar,spellchecker,pastefromword,showblocks,link,unlink,anchor,copyformatting',
extraPlugins: 'indentmodify,indentblockmodify,indentlistmodify,listmodify,removeformatmodified,table1,tabletools1,entitiesmodified,menumodified,findmodified,stylesheetparser,characterStyle,zoom,eventhandler,navigate,comment,symbol,notification,authorproff,proffpara,Newcitation,customfootnotes,floatingmenu,pubsearch,balloontoolbar,balloonpanel,autocorrect'
});
//My instanceReady Code Goes Here
</script>
</body>
A:
I checked this code sample with fresh CKEditor instance and it works fine. You are giving us too little information to get any solid answer.
To run this sample without errors or odd behavior you should include wysiwygarea,toolbar,link,balloontoolbar plugins to your CKEditor configuration. Visit Setting CKEditor configuration if you need some help with it.
If it doesn't solve your problem show us some code or try to reproduce the issue with minimal configuration.
Codepen working sample.
I have to mention that it could not work as expected because we have some issue with balloonpanel positioning for a selection. You can find more information about actual status of the issue on github
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android onscreen joystick issues
So I'm trying to build a game with an on-screen joystick that moves a bitmap around the screen. But when I hold the joystick down in any direction and keep it there, the bitmap will stop moving as well. Its only when I am moving the joystick does the bitmap move. Basically I want to be able to hold down the joystick in say the left position and have the bitmap move left until I let go. Everything else in the code works. Any suggestions?
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
_dragging = true;
else if (event.getAction() == MotionEvent.ACTION_UP)
_dragging = false;
_touchingPoint = new Point();
if (_dragging) {
// get the pos
int x = (int) event.getX();
int y = (int) event.getY();
_touchingPoint.x = x;
_touchingPoint.y = y;
double a = _touchingPoint.x - initx;
double b = _touchingPoint.y - inity;
controllerDistance = Math.sqrt((a * a) + (b * b));
if (controllerDistance > 75) {
a = (a / controllerDistance) * 75;
b = (b / controllerDistance) * 75;
_touchingPoint.x = (int) a + initx;
_touchingPoint.y = (int) b + inity;
}
bitmapPoint.x += a * .05;
bitmapPoint.y += b * .05;
} else if (!_dragging) {
// Snap back to center when the joystick is released
_touchingPoint.x = initx;
_touchingPoint.y = inity;
}
}
A:
It was because I only had the code to increment the bitmaps location in the onTouch method.
When the screen is being touched but not moving a event is not registered. The code below should be outside the onTouch method.
bitmapPoint.x += a * .05;
bitmapPoint.y += b * .05;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I get notified when a specific user makes a new post?
Suppose I work/learn on/about a specific subject, let's say JPA, after making searches and asking questions on SO, I've noticed that some person is very good at JPA and it would be very interesting to be notified about his posts. Is it possible to be told about their new activities on SO?
I think that it would be interesting to have this feature in this situation.
A:
This feature already exists.
If you go to a user's 'Activity' tab, you'll see that all the way at the bottom, under the votes, there's a user feed link:
This will give you an RSS feed for all contributions by that user, including answers and comments.
I will caution you, however, that this feature is not meant to be used for you to upvote all posts by a user. Vote for the post, not for the person; voting based on who posted it considered abusive behavior and you could be suspended for it. So be careful - don't use this to upvote all new posts by one specific user.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you indicate line breaks in a poem when it is written without actual line breaks?
In English, if you have a poem, like
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
and you need to write it on just one line (for reasons of space or whatever), you would write it like this:
Roses are red, / violets are blue, / sugar is sweet, / and so are you.
That is, you use a single forward slash to separate the lines of the poem.
What is the equivalent of this in Japanese? I know that in some cases, you can just omit the line breaks altogether, e.g. writing
古池や
蛙飛び込む
水の音
as
古池や蛙飛び込む水の音
But supposing you did need to indicate the line breaks, how would you do so?
A:
Japanese doesn't traditionally use spaces, so a space will indicate a line break. For example,
八雲立つ 出雲八重垣 妻籠みに 八重垣作る その八重垣を
Which, if choose to write it in rōmaji, is
Yakumo tatsu / Izumo yaegaki / Tsuma-gomi ni / Yaegaki tsukuru / Sono yaegaki wo
I will say, however, texts containing poems would almost always be written vertically, so the need to write a poem horizontally is rare.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Single site web proxy
I want to create a dynamic mirror or a single site web proxy for my blog on a different domain. I have access to a php based web hosting, I own the content on the original site and due to low traffic I think bandwidth is not a issue at all. What would be the best way to proceed?
To provide some context, my real problem is:
- I have a blog hosted on blogger with a custom domain. (e.g. www.abc.com)
- Blogger as a whole is blocked in some countries which effectively makes my blog blocked effectively.
- I own another domain www.def.com and a hosting and all I want is www.def.com to be a dynamic mirror of www.abc.com.
Redirecting will not work because, it will not really bypass the blocking filters.
I am happy with the service of blogger and I do not really want to move or duplicate things.
Before I did not have this problem because blogger allowed me to use ftp and upload stuff on a different hosting server but is not a n option any more.
A:
You could just sign up for CloudFlare. It takes your site and caches it on its network. It may help others reach your blog. I have it set up on my site.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the purpose of each of the different UNIX/Linux shell startup files?
Previously, when setting up a *NIX environment for the first time, I would put all of my shell customisations into .bashrc, with the following .bash_profile:
if [ -f $HOME/.bashrc ]; then
. $HOME/.bashrc
fi
However, based on this answer and its associated comments, I've recently moved my PATH redefinition into .bash_profile.
What types of commands do you feel should go into .profile, .bash_profile, .bashrc (and any other dotfiles), and why?
A:
They are read or not read in a specific order based on how the shell is invoked. The invocation section of 'man bash' will give the order and when they are read. It depends on if the shell is invoked as a interactive and/or login shell.
This link will tell you the 'why'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Frank-Wolfe Algorithm
Do you know any implementation, (java) to solve non linear programming with this algorithm? Could you explain that algorithm, or the code?
A:
Wikipedia has some pretty good pseudocode.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to login to a server as a mysql user in order to stop the mysql server?
I have a linux server instance hosted by RunAbove where I log in as an 'admin' user using an ssh key.
I need to change the mysql root password on the server manually. I'm following directions given here
The problem I have is that I log in to the server as an 'admin' user while the 'mysqld' process is owned by 'mysql' user (this process below):
Feb21 54:48 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib/mysql/plugin --user=mysql --log-error=/var/log/mysql/error.log --pid-file=/var/run/mysqld/mysqld.pid
I need to send kill signal to mysqld.pid, but I'm not able to do it even if I execute it with sudo as an 'admin' user.
RunAbove allows me to ssh into the only server as 'admin'.
What are my options here?
A:
if you have the password of root of mysql or any user with full controll of mysql, you can use mysqladmin in this way:
mysqladmin -u root -p shutdown
You can login as root in your server and use the script of your distribution to stop mysql
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cardboard Mockup Scene for Hololens Look and Fell
I didn't know which forum to ask about this is the most fitting, but I think this is the best:
Our designers want to check their stuff on the hololens. For example to check if their gui is right and how the depth effect is. But we dont have that many hololenses and the developer don't have the time to load up the designers' projects for checking.
So my question is:
Is there an plugin or Scene, in which they can load their stuff and export/build it for vr (cardboard or at least htc vive) and have the same look and feel like the holo lens (just with a 3d world?). It's mostly for some fancy 3D iron man Style ui (for now).
A concrete Problem:
They have a animated loading Circle(s). They want to check if you look straight on it at the holo lens or if you have a to big perspective distortion or occlusion. Also it would be nice if the small FOV would be simulated.
I'm kinda searching a hololens vr simulator for unity scene/script
A:
Sry for the long silence (had other Stuff to do):
The other answering Persons have good Solutions, but i just want to make an Overview of things that helped me on the way. When I asked the questions i had the Hololens like 3 Days and no Idea of it:
Checking Clipping/Lost of sight:
Set the Camera FOV to 55 the aspect ratio to 16:9. Also if you import the Camera from the Toolkit you can change the eye from the Settings. Also set the Clipping Plane to 0.75. Objects closer than this will only be shown on one eye.
As Dtb49 said: "use he Holographic Remoting App on your HoloLens. Once you do that in the Unity editor you can go to Window->Holographic Emulation->Remote To Device and type in the IP address displayed when you launch the app from your HoloLens." The Problem is you need the Fall Creators Update for that (and your Admin won't let you update). And it's very laggy (in my case)
Or use the emulator as Gambolati said.
Last but not least my favorite way now: Use the "Manual Gaze Control" Script from the Toolkit and attach to the cam and use the "Input Manager Prefab". The EditorHandsInput is needed. No you can emulate interactions in the Playmode.
PS: To check the 3D Experience Cardboard is not usefull. It's just another experience.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compute $\operatorname{Cov}(X,Y)$ while $X$ is the sum of the two rolls and $Y$ is the number of $2$s in the two rolls
I think I should start by defining $Y_i$ by: $Y_i=1$ if at the $i$-th roll number $2$ occurs an $0$ otherwise.
And define $X_i$ as $R_1+R_2$.
But I do not know how to proceed. How would I use the formula $\operatorname{Cov}(X,Y)=E[XY]-E[X]E[Y]$ ?
A:
The expected number of $2$s each time you throw the die is $1/6.$ Therefore the expected number in two tosses is $1/3,$ i.e. $\operatorname E(Y) = 1/3.$
The expected outcome when a die is thrown is $(1+2+3+4+5+6)/6 = 7/2 = 3.5;$ therefore the expected sum in two trials is $7,$ i.e. $\operatorname E(X) =7.$
So what is $\operatorname E(XY)\text{ ?}$
One way is just brute force: First look at the list of $36$ outcomes:
$$
\begin{array}{cccccc}
1,1 & 1,2 & 1,3 & 1,4 & 1,5 & 1,6 \\
2,1 & 2,2 & 2,3 & 2,4 & 2,5 & 2,6 \\
3,1 & 3,2 & 3,3 & 3,4 & 3,5 & 3,6 \\
4,1 & 4,2 & 4,3 & 4,4 & 4,5 & 4,6 \\
5,1 & 5,2 & 5,3 & 5,4 & 5,5 & 5,6 \\
6,1 & 6,2 & 6,3 & 6,4 & 6,5 & 6,6
\end{array}
$$
What is the number of $2$s? Here it is:
$$
\begin{array}{cccccc}
0 & 1 & 0 & 0 & 0 & 0 \\
1 & 2 & 1 & 1 & 1 & 1 \\
0 & 1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0
\end{array}
$$
This of course will tell you that $Y = \begin{cases} 0 & \text{with probability } 25/36, \\ 1 & \text{with probability } 10/36, \\ 2 & \text{with probabiltiy } \phantom{0}1/36. \end{cases} \qquad$ So this is another way of seeing that $\operatorname E(Y) = 1/3.$
But now multiply the numbers above by the sum:
$$
\begin{array}{cccccc}
0 & 3 & 0 & 0 & 0 & 0 \\
3 & 8 & 5 & 6 & 7 & 8 \\
0 & 5 & 0 & 0 & 0 & 0 \\
0 & 6 & 0 & 0 & 0 & 0 \\
0 & 7 & 0 & 0 & 0 & 0 \\
0 & 8 & 0 & 0 & 0 & 0
\end{array}
$$
The sum of these is $66,$ so their average is $\dfrac{66}{36}= \dfrac{11}{12}.$
Thus
$$
\operatorname{cov}(X,Y) = \operatorname E(XY) - \operatorname E(X)\operatorname E(Y) = \frac{11}{12} - \left( 7 \times \frac 1 3\right) = \frac{11}{12} - \frac{21}{12} = \frac{-10}{12} = \frac {-5} 6.
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cant import socket module
i've written the following script on PyCharm IDE:
import socket
import time
sock = socket(socket.AF_INET, socket.SOCK_DGRAM)
hexpacket "00 FF"
ip = raw_input('Target IP: ')
port = input('Port: ')
duration = ('Number of seconds to send packets: ')
timeout = time.time() + duration
sent = 0
while True:
if time.time() > timeout:
break
else:
pass
sock.sendto(hexpacket,(ip,port))
sent = sent +1
print "Send %s packet to %s through ports %s"(send, ip, port)
I get an output from the console of:
TypeError: 'module' object is not callable
I have tried to change the "import socket" statement to either "from socket import socket" and "from socket import *" but both did not help.
I also tried to use "pip install socket" but I get "could not find any downloads that satisfy the requirement socket".
Any idea how do I solve this simple issue? I thought socket is a basic module that comes with every python download.
Thanks for the answers..!
A:
sock = socket(socket.AF_INET, socket.SOCK_DGRAM)
you are using socket object directly it's wrong it's throwing an error
TypeError: 'module' object is not callable
Try this::
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
pass parameters to autocomplete using jquery
I have read this post: Passing extra parameters to source using Jquery UI autocomplete
I am develping a Web Page in Asp.net C#.
My HTML code:
<input class="tags" to_search="Birds" />
<input class="tags" to_search="Animals" />
Javascript:
$(document).ready(function() {
$(".tags").autocomplete({
source: "GenericHandler.ashx?name="+$(this).attr("to_search")
});
});
I want to pass the to_search attribute of the <input> tag to generic handler.
Above code is calling GenericHandler.ashx but gives null value of name.
How can I get name value equals to the to_search attribute of <input> tag?
Please help.
A:
Assuming that you don't add any .tags during runtime, you can do this.
$('.tags').each(function(i, tag) {
$(tag).autocomplete({
source: 'GenericHandler.ashx?name='+ $(tag).attr('to_search')
});
});
I also suggest you use data attributes in your input tags like this.
<input class="tags" data-search="Birds" />
resulting in the final solution,
$('.tags').each(function(i, tag) {
$(tag).autocomplete({
source: 'GenericHandler.ashx?name='+ $(tag).data('search')
});
});
In the event that you do add a element to your document dynamically you can do this.
// jquery object of the new element created
var element;
element.autocomplete({
source: 'GenericHandler.ashx?name='+ element.data('search')
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Provide AppStore reviewers with Facebook test accounts
Our iOS app requires users to login using their Facebook account and we need to provide the AppStore reviewers with a test account(s).
Can we take for granted that Apple have their own Facebook accounts that they use to test out apps that solely rely on Facebook for login?
Do we need to set up a Facebook "test user" via their Test User API?
Grateful for any pointers from someone who did this.
A:
Short answer: assume they have an account.
I think you're in a bit of a catch-22 here. It's probably against Facebooks terms of service to create a test account and hand those details to a third party... but, you're right, Apple may ask you for details.
However, in practice, they seem not to. One of my apps requires a login to a third-party website and I just put "you need an account" in the iTC notes section. I've been rejected once (since 2008) because I didn't specify a specific username/password. I explained why (see first paragraph) and it sailed through on the next attempt.
Having said that, apparently Facebook allows a way of creating test accounts. This is probably what you want to do if they insist.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Terminating Qt worker thread during program shutdown
I use Qt 4.8.6, MS Visual Studio 2008, Windows 7. I've created a GUI program. It contains main GUI thread and worker thread (I have not made QThread subclass, by the way), which makes synchronous calls to 3rd party DLL functions. These functions are rather slow. QTcpServer instance is also under worker thread. My worker class contains QTcpServer and DLL wrapper methods.
I know that quit() is preferred over terminate(), but I don't wanna wait for a minute (because of slow DLL functions) during program shutdown. When I try to terminate() worker thread, I notice warnings about stopping QTcpServer from another thread. What is a correct way of process shutdown?
A:
Unless there is an overriding reason to do so, you should not attempt to terminate threads with user code at process-termination.
If there is no such reason, just call your OS process termination syscall, eg. ExitProcess(0). The OS can, and will will stop all process threads in any state before releasing all process resources. User code cannot do that, and should not try to terminate threads, or signal them to self-terminate, unless absolutely necessary.
Attempting to 'clean up' with user code sounds 'nice', (aparrently), but is an expensive luxury that you will pay for with extra code, extra testing and extra maintenance.
That is, if your customers don't stop buying your app because they get pissed off with it taking so long to shut down.
The OS is very good at stopping threads and cleaning up. It's had endless thousands of hours of testing during development and decades of life in the wild where problems with process termination would have become aparrent and got fixed. You will not even get close to that with your flags, events etc. as you struggle to stop threads running on another core without the benefit of an interprocessor driver.
There are surely times when you will have to resort to user code to stop threads. If you need to stop them before process termination, or you need to close some DB connection, flush some file at shutdown, deal with interprocess comms or the like issues, then you will have to resort to some of the approaches already suggested in other answers.
If not, don't try to duplicate OS functionality in the name of 'niceness'. Just ask it to terminate your process. You can get your warm, fuzzy feeling when your app shuts down immedately while other developers are still struggling to implement 'Shutdown' progress bars or trying to explain to customers why they have 15 zombie apps still running.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
time() and how PHP parses the script
I put $START_TIME = time(); at the beginning of my code, and $END_TIME = time(); at the end of my code. then I did echo ($END_TIME - $START_TIME); and received a difference of ~ 4.
My question is, how inaccurate is this way of measuring parsing/processing time? and why?
edit: i took out the stupid part of my question :) the rest of the question still stands!
A:
time() is giving you the seconds since the "unix big bang". What you want is microtime(true) (see documentation here) which gives you the microseconds.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can i write sql code to bring values from another table and use count function?
My quesiton is :
Find the names of all classes that either meet in room R128 or have three or more students enrolled.
and my code is :
SELECT cname,count(cname) as total FROM lab5comblm258.enrolled
where cname= any ( SELECT _name FROM lab5comblm258.class
WHERE room='R128' )
group by cname
;
What Must I add to my code?
A:
You can use exists :
select cname
from lab5comblm258.enrolled e
where exists (select 1
from lab5comblm258.class c
where c._name = e.cname and c.room = 'R128'
)
group by cname
having count(*) >= 3;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
localised ring $\mathbb{Z}_{(2)}$ is an integral domain
Given the localised ring $\mathbb{Z}_{(2)}=\{\frac{a}{b}:a,b \in \mathbb{Z}, 2 \nmid b \}$, I want to show that this is an integral domain.
We choose some fraction $ \frac{a}{b}\in \mathbb{Z}_{(2)}$,where $a \in \mathbb{Z}$ and $b \in \mathbb{Z}$, such that $2 \nmid b$ and pick up another fraction $ \frac{a'}{b'}\neq 0\in \mathbb{Z}_{(2)}$ with $a' \in \mathbb{Z}$ and $b' \in \mathbb{Z}$ such that $2 \nmid b'$. We look at the term $ \frac{a}{b}*\frac{a'}{b'}=0$. Can we just conclude that $a$ and $b$ have to be zero because the only zero divisors in $\mathbb{Z}$ are the zeroes? How could I argue alternatively with the prime ideal $(2)$ ?
A:
Let $A$ be a commutative ring with unit and $S$ multiplicative subset of $A$ (contains $1$ by definition), and $S^{-1}A$ the localization. Then $\frac{a}{s} \frac{a'}{s'} = 0$ means that there is an $s'' \in S$ such that $s''(aa' \times 1 - 0 \times ss') = 0$ in $A$. (As $\frac{0}{1}$ is the localization's zero.) With $A = \mathbf{Z}$ and $S = A \backslash \mathfrak{p}$ where $\mathfrak{p} = (2)$ which is the setup you are dealing with, one sees that $a$ or $a'$ must be zero.
Remark. If $\mathbf{Z}_{(2)}=\{\frac{a}{b} \in\mathbf{Q}\;|\;a,b \in \mathbf{Z}, 2 \nmid b \}$ then $0 = \frac{a}{b} \frac{c}{d} = \frac{ac}{bd}$ implieds that $a$ or $c$ is zero, same conclusion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Displaying embedded video in WP7 browser control - Updated
I have a youtube video that is embedded in an iframe on an html page. I am trying to display this video (i.e. a representation of the video with a button that you can click to launch the default wp7 video player) using the web browser control in a WP7 app. The browser refuses to display the video with button. Note: I updated the sample code below with a different embedded video. The test code is shown below:
private void PageTitle_DoubleTap(object sender, GestureEventArgs e)
{
string _htmlView = "<html><head><style type=\"text/css\">";
_htmlView += " body { margin: 0; }";
_htmlView += "</style></head><body>";
_htmlView += "<iframe height=\"315\" src=\"http://www.youtube.com/embed/0KA4xPUJKtw?rel=0\" frameborder=\"0\" width=\"420\"></iframe>";
_htmlView += "</body></html>";
webBrowser.NavigateToString(_htmlView);
// Navigating directly to the embedded video below does work though
//webBrowser.Navigate(new Uri("http://www.youtube.com/embed/0KA4xPUJKtw?rel=0\"));
}
The XAML is
<phone:PhoneApplicationPage
x:Class="WebTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" DoubleTap="PageTitle_DoubleTap"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser x:Name="webBrowser" Margin="0,0,0,0" Width="Auto" IsScriptEnabled="True"/>
</Grid>
</Grid>
I get "The Adobe Flash Player or an HTML5 supported browser is required for video playback"
Anybody come across this issue and have some ideas on solving it?
Note: I am not able to control the content as it comes from a third party.
A:
Unfortunately the embedded browser control does not behave the same as the native browser on Windows Phone 7.
To have a placeholder image for a youtube video that the user can click on to start the video you'll need to create (or source) the image yourself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Test for significant change of means in application insights
I did a change on my webpage on a given date.
Now a want to measure if there is a significant impact on the usage due to the change. How can I do a sampled t-test in Application Insights? Splitting the time series data on a given date than comparing the two sets?
A:
In the KQL there is a built-in function for calculating Welch's t-test: welch_test().
Given a table T with a metric m and a change date d, you can calculate the test by aggregating the metric before and after the change:
T
| summarize m1 = avgif(m, Timestamp < d),
v1 = varianceif(m, Timestamp < d),
c1 = countif(Timestamp < d),
m2 = avgif(m, Timestamp > d),
v2 = varianceif(m, Timestamp > d),
c2 = countif(Timestamp > d)
| extend pValue=welch_test(m1,v1,c1,m2,v2,c2)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?
What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?
A:
There's an array called attribute_names on the model, which does include all attributes, so use reject to filter attributes:
class Model < AR::Base
def nilify_attributes!(except = nil)
except ||= %w{id created_at updated_at}
attribute_names.reject { |attr| except.include?(attr) }.each { |attr| self[attr] = nil }
end
end
See http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-attribute_names
A:
If it's a one-time thing, you could do this in the controller:
@record.update_attributes(Hash[*@record.attributes.except('created_at','updated_at','id').map { |a| [a.first, nil] }.flatten])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disabling Timer2
I am working on a Heart Rate Monitoring project, using this Sensor from sparkFun, plugged to Arduino pro mini and reading proper BPM, I have an LED connected to pin 13 of my Arduino that blinks when the pulse happen.
The code given on SparkFun page works on Timer2
I have two more LEDs connected to pin12 and pin11, which indicates battery percentage - because i am powering my Arduino using a 2 cell lithium ion battery with Voltage regulator.. I also have a voltage divider circuit at the voltage regulator with 1K resistors and connected to analog pin A0 for monitoring battery voltage.
I have assigned LED connected on pin 13 as LED1, on 12 as LED2 and 11 as LED3
LED1 for low charge
LED2 for half charge
LED3 for full charge
Here is the problem :
When i connect charger ,Arduino reads data from voltage divider and outputs levels to LEDS
Here - LED1 is conflicting between the pulse sensor (which is working on Timer2) and also for indicating the low level charging, and LED1 is flickering.
how to overcome with this issue.? disabling Timer2 helps.? if'Yes' then how to do that.?
Note : I don't want to sample Heart Rate Pulse when charger is connected!
Thank you very much.
Best
void charging() {
TCCR2A = 0;
usbState = digitalRead(usb_detect);
while (usbState == HIGH) {
usbState = digitalRead(usb_detect);
// read the input on analog pin 0:
int sensorValue = analogRead(A1);
// Convert the analog reading (which goes from 0 - 512) to a voltage (0
- 3.3V):
float voltage = sensorValue * (3.3 / 512.0);
// print out the value you read:
if (voltage >= 2.5 && voltage <= 3.3)
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(gps_led, ledState);
digitalWrite(blinkPin, LOW);
digitalWrite(save_led, LOW);
}
}
if (voltage >= 3.4 && voltage <= 3.7)
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(blinkPin, ledState);
digitalWrite(gps_led, HIGH);
digitalWrite(save_led, LOW);
}
}
if (voltage >= 3.8 && voltage <= 4.1)
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(save_led, ledState);
digitalWrite(blinkPin, HIGH);
digitalWrite(gps_led, HIGH);
}
}
Serial.println(voltage);
delay(1); // delay in between reads for stability
}
}
A:
Timer 2 is fundamental to that code. It is used to sample the heart rate sensor at a regular period. If you disable that timer you will never sample the sensor.
You cannot have two functions on one LED - it makes no sense. You should decide on one and only one function to use that LED for. If you want to use it for the battery status then remove the code from the timer interrupt that controls the LED. If you want to use it to display the hear beat then you will have to make do with just two LEDs for your battery status.
If the two operations are mutually exclusive then yes you can disable the timer. Just turn it off, then turn it on again when you want sampling to start again.
Off:
TCCR2B = 0;
On (assuming you are using this
code):
TCCR2B = 0x06;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using Grails to output data in columns
Given a variable amount of data, I want to create a table with fixed number of columns per row. For example, I may only want four columns per row:
<table>
<tr>
<th>COLUMN_1</th> <th>COLUMN_2</th> <th>COLUMN_3</th> <th>COLUMN_4</th>
</tr>
<tr>
for(-some code here-) {
<td>-some output from the loop-</td>
}
</tr>
</table>
But as you can see, if the data consisted of 10 elements, the table row will exceed my four columns.
How can I output the data so the number of columns is constant and new rows are created as needed?
A:
One of the great things about Grails (and Groovy) is its extensibility. Too often developers constrain their thinking to what their tools and frameworks currently provide. I often find it helps to think about what an ideal, more elegant solution would be if it were to be built-in to the framework. That usually gives me a good direction for how I want to implement it. In your scenario, I would prefer a GSP tag that iterates over a collection in groups of elements, so that you can process each group of elements. Something like the following:
<table>
<lm:eachGroup size="4" var="row" in="${myCollection}">
<tr>
<g:each var="cell" in="${row}">
<td>${cell}</td>
</g:each>
</tr>
</lm:eachGroup>
</table>
Of course, that doesn't exist... so I created it! It could be improved by providing a flag to pad the last group of elements so you get a complete row, but I'll leave that as an exercise for the reader. ;-)
To use my <lm:eachGroup> from my taglib in your project you can clone the git repository for my Grails plugin:
$ git clone https://github.com/erturne/leapingmindtaglib
Package the plugin:
$ grails package-plugin
Then install it into your app.
BTW, I did something similar a while back to add an eachGroup() method to List.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
writing an sql query?
I'm having 2 tables
table Items Table (this table holds all items I'm having)
itemId
---------
Item1
Item2
Item3
Item4
Item5
table 2 users_item relation
UserId || ItemId
1 || Item1
1 || Item2
userId one has stored 2 items Item1,Item2.
Now I want to write a query on table1 (Items table) so that it displays all items which user1 has NOT chosen.
A:
select itemid from Items where itemid not in
(select itemid from users_item where userid = 1)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Semantic checking doesn't work in Qt Creator 2.5
I don't get an error for this obviously erroneous code sample. Instead, qt creator mark var as unused variable. Is it possible to fix this strange behavior? I want semantic checking working.
Update:
I've been talking about on the fly semantic checking. Most IDE's analyse code as you type, and highlite errors. Qt Creator seemd to do some code analisis on the fly (because syntax highliting shows differently types, virtual functions and other things), but it doesn't hightlte errors at all.
A:
The code model used by Qt Creator is pretty good but is not based on a complete abstract syntax tree for each compilation unit. Some information about it is provided in this Qt blog post:
http://blog.qt.digia.com/2011/10/19/qt-creator-and-clang/
AFAIK, the current code model allows Qt Creator to do semantic highlighting, refactoring, displaying type hierarchies etc. but does not allow a complete on-the fly check for potential compile errors (like yours). Since the syntax of your code is correct, Qt Creator does not show an error.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML text input with mandatory quotes?
I would like to make an HTML text input field that always shows its contents quoted. I want the visitors to see the quotes but not be able to remove them. So far as I know, this can't be done with HTML, so I threw the javascript tag in there.
To reiterate, I want there to always be one pair of quotes at the beginning of the text input field, and one at the end. Inside the text field, though, of course.
edit: Also, I would want them only to be able to type between the quotes.
A:
Try the following. Its a bit weird, but it works.
Live Demo
input.onkeyup = function(){
var chars = this.value.split('');
// Removes any quotes that are in the string after the first one
for(var i=1;i< chars.length; i++){
if(chars[i] == '"'){
chars.splice(i,1);
}
}
// Adds a quote to the end
chars.push('"');
// adds a quote to the beginning
if(chars[0] != '"'){
chars.unshift('"');
}
this.value = chars.join('');
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ClassNotFoundException: when I try to get a class with Reflect
This is my files:
$ tree
.
├── Main.java
└── life
└── Person.java
Main.java
import life.Person;
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.sayHi();
}
}
And I try to compile this code:
$ javac Main.java -d .
$ java Main
hello world
Yeah, this was fine. But when I try to use reflect, so I change my Main.java to this:
import life.Person;
public class Main {
public static void main(String[] args) {
Class person = Class.forName("life.Person");
}
}
And compiler throw an error:
$ javac Main.java -d .
Main.java:6: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
Class person = Class.forName("life.Person");
I am very confused, why this code success first and failed in the next?
Why class not found?
A:
ClassNotFoundException is a checked exception, it means the statement might throw ClassNotFoundException at run time and you need determine how to handle it at compile stage.
You can throws it to the caller in main method:
public static void main(String[] args) throws ClassNotFoundException
or use a try catch block:
try {
Class person = Class.forName("life.Person");
} catch(ClassNotFoundException e) {
// handle it
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Service started and then stopped?
procedure TService1.ServiceExecute(Sender: TService);
var
FileName : string;
Strm : TMemoryStream;
i : integer;
h,m,s,ms : word;
begin
DecodeTime( now, h, m, s, ms );
if ( h = 13 ) AND ( m = 6 ) AND ( s = 0 ) then
begin
ShowMessage( 'entered' );
for i := 0 to 3 do
begin
DateTimeToString( FileName, 'yyyy-mm-dd-hh-nn-ss', now );
FileName := ExtractFilePath( Application.ExeName ) + FileName + '.jpg';
if not FileExists( FileName ) then
begin
try
Strm := TMemoryStream.Create;
try
IdHTTP_ := TIdHTTP.Create( nil );
try
IdHTTP_.Get( 'http://192.168.1.223/snapshot/view0.jpg', Strm );
finally
IdHTTP_.Free;
end;
Strm.Position := 0;
Strm.SaveToFile( FileName );
finally
Strm.Free;
end;
except
end;
end;
Sleep( 5000 );
end;
end;
end;
this is my code for a service which is supposed to took 4 snapshots from an IP Camera in specific time.
Anyway as soon as I start the service, i am receiving the message "The Service1 service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.", and the service is terminated.
What is the issue in this source ?
A:
The documentation for OnExecute says:
Occurs when the thread associated with the service starts up.
If you are not spawning a new thread to handle individual
service requests in an OnStart event handler, this is where you implement the service. When the OnExecute event handler finishes, the service thread terminates. Most OnExecute event handlers contain a loop that calls the service thread's ProcessRequests method so that other service requests are not locked out.
Your OnExecute does not loop. Once that function exits, the service stops. You will need to do what the documentation describes. Either loop, or spawn a thread to handle service requests.
Do be aware that you cannot show UI in a service. So your attempts to call ShowMessage cannot work. You'll need to use a logging mechanism appropriate for services. For example one that writes to a file.
What you are trying to do would be much easier in a normal desktop process which was scheduled as a scheduled task. I think a service is the wrong solution to your problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why am I Getting: Transaction Error. Exception thrown in contract code in Rinkeby?
I'm creating a token that generates new tokens every time ETH is sent to it. It takes those newly generated tokens and sends them to the wallet address that sent the ETH. The maxTokens is 40mil. The RATE is 20mil (trying to keep things simple for my test). It's pretty straightforward.
The issue I'm encountering with my test contract is that trying to send 1 ETH is fine and the transaction goes through. Trying to send a greater amount, like say 1.5, produces this warning: "Transaction Error. Exception thrown in contract code.
Gas limit set dangerously high. Approving this transaction is likely to fail."
After playing around for a while I realized that I could send smaller amounts of ETH that would go through after sending the 1ETH. However, the closer I got to the max tokens I would get the above mentioned error.
Can anyone explain why I am getting this error? I can't understand why an error is producing when someone sends an amount of ETH that is relatively close to the maxTokens.
Edit: I have successfully been able to buy up to 39,999,700 of the tokens. However, I have to keep buying smaller amounts each time or else I get the above mentioned errors.
pragma solidity ^0.4.11;
import './IERC20.sol';
import './SafeMath.sol';
contract ChekOutToken is IERC20 {
using SafeMath for uint256;
uint public _totalSupply = 0;
string public constant symbol = "CHEKS";
string public constant name = "ChekOut Token";
uint8 public constant decimals = 18;
// 1 ETH = 1000 CHEKS
uint256 public constant RATE = 20000000;
// Sets Maximum Tokens to be Created
uint256 public constant maxTokens = 40000000000000000000000000;
address public owner;
mapping (address => uint256) public balances;
mapping(address => mapping(address => uint256)) allowed;
function () payable{
createTokens();
}
function ChekOutToken(){
owner = msg.sender;
}
function createTokens() payable{
require(msg.value > 0);
require(_totalSupply.add(tokens) <= maxTokens);
uint256 tokens = msg.value.mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
require(_totalSupply.add(tokens) <= maxTokens);
}
function totalSupply() public constant returns (uint256 totalSupply) {
return _totalSupply;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value && _value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
balances[_from] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
A:
I see two issues, and I think the second is the source of your error:
function createTokens() payable{
require(msg.value > 0);
require(_totalSupply.add(tokens) <= maxTokens);
uint256 tokens = msg.value.mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
require(_totalSupply.add(tokens) <= maxTokens);
}
The line require(_totalSupply.add(tokens) <= maxTokens); occurs twice. Each time is problematic:
The first time, tokens has not yet been assigned a value. (I was surprised this even compiled, but apparently variable declarations are hoisted?) So this checks adding 0, which doesn't do what you want.
The second time, you've already added tokens to _totalSupply so you're effectively checking "Can I add tokens twice and still stay under maxTokens?"
I would fix the function by moving the earlier require to after the computation of tokens and getting rid of the require at the end:
function createTokens() payable{
require(msg.value > 0);
uint256 tokens = msg.value.mul(RATE);
require(_totalSupply.add(tokens) <= maxTokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
debian recover fail from postinst script
I'm a little stuck in a postinst file for Ubuntu.
The problem is when upgrading the package. I have some sqlite databases (marked as config files to save them from upgrades) in which I want to modify in a specific version (add some columns). As only I want to modify the database when installing an specific version (for example from version 3 or older to 4) I check if $2 is not null.
The approach to make the database upgrading is as follows:
first I make a backup of the databases
make new table
Then I alter the tables
copy the rows from the old table to the new one
The problem is if something goes wrong, the database already will be modified but the package will be at the new version (the four) with config version at 3. If I want to try install again the package in order to get the package ok, the postinst will fail because the database was already modified.
One thing that came to my mind was unset -e, but I find this very unpleasant.
I've searched in the documentation about how to revert fails from postinst, such as if it's called another script with different arguments, but in the documentation Debian says nothing useful.
Maybe the postinst script is not the best place to modify databases?
Thanks
Best regards
A:
One thing you could do is check if the field already exists on the table, and alter in that case.
That is not dependent on if this is an upgrade or not.
Like this for example:
if sqlite3 /collection.db '.schema media' | grep -q 'new_field text' ; then
echo field already exists, continuing
else
sqlite3 /collection.db 'alter table media add column new_field text'
fi
Also, I would recommend the database schema to be manipulated by the application, and not dpkg.
Imagine that the user might restore a backup from an older version and "break" your software.
It should be clear to the user that the database of older versions is incompatible with the newer version.
I would recommend you to search the internet for help in creating a "migration plan".
Basically that means that you keep track of what "version" the database is and apply sequentially the database modifications when needed, in a way that is very similar to how a patch works.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Split, for-loop with replace to lambda expression
I have a string q.ACBValue which has instances like "v1,v2,v4" or "v3,v5". I want to convert the following code to a neater lambda expression
string[] list = q.ACBValue.Split(',');
for (int i = 0; i < list.Count(); i++)
{
q.ACBOption = q.ACBOption.Replace("value='"+ list[i] + "' ", "value='" + list[i] + "' checked=\"checked\"");
}
A:
Try something like this:
q.ACBValue.Split(',')
.Select(s => new
{
Search = "value='" + s + "' ",
Replace = "value='" + s + "' checked=\"checked\""
})
.ToList()
ForEach(tuple =>
qACBOption = q.ACBOption.Replace(tuple.Search, tuple.Replace));
This solution uses ForEach method of the List<T> class. To make it visible, you have to convert previous sequence to list by explicitly calling extension method ToList.
There is another approach, in which you are aggregating the results along the way using the Aggregate extension method:
q.ACBOption =
q.ACBValue.Split(',')
.Select(s => new
{
Search = "value='" + s + "' ",
Replace = "value='" + s + "' checked=\"checked\""
})
.Aggregate(
q.ACBOption,
(res, tuple) => res.Replace(tuple.Search, tuple.Replace));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My internet is so slow Steam gives up downloading my stuff. What can I do?
Well, I'm in a difficult situation at the moment. I'm temporarily apart from my usual internet connection, and forced to use a really shitty solution. It's slow in ways I can't even explain: sometimes Chrome gives up at loading simple pages due to timeout errors.
Going straight to the point: I've bought some titles in the current sale, and want to play some of them the sooner possible. The problem is I can't download any of them. In fact this happens with every program that implements its own downloading system - they just go corrupt or cancel in the midlle of the process.
Software specialized in downloading stuff usually do just fine for me, but Steam just won't. Is there any workaround? Perhaps some different configuration or external tool. I can login (after some insistence) just ok, but not download any game/update.
A:
If you know someone close by that has the game(s) in question, they can make a backup up of the game(s) and you can restore it to your Steam library, as Steam will just check that you own the game(s) and do the rest for you. This has always worked for me and my friends in DOTA2, where 1 person downloads the update, backs up the game an we all just restore it from the back up.
A:
If you have access to another computer at a location with a properly working network, then you can:
Log onto that computer
install steam
Download the game you want (to that other computer), using the steam client.
Then download the relevant files from the other location to yours using a protocol which works even in very poor connections (e.g. sFTP with resume, scp, http (move the downloaded file to a webserver), ... )
This will work if the download speed is a problem in combination with the steam client.
It will not work (or work poorly) if the problem is not the download speed, but some other reason which messes up your network (e.g. lost packets). Which is likely given that other programs such as Chrome also run into problems. In that case the proper solution would be to fix your network, which starts with identifying what goes wrong.
You did not add any OS to your question, but start with this:
SteamOS/Linux: ifconfig
eth0 Link encap:Ethernet HWaddr 01:27:B0:14:DA:FE
UP BROADCAST RUNNING SLAVE MULTICAST MTU:1500 Metric:1
RX packets:2746252626 errors:0 dropped:1151734 overruns:0 frame:0
TX packets:4109502155 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:427998700000 (408171.3 Mb) TX bytes:3530782240047 (3367216.3 Mb)
Interrupt:40 Memory:d8000000-d8012700
OS X: ifconfig (probably with EN0 rather than ETH0)
Windows 7: [start] [run] cmd netstat -s
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does OS X Have An Inbuilt "Self Cleaning" Feature?
Does OS X have an inbuilt effective "self cleaning" feature/mechanism. If so does it need to be turned on by default, and how often does it take place, (or is this something that is determined by the user).
Is it advisable to use apps such as CleanMyMac or CCleaner for example ? (or are they more harmful than good).
A:
Applications such as CleanMyMac or CCleaner are unnecessary for your Mac. They can clear certain caches or preferences that can interfere with the proper functionality of your other applications - they'll be recreated anyway the next time you use the software. Unless you're in dire need of extra space on your hard drive, I wouldn't suggest trying to erase caches using cleaner applications. If anything, invest in an external hard drive and move some of your larger files over.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fabric Composer Quickstart error
I'm having problems with 'npm install' step in the the Fabric Composer Quickstart guide -- https://fabric-composer.github.io/installing/quickstart.html
My system levels are:
Ubuntu 16.04 LTS
Docker version 1.12.6, build 78d1802
docker-compose version 1.12.0-rc2, build 08dc2a4
node v6.9.4
git 2.7.4
I installed the command line tools:
npm install -g composer-cli
Cloned the sample apps repository:
git clone https://github.com/fabric-composer/sample-applications.git
cd'ed to the sample apps dir:
cd sample-applications/packages/getting-started
ran 'npm install' where I got the following error in the Deploying business network from archive digitalPropertyNetwork.bna step:
...
Found:
Description:Digital Property Network
Name:digitalproperty-network
Identifier:[email protected]
Written Business Network Definition Archive file to digitalPropertyNetwork.bna
Command completed successfully.
Deploying business network from archive digitalPropertyNetwork.bna
Business network definition:
Identifier: [email protected]
Description: Digital Property Network
events.js:160
throw er; // Unhandled 'error' event
^
Error
at ClientDuplexStream._emitStatusIfDone (/home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/grpc/src/node/src/client.js:189:19)
at ClientDuplexStream._readsDone (/home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/grpc/src/node/src/client.js:158:8)
at readCallback (/home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/grpc/src/node/src/client.js:217:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] deployNetwork: composer archive create --sourceName digitalproperty-network --sourceType module --archiveFile digitalPropertyNetwork.bna && composer network deploy --archiveFile digitalPropertyNetwork.bna --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d && composer network list -n digitalproperty-network --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] deployNetwork script 'composer archive create --sourceName digitalproperty-network --sourceType module --archiveFile digitalPropertyNetwork.bna && composer network deploy --archiveFile digitalPropertyNetwork.bna --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d && composer network list -n digitalproperty-network --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the getting-started package,
npm ERR! not with npm itself.
...
Any ideas?
none of the ports which appear to be used by the fabric containers (7050-7054) are in use prior to running nps install according to netstat -a.
I'm attaching the full output from 'npm install' along with the 'docker ps' command result after it runs:
bill@bill-ubuntu:~/blockchain-fabric-composer/sample-applications/packages/getting-started$ npm install
> [email protected] preinstall /home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started
> composer --version || echo 'Please first run npm install -g composer-cli'
composer-cli v0.5.6
composer-admin v0.5.6
composer-client v0.5.6
composer-common v0.5.6
composer-runtime-hlf v0.5.6
composer-connector-hlf v0.5.6
> [email protected] install /home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started
> scripts/download-hyperledger.sh && scripts/start-hyperledger.sh && npm run deployNetwork
# Grab the current directory.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd
dirname "${BASH_SOURCE[0]}"
# Shut down the Docker containers that might be currently running.
cd "${DIR}"/scripts
docker-compose kill && docker-compose down
Removing scripts_vp0_1 ... done
Removing scripts_membersrvc_1 ... done
# TODO change this to alter the default profile which is, by convention, a local running hyperledger fabric
rm -rf ~/.composer-connection-profiles/defaultProfile/*
rm -rf ~/.composer-credentials/*
# delete all existing containers and images
# This is not used in general usage but this might
#read -p "Press y to delete all docker containers images" -n 1 -r
#echo # (optional) move to a new line
#if [[ $REPLY =~ ^[Yy]$ ]]
#then
# docker rm $(docker ps -a -q) -f
# docker rmi $(docker images -q) -f
#fi
# Pull and tag the latest Hyperledger Fabric base image.
docker pull hyperledger/fabric-baseimage:x86_64-0.1.0
x86_64-0.1.0: Pulling from hyperledger/fabric-baseimage
Digest: sha256:ac6a2784cfd028ae62f5688f4436f95d7a60eeacd8506eb303c9c6335328c388
Status: Image is up to date for hyperledger/fabric-baseimage:x86_64-0.1.0
docker tag hyperledger/fabric-baseimage:x86_64-0.1.0 hyperledger/fabric-baseimage:latest
# Grab the current directorydirectory.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd
dirname "${BASH_SOURCE[0]}"
#
cd "${DIR}"/scripts
# Start up the Hyperledger Fabric
docker-compose up -d --build
Creating scripts_membersrvc_1
Creating scripts_vp0_1
# Wait for the Hyperledger Fabric to start.
while ! nc localhost 7051 </dev/null; do sleep 1; done
while ! nc localhost 7053 </dev/null; do sleep 1; done
while ! nc localhost 7054 </dev/null; do sleep 1; done
sleep 5
> [email protected] deployNetwork /home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started
> composer archive create --sourceName digitalproperty-network --sourceType module --archiveFile digitalPropertyNetwork.bna && composer network deploy --archiveFile digitalPropertyNetwork.bna --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d && composer network list -n digitalproperty-network --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d
Creating Business Network Archive
Node module search path :
undefined
Looking for package.json of Business Network Definition in /home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/digitalproperty-network
Found:
Description:Digital Property Network
Name:digitalproperty-network
Identifier:[email protected]
Written Business Network Definition Archive file to digitalPropertyNetwork.bna
Command completed successfully.
Deploying business network from archive digitalPropertyNetwork.bna
Business network definition:
Identifier: [email protected]
Description: Digital Property Network
events.js:160
throw er; // Unhandled 'error' event
^
Error
at ClientDuplexStream._emitStatusIfDone (/home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/grpc/src/node/src/client.js:189:19)
at ClientDuplexStream._readsDone (/home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/grpc/src/node/src/client.js:158:8)
at readCallback (/home/bill/blockchain-fabric-composer/sample-applications/packages/getting-started/node_modules/grpc/src/node/src/client.js:217:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] deployNetwork: `composer archive create --sourceName digitalproperty-network --sourceType module --archiveFile digitalPropertyNetwork.bna && composer network deploy --archiveFile digitalPropertyNetwork.bna --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d && composer network list -n digitalproperty-network --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] deployNetwork script 'composer archive create --sourceName digitalproperty-network --sourceType module --archiveFile digitalPropertyNetwork.bna && composer network deploy --archiveFile digitalPropertyNetwork.bna --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d && composer network list -n digitalproperty-network --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the getting-started package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! composer archive create --sourceName digitalproperty-network --sourceType module --archiveFile digitalPropertyNetwork.bna && composer network deploy --archiveFile digitalPropertyNetwork.bna --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d && composer network list -n digitalproperty-network --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs getting-started
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls getting-started
npm ERR! There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/bill/.npm/_logs/2017-04-08T23_44_23_838Z-debug.log
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `scripts/download-hyperledger.sh && scripts/start-hyperledger.sh && npm run deployNetwork`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'scripts/download-hyperledger.sh && scripts/start-hyperledger.sh && npm run deployNetwork'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the getting-started package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! scripts/download-hyperledger.sh && scripts/start-hyperledger.sh && npm run deployNetwork
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs getting-started
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls getting-started
npm ERR! There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/bill/.npm/_logs/2017-04-08T23_44_23_862Z-debug.log
bill@bill-ubuntu:~/blockchain-fabric-composer/sample-applications/packages/getting-started$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
24bb54c9fec3 hyperledger/fabric-membersrvc "membersrvc" 14 seconds ago Up 13 seconds 0.0.0.0:7054->7054/tcp scripts_membersrvc_1
bill@bill-ubuntu:~/blockchain-fabric-composer/sample-applications/packages/getting-started$
including output from docker ps -s after running teardown.sh, download-hyperledger.sh, and start-hyperledger.sh:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
fdccb0a2ce8c hyperledger/fabric-peer "sh -c 'sleep 5; peer" 18 minutes ago Exited (1) 18 minutes ago scripts_vp0_1
a9d625859d2b hyperledger/fabric-membersrvc "membersrvc" 18 minutes ago Up 18 minutes 0.0.0.0:7054->7054/tcp scripts_membersrvc_1
and here is the output from docker logs for the failed peer container:
bill@bill-ubuntu:~/blockchain-fabric-composer/sample-applications/packages/getting-started/scripts$ docker logs fdccb0a2ce8c
21:43:33.321 [logging] LoggingInit -> DEBU 001 Setting default logging level to DEBUG for command 'node'
21:43:33.322 [peer] func1 -> INFO 002 Auto detected peer address: 172.18.0.3:7051
21:43:33.322 [peer] func1 -> INFO 003 Auto detected peer address: 172.18.0.3:7051
21:43:33.324 [eventhub_producer] AddEventType -> DEBU 004 registering BLOCK
21:43:33.325 [eventhub_producer] AddEventType -> DEBU 005 registering CHAINCODE
21:43:33.325 [eventhub_producer] AddEventType -> DEBU 006 registering REJECTION
21:43:33.325 [eventhub_producer] AddEventType -> DEBU 007 registering REGISTER
21:43:33.325 [nodeCmd] serve -> INFO 008 Security enabled status: true
21:43:33.325 [nodeCmd] serve -> INFO 009 Privacy enabled status: false
21:43:33.325 [eventhub_producer] start -> INFO 00a event processor started
21:43:33.325 [db] open -> DEBU 00b Is db path [/var/hyperledger/production/db] empty [true]
21:43:33.326 [db] open -> INFO 00c Setting rocksdb maxLogFileSize to 10485760
21:43:33.326 [db] open -> INFO 00d Setting rocksdb keepLogFileNum to 10
21:43:34.513 [nodeCmd] func1 -> DEBU 00e Registering validator with enroll ID: test_vp0
21:43:34.513 [crypto] RegisterValidator -> INFO 00f Registering validator [test_vp0] with name [test_vp0]...
21:43:34.517 [crypto] Debugf -> DEBU 010 [validator.test_vp0] Data will be stored at [/var/hyperledger/production/crypto/validator/test_vp0]
21:43:34.517 [crypto] Debugf -> DEBU 011 [validator.test_vp0] Keystore path [/var/hyperledger/production/crypto/validator/test_vp0/ks] missing [true]: [<clean>]
21:43:34.518 [crypto] Debugf -> DEBU 012 [validator.test_vp0] Creating Keystore at [/var/hyperledger/production/crypto/validator/test_vp0/ks]...
21:43:34.518 [crypto] Debug -> DEBU 013 [validator.test_vp0] Open Keystore DB...
21:43:34.518 [crypto] Debug -> DEBU 014 [validator.test_vp0] Ping Keystore DB...
21:43:34.519 [crypto] Debugf -> DEBU 015 [validator.test_vp0] Keystore created at [/var/hyperledger/production/crypto/validator/test_vp0/ks].
21:43:34.520 [crypto] Debugf -> DEBU 016 [validator.test_vp0] Keystore opened at [/var/hyperledger/production/crypto/validator/test_vp0/ks]...done
21:43:34.520 [crypto] Debug -> DEBU 017 [validator.test_vp0] Registering node crypto engine...
21:43:34.520 [crypto] Debug -> DEBU 018 [validator.test_vp0] Initiliazing TLS...
21:43:34.520 [crypto] Debug -> DEBU 019 [validator.test_vp0] Initiliazing TLS...Disabled!!!
21:43:34.521 [crypto] Debug -> DEBU 01a [validator.test_vp0] Getting ECA client...
21:43:34.521 [crypto] Debugf -> DEBU 01b [validator.test_vp0] Dial to addr:[membersrvc:7054], with serverName:[tlsca]...
21:43:34.521 [crypto] Debug -> DEBU 01c [validator.test_vp0] TLS disabled...
21:43:34.521 [crypto] Debug -> DEBU 01d [validator.test_vp0] Getting ECA client...done
21:43:34.522 [crypto] Errorf -> ERRO 01e [validator.test_vp0] Failed requesting read certificate [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
21:43:34.522 [crypto] Errorf -> ERRO 01f [validator.test_vp0] Failed requesting ECA certificate [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
21:43:34.523 [crypto] Errorf -> ERRO 020 [validator.test_vp0] Failed getting ECA certificate [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
21:43:34.523 [crypto] Errorf -> ERRO 021 [validator.test_vp0] Failed retrieving ECA certs chain [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
21:43:34.523 [crypto] Errorf -> ERRO 022 [validator.test_vp0] Failed registering node crypto engine [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
21:43:34.523 [crypto] Errorf -> ERRO 023 [validator.test_vp0] Failed registering peer [test_vp0]: [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure]
2017/04/09 21:43:34 grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp 172.18.0.2:7054: getsockopt: connection refused"; Reconnecting to {"membersrvc:7054" <nil>}
2017/04/09 21:43:34 Failed to dial membersrvc:7054: grpc: the connection is closing; please retry.
21:43:34.523 [crypto] Errorf -> ERRO 024 [validator.test_vp0] Failed registering [test_vp0]: [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure]
21:43:34.523 [crypto] RegisterValidator -> ERRO 025 Failed registering validator [test_vp0] with name [test_vp0] [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
Error: rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure
Usage:
peer node start [flags]
Flags:
-h, --help help for start
--peer-chaincodedev Whether peer in chaincode development mode
Global Flags:
--logging-level string Default logging level and overrides, see core.yaml for full syntax
--test.coverprofile string Done (default "coverage.cov")
-v, --version Display current version of fabric peer server
bill@bill-ubuntu:~/blockchain-fabric-composer/sample-applications/packages/getting-started/scripts$
A:
first time answering, so forgive my bad style I guess.
Anyway I had the same issue and in my case it was a matter of a slow computer. In other words the membersrvc was not up when the peer vp0 was trying to connect.
I fixed it by changing the start-hyperledger.sh script to sleep an extra 60 seconds just to be sure:
`# Wait for the Hyperledger Fabric to start.
while ! nc localhost 7051 </dev/null; do sleep 1; done
while ! nc localhost 7053 </dev/null; do sleep 1; done
while ! nc localhost 7054 </dev/null; do sleep 1; done
sleep 65
`
And also added some extra time before building the peer container in the composer file, docker-compose.yml:
`vp0:
image: hyperledger/fabric-peer
ports:
- '7050:7050'
- '7051:7051'
- '7052:7052'
- '7053:7053'
environment:
- CORE_PEER_ADDRESSAUTODETECT=true
- CORE_VM_ENDPOINT=unix:///var/run/docker.sock
- CORE_LOGGING_LEVEL=DEBUG
- CORE_PEER_ID=vp0
- CORE_PEER_PKI_ECA_PADDR=membersrvc:7054
- CORE_PEER_PKI_TCA_PADDR=membersrvc:7054
- CORE_PEER_PKI_TLSCA_PADDR=membersrvc:7054
- CORE_SECURITY_ENABLED=true
- CORE_SECURITY_ENROLLID=test_vp0
- CORE_SECURITY_ENROLLSECRET=MwYpmSRjupbT
links:
- membersrvc
command: sh -c 'sleep 25; peer node start'
volumes:
- /var/run/docker.sock:/var/run/docker.sock`
Those two changes fixed it for me. So hope it helps
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Writing dynamic SQL safely, with an example function that estimates rows in any view
Last week I wrote myself a client side pivot table generator. Included on the screen is a list of tables and views. Along the way, I found it helpful to have an estimate of the number of rows in a selected table or view. It turns out to be easy to get an estimate of a table count, but I didn't know how to get an estimate of the rows in a view. Today, I was reading
COUNT(*) MADE FAST
Laurenz Albe's blog post ends with this tidy piece of clever:
CREATE FUNCTION row_estimator(query text) RETURNS bigint
LANGUAGE plpgsql AS
$$DECLARE
plan jsonb;
BEGIN
EXECUTE 'EXPLAIN (FORMAT JSON) ' || query INTO plan;
RETURN (plan->0->'Plan'->>'Plan Rows')::bigint;
END;$$;
That. Is. Nice. I realized that this would work as a view estimator, so I wrote up (read "hacked together") a function:
DROP FUNCTION IF EXISTS api.view_count_estimate (text, text);
CREATE OR REPLACE FUNCTION api.view_count_estimate (
schema_name text,
view_name text)
RETURNS BIGINT
AS $$
DECLARE
plan jsonb;
query text;
BEGIN
EXECUTE
'select definition
from pg_views
where schemaname = $1 and
viewname = $2'
USING schema_name,view_name
INTO query;
EXECUTE
'EXPLAIN (FORMAT JSON) ' || query
INTO plan;
RETURN (plan->0->'Plan'->>'Plan Rows')::bigint;
END;
$$ LANGUAGE plpgsql;
ALTER FUNCTION api.view_count_estimate(text, text) OWNER TO user_change_structure;
This brings me to one of the areas I'm a bit nervous about in Postgres: Creating dynamic SQL safely. I'm not really clear about the magic regclass castings, or if I should be using something like quote_ident() above. Is the built SQL with the USING list safe? I don't see how it could be.
I'm using Postgres 11.4.x.
A:
As Laurenz said, your current code is perfectly safe, but given the amount of paranoia around SQL injection nowadays, it's worth elaborating.
Consider the naive version of your function:
CREATE FUNCTION api.view_count_estimate(schema_name text, view_name text) RETURNS BIGINT
AS $$
DECLARE result BIGINT;
BEGIN
EXECUTE 'SELECT COUNT(*) FROM ' || schema_name || '.' || view_name INTO result;
RETURN result;
END
$$ LANGUAGE plpgsql;
This is obviously wide open to SQL injection, but can be easily secured in a couple of ways. The most straightforward is to use quote_ident():
EXECUTE 'SELECT COUNT(*) FROM ' || quote_ident(schema_name) || '.' || quote_ident(view_name)
INTO result;
This guarantees that the concatenated strings are syntactically valid identifiers, by double-quoting them if they contain any symbols, whitespace, or uppercase characters, so there is no risk of the user input being interpreted as an unwanted SQL expression or keyword (though it has the potential downside of making your function inputs case-sensitive).
A much more succinct alternative to quote_ident() is to use the equivalent %I format specifier:
EXECUTE format('SELECT COUNT(*) FROM %I.%I', schema_name, view_name) INTO result;
There is also a %L specifier for embedding string literals, equivalent to the quote_literal() function.
An even nicer approach is to pass view references via a regclass parameter:
CREATE FUNCTION api.view_count_estimate(view_id regclass) RETURNS BIGINT
AS $$
DECLARE result BIGINT;
BEGIN
EXECUTE 'SELECT COUNT(*) FROM ' || view_id::text INTO result;
RETURN result;
END
$$ LANGUAGE plpgsql;
The "magic" behind the regclass type is actually pretty straightforward; the value itself is just the integer primary key of the pg_class table, and it behaves like an integer in most respects, but the casts to and from string values will query pg_class to find the name of the table, following the same quoting rules as quote_ident() and respecting the current schema search path.
In other words, you can call the function with
SELECT view_count_estimate('my_view')
or
SELECT view_count_estimate('"public"."my_view"')
or
SELECT view_count_estimate('public.My_View')
...and the regclass conversion will resolve the identifier just as it would in a query (while the text cast within the function will quote/qualify the identifier as needed).
But all of this is only necessary if you need to substitute an identifier into your query. If you just need to substitute values into a query (as is the case in your function) then a parameterised query (e.g. EXECUTE ... USING) is completely safe. Query parameterisation is not simple string substitution; it maintains a clear separation between code and data (in fact, the entire SQL statement is parsed, and all identifiers resolved, before the parameter values are even considered), so there is no possibility of SQL injection.
In fact, since all of the variables in this case are simple parameters, you don't need a dynamic query at all; your function can just run the query directly, without the EXECUTE:
SELECT definition
FROM pg_views
WHERE schemaname = schema_name
AND viewname = view_name
INTO query;
Under the hood, PL/pgSQL will build exactly the same parameterised query (i.e. ...WHERE schemaname = $1 AND viewname = $2) and bind the parameters to your function inputs. This approach has the added benefit of only preparing the query the first time you call the function within a session, and just re-binding the parameter values on subsequent calls.
Actually, in this case you don't really need the query at all. The pg_get_viewdef() function will return the view definition for a given regclass, so the whole thing can be reduced to:
CREATE FUNCTION api.view_count_estimate(view_id regclass) RETURNS bigint
AS $$
DECLARE
plan jsonb;
BEGIN
EXECUTE 'EXPLAIN (FORMAT JSON) ' || pg_get_viewdef(view_id) INTO plan;
RETURN (plan->0->'Plan'->>'Plan Rows')::bigint;
END;
$$ LANGUAGE plpgsql;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java WS only responds with tcp/ip monitor turned on
created a very basic WS. i have LoggingHandler, Test, TestImpl, & TestPublisher. my publisher creates my endpoint below:
import javax.xml.ws.Endpoint;
public class TestPublisher {
public static void main(String[] args) {
LoggingHandler handle = new LoggingHandler();
Endpoint ep = Endpoint.publish( "http://localhost:8060/message/hello",
new TestImpl() );
ep.getBindings().getHandlerChain().add( new LoggingHandler() );
System.out.print( handle.toString() );
}
}
my Test interface uses @WebService & @WebMethod and only does "String getHello( String str );"
my TestImpl implements Test and uses @WebService(endpointInterface="my package location") and only has a method "public String getHelloWorld( String str ){ return "Hello " + str; }
my handler has handleMessage, handleFault, & close. i can put this code up too but i don't think that would help.
when i head over to localhost:port/message/hello on the same (dev) RH6 pc, it works great! i get "Hello my name". i even can get a wsdl file at localhost:port/message/hello?wsdl
when i try accessing from any other pc, linux or windows, i get a timeout or "cannot display the webpage" error. so i setup in tcp/ip monitor in eclipse to monitor and route traffic from port 8061 (new port) to my WS port [here][link3] without changing any code.
results: i still can't access 8060 from any other pc except the one running the service (dev). so i point my browser to on the other pc's to port 8061 (tcp/ip monitor) and it successfully returns my message! do i need to run a monitor to forward to my java webservice?
on my RH6 box, i am not running a firewall or a web server & i am on my work network. i can successfully start tomcat6 and get to 8080 from the other pc's without using tcp/ip monitor.
A:
Try Endpoint.publish with the ip address of your machine,
ex: Endpoint.publish("http://192.168.0.1:8060/message/hello")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
some uid's in /proc/pid/loginuid are strange
i'm analysing the procfs in unix/linux and some loginuid of processes are really strange. Some pid's have as loginuid a big number: 4294967295. Are they daemons or system events or whats the matter?
# cat /proc/11071/loginuid
4294967295
A:
4294967295 is just (unsigned long) -1. -1 means that loginuid was not set. This is normal behavior for processes that were not spawned by any login process (e.g. for daemons).
loginuid is -1 by default; pam_loginuid module changes it to your user id whenever you login (in a tty/in DM/via ssh), and this value is preserved by child processes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Trouble with aggregate in Where clause, Selecting Max(x) When Max(x) != 3
I am trying to reconfigure the below sql to only pull records when the Max(Field) != 3 but keep getting an error (detailed) below.
This is the code before adding the Where Max(field) != 3
SELECT P.Code,
MAX(PW.v1) AS V1
FROM SW
INNER JOIN S ON SW.S_Id = S.Id
INNER JOIN PW ON SW.PW_Id = PW.Id
INNER JOIN PON S.P_Id = P.id
WHERE S.P_Id = P.id
GROUP BY P.Code
My Attempt
SELECT P.Code,
MAX(PW.v1) AS V1
FROM SW
INNER JOIN S ON SW.S_Id = S.Id
INNER JOIN PW ON SW.PW_Id = PW.Id
INNER JOIN PON S.P_Id = P.id
WHERE S.P_Id = P.id
AND (SELECT MAX(PW.v1)
FROM SW AS SW2
WHERE SW.PWId = SW2.PW_Id) != 3
GROUP BY P.Code
This is the error I get and not sure what to do:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
A:
Traditional method of filtering on results of an aggregate can be achieved by using HAVING clause. I also removed the unnecessary WHERE clause as you already joined those 2 tables on that column. Here is the query:
SELECT P.Code
,MAX(PW.v1) AS V1
FROM SW
INNER JOIN S
ON SW.S_Id = S.Id
INNER JOIN PW
ON SW.PW_Id = PW.Id
INNER JOIN P
ON S.P_Id = P.id
GROUP BY P.Code
HAVING MAX(PW.v1)!=3;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Lock issues on large recordset
I have a database table that I use as a queue system, where separate process that talk to each other create and read entries in the table. For example, when a user initiates a search an entry is created, then another process that runs every second or two will pick up that new entry, update the status and then do a search, updating the entry again when the search is complete. This all seems to work well with thousands of searches per hour.
However, I have a master admin screen that lets me view the status of all of these 'jobs' but it runs very slowly. I basically return all entries in the table for the last hour so I can keep an eye on what's going on. I think that I am running into lock issues of some sort. I only need to read each entry, and don't really care if it the data is a little bit out of date. I just use a standard 'Select * from Table' statement so maybe it is waiting for other locks to expire before returning data as the jobs are constantly updating the data.
Would this be handled better by a certain kind of cursor to return each row one at a time, etc? Any other ideas?
Thanks
A:
If you really don't care if the data is a bit out of date... or if you only need the data to be 99.99% accurate, consider using WITH (NOLOCK):
SELECT * FROM Table WITH (NOLOCK);
This will instruct your query to use the READ UNCOMMITTED ISOLATION LEVEL, which has the following behavior:
Specifies that dirty reads are allowed. No shared locks are issued to
prevent other transactions from modifying data read by the current
transaction, and exclusive locks set by other transactions do not
block the current transaction from reading the locked data.
Be aware that NOLOCK may cause some inaccuracies in your data, so it probably isn't a good idea to use it throughout the rest of your system.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error get name value copy from textarea
<script>
$(document).ready(function(){
$('.next').click(function(){
$('input#productname').val($('input#_productname').val());
$('textarea#description').val($('textarea#_description').val());
});
});
</script>
<input type="text" name="_productname" id="_productname" value="demo"/>
<textarea name="_description" id="_description" value="demo" ></textarea>
<input type="text" name="productname" id="productname" />
<textarea name="description" id="description" ></textarea>
<input id="next" class="next" type="submit" name="next" value="next" />
output:
productname = demo
description =
Help me get value this tag texterea
A:
Textareas do not have a value attribute documentation (so do not use one). You have to put the value between the opening and closing tag <textarea> value here </textarea>
and also id's cannot start with _ documentaion so change that too, and it should work.
html
<input type="text" name="productname_" id="productname_" value="demo"/>
<textarea name="description_" id="description_">demo</textarea>
<input type="text" name="productname" id="productname" />
<textarea name="description" id="description" ></textarea>
javascript
$(document).ready(function(){
$('.next').click(function(){
$('input#productname').val($('input#productname_').val());
$('textarea#description').val($('textarea#description_').val());
});
});
demo at http://jsfiddle.net/gaby/Fmxyd/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Storage Bench Possible with 3/4" Plywood/MDF?
Is it possible to make the storage bench below using only wood glue, screws, and 3/4-inch plywood or MDF?
The only requirement is that it must support a 80lb kid sitting on it. 4.5" floor clearance is a must. I don't think it would be strong enough (diagram is to scale). Any ideas to make it stronger are much appreciated. I'm in a remote area with limited tools (saw, drill, screws, glue, and 1 trip to home center)
A:
ideas to make it stronger
Resisting vertical forces
Add a rail front and rear, inset from front and rear edges. The rail would be 31" wide x 2" high. Make it taller for greater strength.
Resisting lateral forces
The greatest weakness is lateral collapse by lozenging. Adding metal corner brackets or adding a back panel would prevent that. With an inset back panel you wouldn't need a rear rail.
Minimum would be an unobtrusive triangular wooden brace centrally at each end of the underside of the top, glued with tenons or plenty of dowels.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ubuntu 14.04 x64 HPmini 100-3100 getting stuck
here is the thing:
I install last Ubuntu version in a Hp mini 110-3100 with n455 1.66ghz 64bit I-Atom processor and 2gb RAM, should i install Ubuntu 32bit? because, 64 bit is getting stuck for no reason and I have to do an hard-shutdown to my pc
thanks!
A:
To my knowledge, memory usage is higher on a 64bit operating system compared to a 32bit operating system, especially if you only have 2GB of RAM. So you could be handing out memory for nothing and ultimately.. causing your OS to get Frozen/Stuck.
Conclusion: Yes give a 32bit Operating System a go, but maybe just consider in upgrading from 2GB of Memory to 4GB of Memory, and make the most of 64bit processing.
You're Welcome!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If $w^2 + x^2 + y^2 = z^2$, then $z$ is even if and only if $w$, $x$, and $y$ are even
I'm trying to go through the MIT opencourseware Mathematics for Computer Science (6.042J). I've been stumped for half a day trying to figure it out. Something isn't clicking, and I could use some help.
Here is the problem:
Suppose that $w^2 + x^2 + y^2 = z^2$, where $w$, $x$, $y$, and $z$ always denote positive integers.
(Hint: It may be helpful to represent even integers as $2i$ and odd integers as $2j + 1$, where $i$ and $j$ are integers)
Prove the proposition: $z$ is even if and only if $w$, $x$, and $y$ are even. Do this by considering all the cases of $w$, $x$, $y$ being odd or even.
A:
The square of an odd number is one more than a multiple of $4$:
$$(2j+1)^2=4j^2+4j+1=4(j^2+j)+1,$$
and the square of an even number is exactly a multiple of $4$:
$$(2i)^2=4i^2.$$
In fact, it is easy to see that the converse holds as well. That is, for any integer $m$,
$$\begin{align*}
m\text{ is even }&\iff m^2\text{ is a multiple of 4},\\[0.1in]
m\text{ is odd }&\iff m^2\text{ is one more than a multiple of 4}.
\end{align*}$$
If none of the numbers $w,x,y$ are odd, then
$$z^2=w^2+x^2+y^2=(\text{multiple of 4})+(\text{multiple of 4})+(\text{multiple of 4})$$
is a multiple of 4, which implies $z$ is even.
If exactly one of the numbers $w,x,y$ is odd, then
$$z^2=w^2+x^2+y^2=(\text{multiple of 4})+(\text{multiple of 4})+(\text{multiple of 4})+1$$
is one more than a multiple of $4$, and therefore $z$ is odd.
Is it possible to have two, or all three, of the integers $w,x,y$ be odd, and have $z^2=w^2+x^2+y^2$ be true for some integer $z$?
My answer above is just a more verbose way of doing modular arithmetic, or more specifically, arithmetic modulo $4$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I place a normal HTML word between <> tags?
A very weird question in comparison with what is asked on this site generally, but:
I want to place a normal word between the <> tags. The output should be
<Random Word>. Of course a browser sees this as a HTML tag like <div> and doesn't display anything.
Strange enough I can't find a way to do this anywhere to my feeling is the solution is very easy.
A:
You should encode the signs
<Random Word>
Giving
<Random Word>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the important of the use of codeigniter database session (ci_session)
I need an answer from someone who have an experience with using codeigniter session. In config file i have to don't use session database because it cause a conflit in my code :
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
I use here session database off :
$config['sess_use_database'] = FALSE;
What's is the importante of using this? and may i have problems in security if i desactivate it (FALSE) ?
A:
This is from codeigniter you can read more here
http://www.codeigniter.com/user_guide/libraries/sessions.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Learning an instrument online
I took ballet and with ballet you gain something called muscle memory and if you learn incorrectly, it's almost impossible to become a great dancer. Because of this, you can't learn ballet out of a book or from a video -- you need an instructor to say "You're doing a great job" or "You need to do this instead."
Is learning an instrument online a bad idea because of the above reason or any other reason?
I would like to learn the flute, but I live pretty much in the middle of nowhere. I see that there are plenty of learn flute online courses, but I'm wondering if anyone has had any success with learning an instrument over the Internet, out of a book, from videos, etc? I'm not talking about people who see an instructor and then go home and practice out of a book, but rather those who never have the help of an instructor.
Edit: By "online", I mean courses in which I'm not interacting with an instructor.
A:
I think if one wanted to be a concert pianist or part of a symphony or something, there's no question that one should get a good teacher. Precision is necessary in these areas, and precision is exceptionally difficult to teach oneself. As well, you might never be exposed to some concepts through picking up things on your own that a teacher would deem absolutely necessary.
That said, it's not necessary to have a teacher in order to be a decent musician. While you might never go to a performance of amateur ballet dancers, people go see amateur(ish) musicians in concert all the time. Technique is rarely the focus, but rather creativity and artistry. These things can be enhanced by formal training but aren't really taught.
It's certainly easy to develop bad habits, but I think they can be corrected more easily in music than in ballet. My third piano teacher was much more competent than my first two, and managed to smack most of my bad habits out of me. It's also easy to ignore certain areas, such as theory and sight reading; but many people manage to ignore them even with a teacher. Memorizing a song can hide that you can't sightread quickly, and that sort of thing.
If you're focused enough, you can definitely achieve a high skill level without a teacher.
A:
Is the quality of online lesson good?
With very detailed, in-depth instructions like Youtube:ProfessorV's Violin lessons, one can confidently start learning an instrument. (find something similar for your instrument)
Are you aware of your mistakes?
Would you know if your posture is wrong or stressing some of your muscles unnecessarily? Could you detect your intonation flaws? If you've already learnt an instrument, and/or quite aware of technique, you will probably avoid getting stuck with bad habits.
As you say you've learnt ballet, you probably know the proper learning process, rather than hacking and learning to play a few cool tunes. There are very useful learning resources online. I don't see why you should hesitate, especially when there's no teacher around.
tip: record yourself
A:
From learning the flute as a kid, I would say that you will probably benefit from an instructor. But I don't think you need to see the instructor very often. If you can get to an instructor once every couple of months to make sure you aren't making any mistakes in your basic technique, that is probably enough.
So maybe instead of an instructor, you can call it a "coach". :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
algorithm to name files with no probability of repetition
Can someone suggest a complex algorithm in php to name files that would be uploaded so that it never repeats? i wonder how youtube which has millions of videos does it??
Right now i use an random number and get its 16 character sha1 hash and name the file with that name but i'm pretty sure it will eventually repeat and generate an error as file will not be able to save in the file system.
something like:
$name = sha1(substr(sha1(md5($randomnumber)),0,10));
somebody once told me that its impossible to break the hash generated by this code or at least it'll take 100 years to break it.
A:
you could do:
$uniq = md5(uniqid(rand(), true));
You could also apped user id of users uploading the file, like:
$uniq = $user_id_of_uploader."_".md5(uniqid(rand(), true));
A:
Do below with proper methods.
First slice its extension and filename
Now Trim the filename
Change multiple Space into single space
Replace special character and whitespace into to _
Prefix with current timestamp using strtotime and salt using md5(uniqid(rand(), true)) separated by _ (Thanks to @Sudhir )
Suffix with a special signature using str_pad and limit the text length of a file
Now again add extension and formatted file name
hope it make sense.
Thanks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find difference between two fields as columns in a table
I have the following sql below
SELECT
ttstudent.ttstudentid,
ttstudent.studentid,
ttstudent.subjectid,
ttstudent.classnumber,
ttstudent.classid,
concat(student.fn, " ", student.sn) AS Student,
SUM(If(ondemand.cycle="Feb7" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr7 Feb`,
SUM(If(ondemand.cycle="Jul7" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr7 July`,
SUM(If(ondemand.cycle="Feb8" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr8 Feb`,
SUM(If(ondemand.cycle="Jul8" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr8 July`,
SUM(If(ondemand.cycle="Feb9" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr9 Feb`,
SUM(If(ondemand.cycle="Jul9" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr9 July`,
SUM(If(ondemand.cycle="Feb10" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr10 Feb`,
SUM(If(ondemand.cycle="Jul10" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr10 Aug`,
ondemand.Student_ID
FROM ttstudent
INNER JOIN student ON ttstudent.studentid = student.code
INNER JOIN ondemand ON ttstudent.studentid = ondemand.Student_ID
GROUP BY ondemand.Student_ID
This generates for about 25 people a columnar list with the last column the calculated field that finds the difference between the last 2 values in the table. The scores are time stamped.
CODE |Year7Feb|Year7Jul|Year8Feb|Year8Jul|Year9Feb|Year9Jul| Year10Feb| Growth
abe1 | 2.3 | 2.9 | | | | | | .6
bas1 | | | 3.5 | 3.7 | | | | .2
cod | | | | | | 4.5 | 5.2 | .7
What I would like to do is a add another column which would take the last two scores from each user (whichever column it is in) and find the difference. I would call this column growth.
I am struggling with what to use other than max. Any ideas?
A:
This should do the trick:
Calculate column growth with the following query
SELECT si,ty,la.uid laid,pr.uid prid,(la.score-pr.score) growth FROM (
SELECT si,ty,max(test_date) cyprev, cylast FROM ondemand INNER JOIN (
SELECT Student_ID si,type ty,max(test_date) cylast FROM ondemand
GROUP BY Student_ID,type
) od ON si=Student_ID AND ty=type AND cylast>test_date
GROUP BY si,ty, cylast
) getlast2
INNER JOIN ondemand la ON la.Student_Id=si AND la.type=ty AND la.test_date=cylast
INNER JOIN ondemand pr ON pr.Student_Id=si AND pr.type=ty AND pr.test_date=cyprev
and then LEFT JOIN it to your overall query (slightly simplified version here):
SET @subj:="Numeracy";
SELECT Student_id,
SUM(If(ondemand.cycle="Feb7" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr7 Feb`,
SUM(If(ondemand.cycle="Jul7" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr7 July`,
SUM(If(ondemand.cycle="Feb8" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr8 Feb`,
SUM(If(ondemand.cycle="Jul8" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr8 July`,
SUM(If(ondemand.cycle="Feb9" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr9 Feb`,
SUM(If(ondemand.cycle="Jul9" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr9 July`,
SUM(If(ondemand.cycle="Feb10" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr10 Feb`,
SUM(If(ondemand.cycle="Jul10" and ondemand.type=@subj, ondemand.Score, NULL)) AS `Yr10 Aug`,
growth
FROM ondemand LEFT JOIN (
SELECT si,ty,la.uid laid,pr.uid prid,(la.score-pr.score) growth FROM (
SELECT si,ty,max(test_date) cyprev, cylast FROM ondemand INNER JOIN (
SELECT Student_ID si,type ty,max(test_date) cylast FROM ondemand
GROUP BY Student_ID,type
) od ON si=Student_ID AND ty=type AND cylast>test_date
GROUP BY si,ty, cylast
) getlast2
INNER JOIN ondemand la ON la.Student_Id=si AND la.type=ty AND la.test_date=cylast
INNER JOIN ondemand pr ON pr.Student_Id=si AND pr.type=ty AND pr.test_date=cyprev
) gt ON si=Student_id AND ty=@subj
GROUP BY Student_id;
I left out the JOINs to tables student and ttstudentand their columns
ttstudent.ttstudentid,
ttstudent.studentid,
ttstudent.subjectid,
ttstudent.classnumber,
ttstudent.classid,
concat(student.fn, " ", student.sn) AS Student
Edit:
Just made the changes using your test_date column. The subquery was tested in MySQL, I hope it also works in your database.
Edit2:
I slowly see where you are coming from. It's getting more and more complicated (just filled in the xtra conditions concerning type="Numeracy" ... Maybe there is an easier solution after all?
Anyway, here is a SQLfiddle to demonstrate the whole thing (and here a modified version: sqlfiddle2).
3rd and final edit:
What you probably want is something on the lines of SQLfiddle3 (--> only one SELECT command without a preceding SET statement). Your complete command should then look something like this:
SELECT
ttstudent.ttstudentid,
ttstudent.studentid,
ttstudent.subjectid,
ttstudent.classnumber,
ttstudent.classid,
concat(student.fn, " ", student.sn) AS Student,
SUM(If(ondemand.cycle="Feb7" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr7 Feb`,
SUM(If(ondemand.cycle="Jul7" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr7 July`,
SUM(If(ondemand.cycle="Feb8" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr8 Feb`,
SUM(If(ondemand.cycle="Jul8" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr8 July`,
SUM(If(ondemand.cycle="Feb9" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr9 Feb`,
SUM(If(ondemand.cycle="Jul9" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr9 July`,
SUM(If(ondemand.cycle="Feb10" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr10 Feb`,
SUM(If(ondemand.cycle="Jul10" and ondemand.type="Numeracy", ondemand.Score, NULL)) AS `Yr10 Aug`,
ondemand.Student_ID,
getdif.growth
FROM ttstudent
INNER JOIN student ON ttstudent.studentid = student.code
INNER JOIN ondemand ON ttstudent.studentid = ondemand.Student_ID
LEFT JOIN (
SELECT si,ty,la.uid laid,pr.uid prid,(la.score-pr.score) growth FROM (
SELECT si,ty,max(test_date) cyprev, cylast FROM ondemand INNER JOIN (
SELECT Student_ID si,type ty,max(test_date) cylast FROM ondemand
GROUP BY Student_ID,type
) od ON si=Student_ID AND ty=type AND cylast>test_date
GROUP BY si,ty, cylast
) getlast2
INNER JOIN ondemand la ON la.Student_ID=si AND la.type=ty AND la.test_date=cylast
INNER JOIN ondemand pr ON pr.Student_ID=si AND pr.type=ty AND pr.test_date=cyprev
) getdif ON si=ondemand.Student_ID AND ty=ondemand.type
WHERE ondemand.type='Numeracy'
GROUP BY ondemand.Student_ID
My previous versions reflected my personal preference of avoiding any kind of redundancy and also my ambition to parameterize things as much as possible. But I probably went a bit too far ;-).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get string between two strings [PHP]
Okay this is probably all over the internet but I can't find a solution and been searching and trying different ways.
So the main way i've tried so far is as following:
string:
<div data-image-id="344231" style="height: 399.333px; background-image: url("/website/view_image/344231/medium"); background-size: contain;"></div>
code:
preg_match_all('/(style)=("[^"]*")/i', $value, $match);
preg_match('/background-image: url("(.*?)");/', $match[2][0], $match);
print_r($match);
I'm guessing I can't use:
background-image: url(" and "); instead the preg_match
Could someone give me some guidence on how I can achieve getting:
"/website/view_image/344231/medium"
A:
If you use single quotes for the background image url instead of double quotes you could use DOMDocument and get the style attribute from the div.
Then use explode("; ") which will return an array where one item of that array will be "background-image: url('/website/view_image/344231/medium')".
Loop through the array and use preg_match with a regex like for example background-image: url\(([^)]+)\) which will capture in a group what is between the parenthesis.
If there is a regex match, store the value from the group.
$html = <<<HTML
<div data-image-id="344231" style="height: 399.333px; background-image: url('/website/view_image/344231/medium'); background-size: contain;"></div>
HTML;
$doc = new DOMDocument();
$doc->loadHTML($html);
$elm = $doc->getElementsByTagName("div");
$result = array ();
$style = $doc->getElementsByTagName("div")->item(0)->getAttribute("style");
foreach (explode("; ", $style) as $str)
if (preg_match ('/background-image: url\(([^)]+)\)/', $str, $matches)) {
$result[] = $matches[1];
}
echo $result[0];
That will give you:
'/website/view_image/344231/medium'
Demo Php
|
{
"pile_set_name": "StackExchange"
}
|
Q:
boiler switch transistor
I'd like to switch a boiler on and off electronically.
It is now connected to a thermostat.
The first thing I did was measuring the current flowing, closing the circuit with a multimeter set to DC. It is 0.44mA.
Then I switched to voltage and measured 90V.
I didn't expect such a high voltage.
I was wondering if I could use BC547 transistor, but I saw that limit on collector voltage is 50V. So I think it will not fit. However the current is very small so I don't know.
Do you have any suggestion ? May I still use this transistor, or you have another kind of transistor to suggest? I would use NPN transistors because they are the easiest to use. Would in this case be needed a different kind of transistor?
UPDATE
@ Dave Tweed: Good point the AC. I closed the circuit with my multimeter set to AC. I got 120V and 0.6mA. Now I don't know any more if it's DC or AC.
@ markrages: NPN transistors, as long as I have read are easier compared to PNP. What do you mean when you say they are not easy? Compared to what? I'm afraid I don't get the sense of your sentence.
@ George Herold and @ Peter Bennett: A relay is easy to intall and certainly working for my project. This is why I'm asking about transistors. However, I didn't consider the circuit isolation point, which I consider very valuable information, since I really don't know anything about the remote circuit. I just have 2 cables and I know that if I connect them the boiler powers on.
The reason why I am asking about transistors as an alternative to relay are the following
Relays are more expensive, more noisy (chatters), larger, more power demanding.
So I renew my question:
Does it make any sense to use a transistor to electronically turn on and off a remote circuit with the current characteristics outlined above?
In case nobody has any suggestion for this question I'll certainly use a realy as suggested.
A:
I would use a relay for this. A relay provides electrical isolation between the controlling circuit and the controlled circuit. You would not need to know anything about the controlled circuit: whether either side is grounded, polarity, voltage, AC/DC, etc., as long as the relay contacts are rated for the voltage and current they will need to handle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
using AES_DECRYPT to get data
I am trying to retrieve data from a table from some old legacy work, the Email field all have '[BLOB - 32 B]' in the fields therefore has been encrypted - can anyone explain how I use the AES_DECRYPT to collect the actual email address from this table?
I have the AES_PASSWORD in var stored already within one of the common functions.
A:
Where $key = AES_PASSWORD (Your key for the data)
Your SQL would be
$sqlinsert = "INSERT INTO tblemail (email) VALUES (AES_ENCRYPT('$email','$key'))";
$sqlget = "SELECT AES_DECRYPT(email,'$key') from tblemail;";
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the different commands available for nuget package manager console?
Can anyone post the different commands available in package manager console for visual studio.
examples:
install-package packagename
remove-package packagename
A:
Look at the nuget command line reference.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Invalid access to memory location with ReadFile
I have a file, C:\demo\Demo.txt, that has a simple "Hello, world" on it. I want to pass the path as argument to my app, open it with CreateFile, read it with ReadFile and show that line out on console. However, I am receiving an error code 998:
Invalid access to memory location.
This is my code:
int wmain(int argc, WCHAR **argv)
{
if (argc != 2)
{
fwprintf(stderr, L"\nWrong arguments. \n");
return 1;
}
// CreateFile function variables
HANDLE hSourceFile;
LPCWSTR fileName = (LPCWSTR)argv[1];
DWORD desiredAccess = FILE_GENERIC_READ;
DWORD shareMode = FILE_SHARE_READ;
DWORD creationDisposition = OPEN_EXISTING;
DWORD flagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
//---------------------------------------------------------------
// Opening file for reading data
hSourceFile = CreateFileW(
fileName,
desiredAccess,
shareMode,
NULL,
creationDisposition,
flagsAndAttributes,
NULL);
if (hSourceFile != INVALID_HANDLE_VALUE)
{
wprintf(L"\nThe source file, %s, is open. \n", fileName);
}
else
{
wprintf(L"Error code: %u\n", GetLastError());
}
// ReadFile function variables
LPVOID dataRead=NULL;
DWORD bytesToRead = 100;
DWORD bytesWritten = 0;
//-----------------------------------------------------------------
// Reading data from file
if (!ReadFile(
hSourceFile,
dataRead,
bytesToRead,
&bytesWritten,
NULL))
{
wprintf(L"Error code: %u\n", GetLastError());
return 1;
}
wprintf(L"%s. \n", (LPWSTR)dataRead);
CloseHandle(hSourceFile);
return 0;
}
First time I use ReadFile, so no idea what I am doing wrong.
Can you help me?
A:
ReadFile wants a pointer to a buffer into which it can write the data. You are passing NULL, so you get the error you see.
I would change the code to
// ReadFile function variables
static const DWORD bytesToRead = 100;
unsigned char dataRead[bytesToRead];
DWORD bytesWritten = 0;
//-----------------------------------------------------------------
// Reading data from file
if (!ReadFile(
hSourceFile,
dataRead,
bytesToRead,
&bytesWritten,
NULL))
{
wprintf(L"Error code: %u\n", GetLastError());
return 1;
}
The next problem you have, is that you are casting your pointer to LPWSTR, that is a pointer to a null-terminated wide string. Does your file contain that null termination? or do you need to add it yourself? Assuming the file doesn't contain the termination, you probably want:
// ReadFile function variables
static const DWORD bufferSize = 50;
WCHAR buffer[bufferSize+1]; // Leave room for null.
DWORD bytesWritten = 0;
//-----------------------------------------------------------------
// Reading data from file
if (!ReadFile(
hSourceFile,
buffer,
bufferSize*sizeof(WCHAR),
&bytesWritten,
NULL))
{
wprintf(L"Error code: %u\n", GetLastError());
return 1;
}
buffer[bytesWritten/sizeof(WCHAR)] = 0; // Null terminate.
wprintf(L"%s. \n", buffer); // Look ma! No cast needed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using config.ini for a project
I'm working on a project with PHP. I was planing to use a file called config.ini for gathering some settings including database information (password, username, name etc..).
I thought about .htaccess code to secure config.ini file
<Files config.ini>
order allow,deny
deny from all
</Files>
My question is if this will provide enough protection for config.ini file. In the end, I wouldn't like any user / visitor to see config.ini or access file if they don't have FTP account access.
Maybe this is a bad approach, I will be glad if you can share your experiences. I would like to go with ini file, maybe changing some settings in server might help to secure it better?
A:
I would personally recommend keeping the whole configuration file outside your http root, if possible. I think your setting should be enough to block access to it, though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Проблема с суммой значений
$(function() {
$(".test").click(function(){
var a=$("#l_inpt_1").val();
var b=$("#l_inpt_2").val();
var c=$("#l_inpt_3").val();
var sumS=(a+b+c)/3;
$(".midle_g p").append(sumS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Число 1" id="l_inpt_1">
<input type="text" placeholder="Число 1" id="l_inpt_2">
<input type="text" placeholder="Число 1" id="l_inpt_3">
<button class="test">Очистити поля</button>
<div class="midle_g">
<p></p>
</div>
У нас есть 3 инпута допустим в них мы впишем числа 1,2,3 по нажатию на кнопку у нас должно найти среднее значения (1+2+3)/3=2, но проблема в том что сума отображает как 123 а не 6!Как исправить!?
A:
У вас поля были добавлены не числами, а текстом. ParseFloat превращает текст в число
$(function() {
$(".test").click(function(){
var a = parseFloat($("#l_inpt_1").val());
var b = parseFloat($("#l_inpt_2").val());
var c = parseFloat($("#l_inpt_3").val());
var sumS = (a+b+c)/3;
$(".midle_g p").append(sumS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Число 1" id="l_inpt_1">
<input type="text" placeholder="Число 1" id="l_inpt_2">
<input type="text" placeholder="Число 1" id="l_inpt_3">
<button class="test">Очистити поля</button>
<div class="midle_g">
<p></p>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create array from file_get_contents() value
socallink.txt:
"Facebook","Twitter","Twitter","google-plus","youtube","pinterest","instagram"
PHP:
$file = file_get_contents('./Temp/socallink.txt', true);
$a1 = array($file);
print_r($a1);
Result :
Array
(
[0] => "Facebook","Twitter","Twitter","google-plus","youtube","pinterest","instagram"
)
Needed:
$a1['0']=facebook;
$a1['1']=Twitter;
A:
This solves your problem :
$file = '"Facebook","Twitter","Twitter","googleplus","youtube","pinterest","instagram"'; // This is your file
First remove all the ".
$file = str_replace('"', '', $file);
Then explode at every ,
$array = explode(',',$file);
var_dump($array) gives :
array(7) {
[0]=>
string(8) "Facebook"
[1]=>
string(7) "Twitter"
[2]=>
string(7) "Twitter"
[3]=>
string(11) "google-plus"
[4]=>
string(7) "youtube"
[5]=>
string(9) "pinterest"
[6]=>
string(9) "instagram"
}
Global code looks like :
$file = file_get_contents('./Temp/socallink.txt', true);
$file = str_replace('"', '', $file);
$a1 = explode(',',$file);
Hope this'll help
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can this object model for my Java application be improved?
I'm designing a Java application that will be used by contractors to diagram residences. Currently, I'm in the modeling phase and am creating a UML class diagram. My issue is that I'm not sure the ideal way to model some of my objects. Users will "draw" elements of the home like walls, lights, doors, windows, etc... Each element has an initial set of required properties. Based on this initial set of required properties, a sub set of different properties will be required for that element.
I'll use my Structure class as an example. One of the things a user will "draw" on the diagram is a Structure. A structure's two main properties are structureType and composition. Composition is straightforward. The client provides a list of possible compositions that that a user will select, so I put that data in a combo box and let the pick from a drop down. However, based on structureType, additional properties will be required.
IE) if StructureType = Wall, then length and height are required. If StructureType = Ceiling, then length, width and height are all required.
The example is simplified and may seem trivial, but the sub-properties can get much more involved than this, and there are many of them. Some of them give rise to even further sub-properties. However, despite the over simplification, it gives a pretty specific idea of the problem I'm trying to solve.
My thinking is that I should have subclasses extending Structure, each with a set of properties that are unique to each subclass. IE) class Wall extends class Structure, and contains a group of member variables unique to Walls.
Some advice on wether or not I'm thinking about this clearly would be appreciated, and if I'm off base a push in the right direction would be appreciated. Likewise if there's a consideration I've missed in my decision making, some constructive criticism is welcome.
A:
I would extend your thoughts a bit Further.
Instead of Properties being part of Structure, I would keep them aside, have an interface StrucutreProperties which has all common properties like getLength(), getWidth().
Then as you said have Wall extends Structure and in this case Wall will have WallProperties extends StructureProperties interface.
In case of Ceiling extend StructureProperties, there will be CeilingProperties extends StructureProperties and add getBreadth() to it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
adding classes through generic mouse over event
I have four background images on main page each parent of the background image has the width of 25% so that they can take up to full screen,now i have to do something like when one of them is hovered i need to add the class width-37 which means i am increasing the width of that specific div, by increasing the width of that specific i then need to decrease the width of other divs so that they may remain on the same line for that i will be adding the class width-27 to the divs other than the current div which has the width-37
here's my current code
Html:-
<div class="index-rel" id="index-height">
<div class="width-25">
<div class="img img1"></div>
</div>
<div class="width-25">
<div class="img img2"></div>
</div>
<div class="width-25">
<div class="img img3"></div>
</div>
<div class="width-25">
<div class="img img4"></div>
</div>
<div class="index-abs">
</div>
</div>
CSS:-
.index-rel {
position: relative;
}
.index-rel .width-25 {
width: 25%;
display: inline-block;
float: left;
height: 100%;
transition: all 0.5s ease;
}
.index-rel .width-37 {
width: 37%;
}
.index-rel .width-21 {
width: 21%;
}
.index-rel .img {
background-size: cover;
height: 100%;
background-repeat: no-repeat;
background-position: 53% center;
}
.index-rel .img1 {
background-image: url("../images/index (3).jpg");
}
.index-rel .img2 {
background-image: url("../images/index (4).jpg");
}
.index-rel .img3 {
background-image: url("../images/index (1).jpg");
}
.index-rel .img4 {
background-image: url("../images/index (2).jpg");
}
jQuery:-
$("#index-height").height($(window).height());
$(document).ready(function() {
$(".index-rel .width-25").mouseover(function() {
$(this).addClass("width-37");
});
$(".index-rel .width-25").mouseout(function() {
$(this).removeClass("width-37");
$(this).removeClass("width-21");
});
});
now the problem is i couldnt really make the logic in Jquery that on mouse over add width-37 to the current div and add width-21 to the other divs! any help?
Jsbin
A:
Need to do like below:-
$("#index-height").height($(window).height());
$(document).ready(function(){
$(".width-25").mouseover(function(){
$(this).addClass("width-37");
$('.index-rel').children().not($(this)).addClass('width-21');
});
$(".width-25").mouseout(function(){
$('.index-rel').children().removeClass('width-21');
$('.index-rel').children().removeClass('width-37');
});
});
Working example:- https://jsfiddle.net/5gcLq089/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
javafx Color parsing
Trying to let users select a custom Color scheme for their display.
User Input is turned into a javafx.scene.paint.Color c1.
c1 is a valid Color. However, when i feed it into the setStyle method there is a parser error:
System.out.println("c1 values: R" + c1.getRed()+ " G:"+ c1.getGreen()+" B:" + c1.getBlue());
Button test = new Button("test");
test.setStyle("-fx-background-color: " + c1);
Scene login = new Scene(test,640,480);
stage.setScene(login);
stage.show();
c1 is a valid Color:
"c1 values: R0.30588236451148987 Gb0.6745098233222961 B:1.0"
However there is a parsing error:
"WARNING: CSS Error parsing '*{-fx-background-color: 0x4eacffff}: Unexpected token '0x' at [1,24]"
I suspect the Color (which returns doubles) is clashing with -fx-background-color which is expecting a HEX ( ? )
Am i using the tools wrong or do i need to unpack the doubles manually and recast to HEX?
A:
Don't rely on Color.toString() to generate a valid string that can be parsed by the CSS parser. The Javadocs are pretty explicit about this:
Returns a string representation of this Color. This method is intended to be used only for informational purposes. The content and format of the returned string might vary between implementations. The returned string might be empty but cannot be null.
(my emphasis).
You can format a color in a web-friendly hex format with
String webFormat = String.format("#%02x%02x%02x",
(int) (255 * c1.getRed()),
(int) (255 * c1.getGreen()),
(int) (255 * c1.getBlue()));
If you want to allow transparency, you could do something like
String webFormat = String.format("rgba(%d, %d, %d, %f)",
(int) (255 * c1.getRed()),
(int) (255 * c1.getGreen()),
(int) (255 * c1.getBlue()),
c.getOpacity());
Then of course use
test.setStyle("-fx-background-color: " + webFormat + ";");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cascades of delegates and hijacking delegate callbacks in Objective-C
Say I write a UITextField subclass and want to have control over the text written into it by the user. I would set the input field's delegate to be myself and implement -textField:shouldChangeCharactersInRange:replacementString:.
However, I would still want to allow whatever part of code uses me as a text field to implement the usual delegate methods. An approach for that would be to store a second delegate reference and map them like so:
- (id)init {
self = [super init];
super.delegate = self;
return self;
}
- (void)setDelegate:(id)delegate {
self.nextDelegate = delegate;
}
- (id)delegate {
return self.nextDelegate;
}
I would then proceed to implement all UITextFieldDelegate methods and forward them to the next delegate as I wish. Obviously, I may want to modify some parameters before passing them on to the next delegate, like in -textField:shouldChangeCharactersInRange:replacementString:.
Another problem I'm thinking of is when the user's sets nextDelegate to the text field itself (for whatever reason), resulting in an infinite loop.
Is there a more elegant way to hijack delegate callbacks like in the example code I posted?
A:
The problem with your approach is the overridden delegate accessor: There's no guarantee that Apple's code always uses the delegate ivar directly and does not use the getter to access the delegate. In that case it would just call through to the nextDelegate, bypassing your sneaked in self delegate.
You might have checked that your approach works in the current implementation but this could also change in future UIKit versions.
Is there a more elegant way to hijack delegate callbacks like in the example code I posted?
No, I'm not aware of any elegant solutions. You could not override the delegate accessor and instead set up secondary delegate (to which you have to manually pass all delegate messages).
To solve the actual problem of filtering text input it might be worthwhile looking into
- (void)replaceRange:(UITextRange *)range withText:(NSString *)text;
This method is implemented by UITextField (as it adopts UITextInput) and could be overridden to filter the text argument.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get the value of a DropDownListFor in MVC6
I have been browsing stack for an answer and I see so many different ways of doing this, none of them works when i try them though. so maybe I am doing something fundamentally wrong in my code.
I have a dropdownlistfor which looks like this:
@Html.DropDownListFor(m => m.PrivilegesGroups.First().Id, new SelectList(Model.PrivilegesGroups, "Id", "Name"), new { id = "PrivilegeGroupIdDDL", @class = "tableInput" })
This is my model.
namespace My.Internal.Models {
public class UserViewModel {
public User User { get; set; }
public IEnumerable<PrivilegeGroup> PrivilegesGroups { get; set; }
public IEnumerable<Company> UserCompanies { get; set; }
}
}
Where User is a class with an Id, Name, UsersCompanyId and PrivilegeGroupId.
PrivilegeGroup is a class with: Id,Name.
Company is a class with: Id,Name.
My controller for saving looks like this.
[HttpPost]
public IActionResult ManageUsers(UserViewModel model) {
UserDao db = new UserDao();
User modelToSave = new User();
db.AddUpdateUser(modelToSave);
return RedirectToAction("ManageUsers");
}
I have tried different ways of getting the value of the selected dropdownlist item but have yet to manage to have it come back in the UserViewModel.
Any help in how to get the ID of the selected item would be much appreciated.
A:
You're doing two main things wrong here. First, you cannot execute a function in an expression like this:
m => m.PrivilegesGroups.First().Id
You will have to do the execution before you call the expression. Either add a variable to your ViewModel to contain the result of this, or execute the method into a local variable in your view (not really recommended, but it would work)
The other problem is that you're overriding the id:
new { id = "PrivilegeGroupIdDDL", @class = "tableInput" })
This is not good because you are taking away the helpers ability to prevent ID conflicts. This can result in invalid HTML and unexpected results.
As far as coming back in the UserViewModel, are you using an Html.BeginForm() correctly?
EDIT:
To add the ID to your model, just do something like this:
public class UserViewModel {
public User User { get; set; }
public int PrivelegesId { get; set; }
public IEnumerable<PrivilegeGroup> PrivilegesGroups { get; set; }
public IEnumerable<Company> UserCompanies { get; set; }
}
And in your controller you, execute the query:
model.PrivelegesId = myQuery.PrivelegesGroup.First().Id;
Then in your DropDownList:
DropDownListFor(m => m.PrivilegesId,
new SelectList(Model.PrivilegesGroups, "Id", "Name"), new { @class = "tableInput" })
I don't know what your Controller code looks like, so I just guessed at variable names, but you should be able to figure it out.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery Validation on entire page
I have a webpage developed in ASP.NET MVC 3 and I am using jQuery validator to validate my fields.
$.validator.setDefaults({
errorContainer: "#validationSummary, #validationNotice",
highlight: function (element, errorClass) {
$(element).css("border", "1px dotted red");
},
unhighlight: function (element, errorClass) {
$(element).css("border", "1px solid black");
}
});
This will give my fields a "red dotted border" when they aren't valid.
I have a text that i want to show IF all fields are valid in my page .
<div class="ReadyToSend" style="margin-top:50px;">
All fields are valid.
</div>
So I want to hide "ReadyToSend" if my page isn't valid and show it if ALL of my fields on the page is valid.
A:
try this
$.validator.setDefaults({
errorContainer: "#validationSummary, #validationNotice",
highlight: function (element, errorClass) {
$(element).css("border", "1px dotted red");
$(".ReadyToSend").hide();
},
unhighlight: function (element, errorClass) {
$(element).css("border", "1px solid black");
if($("#yourFormName").validate().checkForm()) {
$(".ReadyToSend").show();
}
}
});
make sure you add display: none on your ReadyToSend div
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I use conditionals and loops to simulate the Monty Hall porblem?
I'm starting to learn programming and am working with c and conditional loops right now. And I wanted to make an interactive simulation of the Monty hall car behind doors problem(One of the 3 doors has a car behind it, the other 2 have goats. After the used picks one, Monty reveals one of the others with the goat behind it and allows the user to switch to the other door). According to what I've read from C Programming a modern approach by K.N. King, this should be possible with a few functions, conditionals and loops. But The code I've written loops infinitely in one of my functions and I'm not sure why, here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// A function that gets a valid door input from the user
int chooseDoor(){
int choice = 0;
while(choice < 1 || choice > 3){
printf("Choose a door from 1 to 3: ");
scanf("%d",&choice);
printf("%d\n", choice);
}
return choice;
}
// A function to get a valid yes or no response from the user
int validateYn(){
char yn[1];
fgets(yn,1,stdin);
while(yn[0] != "Y" && yn[0] != "y" && yn[0] != "N" && yn[0] != "n"){
printf("Error: Please enter Y or N: ");
fgets(yn,1,stdin);}
if(yn[0] == "Y" || yn[0] == "y"){
return 1;}
else{
return 0;}}
int main(){
bool play = true; //conditional boolean to repeat the game
while(play){
int car, shown, other, choice; //initialisers for the door with the car, door that monty will reveal, the remaining door and door chosen by player
bool swap;
car = rand()%3; //select a random door between 1 and 3
choice = chooseDoor(); //call function to get user input of chosen door
printf("You picked door #%d", choice);
// A loop to find the lowest door that is not picked by the user and has a goat behind it
for(int i = 0; i<3; ++i){
if( i == car || i == choice){
continue;}
shown = i;
break;}
// A loop to find the remaining door besides the one revealed and the one user picks
for(int i = 0; i<3; ++i){
if( i == car || i == choice || i == shown){
continue;}
other = i;
break;}
printf("Monty opens door #%d, there's a goat!\nWould you like to switch to door #%d?", shown, other);
swap = validateYn();
// Change user choice if user says yes to swap
if(swap){
choice = other;}
// win if user choice had car, lose otherwise
if(choice == car){
printf("Monty opens door #%d, it's the car! You win!", car);}
else{
printf("Monty opens door #%d, there's a goat. You lose.", choice);}
}
printf("Would you like to play again?");
play = validateYn();
return 0;}
My friend also told me that a switch statement should make things easier, but I have no idea how to use them right, thanks
A:
there is only one problem in your code: you ask to the user if he wants to continue outside of the loop. Sometimes it happens, that's nothing so difficult to solve.
You just need to move the last user interaction block of code (last printf and last scanf), inside the while loop brackets.
I'm going to attach you here the code that fully works. I also made some update and changes:
Changed for loops iteration. Instead of 0..<3; ++i now is 1..<4; i++
Changed the fgets with a getchar, since you are taking in input only one char and not a string.
Added a fflush(stdin) to free input buffer after that you take a char, since when you take different kind of input, the scanf could go crazy and show up messy result.
Changed the randomness. Now the seed will change each iteration with srand and time
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
// A function that gets a valid door input from the user
int chooseDoor()
{
int choice = 0;
while (choice < 1 || choice > 3)
{
printf("Choose a door from 1 to 3: ");
scanf("%d", &choice);
}
return choice;
}
// A function to get a valid yes or no response from the user
int validateYn()
{
char yn;
yn = getchar();
while (yn != 'Y' && yn != 'y' && yn != 'N' && yn != 'n')
{
printf("Error: Please enter Y or N: ");
yn = getchar();
}
if (yn == 'Y' || yn == 'y')
{
return 1;
}
else
{
return 0;
}
}
int main()
{
srand((unsigned int) time(NULL)); // generating number with better randomness
bool play = true; //conditional boolean to repeat the game
while (play)
{
int car, shown, other, choice; //initialisers for the door with the car, door that monty will reveal, the remaining door and door chosen by player
bool swap;
car = 1 + rand() % 3; //select a random door between 1 and 3
choice = chooseDoor(); //call function to get user input of chosen door
printf("You picked door #%d", choice);
// A loop to find the lowest door that is not picked by the user and has a goat behind it
for (int i = 1; i < 4; i++)
{
if (i == car || i == choice)
{
continue;
}
shown = i;
break;
}
// A loop to find the remaining door besides the one revealed and the one user picks
for (int i = 1; i < 4; i++)
{
if (i == car || i == choice || i == shown)
{
continue;
}
other = i;
break;
}
printf("\nMonty opens door #%d, there's a goat!\nWould you like to switch to door #%d? (y/n).\nChoose: ", shown, other);
fflush(stdin);
swap = validateYn();
// Change user choice if user says yes to swap
if (swap)
{
choice = other;
}
// win if user choice had car, lose otherwise
if (choice == car)
{
printf("\nMonty opens door #%d, it's the car! You win!", car);
}
else
{
printf("\nMonty opens door #%d, there's a goat. You lose. ", choice);
}
printf("\n\nWould you like to play again?"); //here now it is inside the while loop
play = validateYn();
}
return 0;
}
Tip: Try to be a little bit more clear with indentation. You will be able to catch this kind of "brackets and scope errors" easily next time.
Furthermore that's true you could do this program with a switch to make it easy. They aren't so difficult to use. Good Luck!!
-Denny
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Smooth loading screen between scenes
I created a loading screen to display a loading animation as the next scene is loading. I load the next scene asynchronously with:
yield return SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);
And also set Application.backgroundLoadingPriority = ThreadPriority.Low;, but the behaviour is still the same as a regular level load.
Am I missing something?
Expected behaviour:
Exit level, and fade out.
Loading screen appears.
Once load is done, fade loading screen out.
Fade in next scene.
What is happening:
Exit level, and fade out.
Loading screen appears, frozen
Suddenly new scene fades in.
Once the load starts, the game just frezees, like with a regular Scene load.
I read that you have to set allowSceneActivation = false, so you can fade the loading screen out, and then set it to true to let unity finish loading, but this completelly freezes my game, like the async operation never finishes loading.
A:
When you load an scene with SceneManager.LoadSceneAsync() there are actually two things happening:
The gameObjects of the scene are loaded into memory.
Then the whole scene is enabled. All Awake() and Start() callbacks will be called for the objects in the scene.
The second step, enabling the scene, is what actually freezes unity, because unity is running all those initialization callbacks in your scripts in a single cycle.
Indeed setting SceneManager.LoadSceneAsync().allowSceneActivation to false will make the async operation to complete only the first step of the process, and will wait until it's set to true to begin the second part of the process.
But if you set allowSceneActivation to false and yield on the callback like this, you will freeze your game for good:
AsyncOperation AO = SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);
AO.allowSceneActivation = false;
yield return AO;
//Fade the loading screen out here
AO.allowSceneActivation = true;
Why? Because you are telling the Async operation to not proceed with the second step of the scene load, so the operation will never be completed.
If you want to know when the first part of the operation is ready, to then proceed with the second one, you have to rely on AsyncOperation.progress. This value will stop at 0.9f once it's waiting for the allowSceneActivation flag.
It should be something like this:
AsyncOperation AO = SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);
AO.allowSceneActivation = false;
while(AO.progress < 0.9f)
{
yield return null
}
//Fade the loading screen out here
AO.allowSceneActivation = true;
If you want the scene activation to not freeze your game, then you should keep your Awake and Start callbacks to a minimun, and initialize your scripts in a coroutine through several cycles.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does this line of CSS mean? @media only screen and (min-device-width: 320px) and (max-device-width: 480px)
I found the following line of code inside Wordpress' Twenty Eleven theme stylesheet.
What does it mean?
@media only screen and (min-device-width: 320px) and (max-device-width: 480px)
A:
It's called CSS3 Media Queries which is a technique to help your website adapt to various of screen dimensions or basically, it helps to deliver different styles to different devices.
Since you're new, let's break down your media query to two parts:
@media only screen
This means we will apply css styles to a device with a screen. The keyword only used here to hide style sheets from older browsers from seeing phone style sheet.
and (min-device-width: 320px) and (max-device-width: 480px)
This is quite obvious since it means that the specified css only applied when a device has a screen's size with minimum 320px and maximum of 480px in width dimension.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When is $\lim\limits_{t \rightarrow \infty} \mathbb{E}[X|\mathcal{F}_{t}] =\mathbb{E}\left[X|\lim\limits_{t\rightarrow\infty}\mathcal{F}_{t}\right]$?
When is $\lim\limits_{t \rightarrow \infty} \mathbb{E}[X|\mathcal{F}_{t}] =\mathbb{E}\left[X|\lim\limits_{t\rightarrow\infty}\mathcal{F}_{t}\right]$?
Is there a theorem like monotone convergence or dominated convergence for a problem of this sort?
One specific case of interest would be when $\{\mathcal{F}_{t}\}$ is a sequence of sub-sigma algebras such that $\forall s<t[\mathcal{F}_{s}\subseteq \mathcal{F}_{t}]$ (that is, it is non-decreasing).
A:
You should state all the premises and define your notations. For example,
let $(\Omega,\mathcal{F},P)$ be a probability space and let $\{\mathcal{F}_{t}\mid t\geq0\}$
be a filtration. Let $X:\Omega\rightarrow\mathbb{R}$ be an integrable
random variable.
Define $\mathcal{F}_{\infty}=\sigma\left(\cup_{t}\mathcal{F}_{t}\right)$.
For each $t\geq0$, note that $E\left[X\mid\mathcal{F}_{t}\right]$
is only determined a.e. What is the sense of convergence $\lim_{t\rightarrow\infty}E\left[X\mid\mathcal{F}_{t}\right]$
? Pointwisely a.e. ?
If this is what you want, you need to be careful: For the case of
sequence, if we want to talk about pointwise a.e. convergence $X_{n}\rightarrow X$,
for each $n$, we may modify $X_{n}$ on a $P$-null set and it would
not affect the conclusion. However, for limit process involving uncountably
terms, like $X_{t}\rightarrow X$, we are not allow to "For each
$t$, modify $X_{t}$ on a $P$-null set". Now, we immediately encounter
a problem: What is $E[X\mid\mathcal{F}_{t}]$? It is not a concrete
random variable, but it is only determined a.e.. It is true that $\{E[X\mid\mathcal{F}_{t}]\mid t\geq0\}$
is always a martingale. However, its sample paths are out of control.
Note that, if the filtration is standard, we can always choose a cadlag
modification for $\{E[X\mid\mathcal{F}_{t}]\mid t\geq0\}$ (a deep
result due to Doob) then invoke Martingale Convergence Theorem (uniformly
integrable version) and conclude that $\lim_{t\rightarrow\infty}E[X\mid\mathcal{F}_{t}]=E[X\mid\mathcal{F}_{\infty}]$
pointwisely a.e.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What Happens To MSMQ When Network Connection Lost
If I am using MSMQ over the web, what happens if the network connection is lost between client and server?
So can you still add messages to the Queue, and if so where are they stored? In the client app, or in the clients OS etc?
For instance if I have a windows service which is adding items to a queue in a different country. What if the network connection is lost, and the windows service is restarted. Do the messages get lost forever?
The other part of the question relates to the route that a message takes, is it sent directly to the receiving queue, or is it written into a queue on the client side? Does that require MSMQ to be installed on the sending server, and how about licensing for that?
Is there any good documentation to explain the required setup?
A:
Update: Regarding your follow up question. Yes you have to install msmq on the sending server. There aren't any licensing cost, because MSMQ is part of windows and not a separate software (just like the IIS). Here is documentation on "Setting Up a Message Queue" on windwos 2003.
Before Update: Outgoing message are stored in the outgoing queue of the sending server. They are not lost if the sending service is restarted. They will wait in the outgoing queues ( which can be inspected with the msmq manager ) for I don't know how long.
if the msmq service or the sending server are restarted. Then "express" messages will be lost. express or recoverable are properties of non-transcriptional messages.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Type expected declaration or statement at end of input
I am making a C program that is a simple calculator without a GUI, called "Quical". (Check out the code on Github). I am somewhat new to C, and so I am making some syntax errors. One of the errors is this:
expected declaration or statement at end of input
Another one of the errors that comes up is this:
else without a previous if
Here is my code.
Hopefully, this can shed some light as to why I am getting these syntax errors. Any help would be much appreciated.
A:
Your braces don't match. You have something like
main()
{
some statement
{
}
another
{
}
and it ends.
It is saying it wants a statement here. Try that and see what the next error is.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IntelliJ 12.0.2 - Elements within Test sources folder are not compiled
I have a Play! 2.0 application opened in IntelliJ 12.0.2 and created with play ideacommand.
Within test sources folder, I've created a unit test (using JUnit, nothing special here).
Both ways to run this unit test:
From Command-line: play test-only MyUnitTest => Works well
From IntelliJ IDE: Simply using "Run" button.
Output path compilation of unit test in IntelliJ matches the output path compilation of the command play test for tests.
What happened: IntelliJ well behaves when MyTest.class has been generated by the playcommand. It just benefit from it as soon as .class file is not removed.
However, I don't want to use play command and want to benefit from IDE to run tests.
When I manually remove MyTest.class from output compilation path, I expect IntelliJ to recreate it when I launch the test...but nothing happened.
How can I force IntelliJ to compile my unit tests and output them into the corresponding path?
May it be an issue with the most recent IntelliJ EAP version?
A:
According to the comments is seems to be a bug specific to the external make option. If the issue is reproducible with the latest IDEA 12.0.3 EAP version and latest Scala plug-in, it should be reported in YouTrack with the sample project reproducing it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Not being able to download dependency elasticsearch for playframework 2
I'm trying to implement elasticsearch in my play 2 app: https://github.com/cleverage/play2-elasticsearch but I get a problem when downloading the dependecy:
[warn] problem while downloading module descriptor: http://cleverage.github.com/play2-elasticsearch/releases/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml: Premature EOF (288ms)
play.plugins:
9000:com.github.cleverage.elasticsearch.plugin.IndexPlugin
application.conf:
elasticsearch.local=false
elasticsearch.client="192.168.0.101:9300"
elasticsearch.index.name="play2-elasticsearch"
elasticsearch.index.clazzs="models.*"
elasticsearch.index.show_request=true
Build.scala:
import sbt._
import Keys._
import PlayProject._
object ApplicationBuild extends Build {
val appName = "test"
val appVersion = "1.0-SNAPSHOT"
val appDependencies = Seq(
// Add your project dependencies here,
"mysql" % "mysql-connector-java" % "5.1.18",
"com.github.cleverage" % "elasticsearch_2.9.1" % "0.4"
)
val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings(
// Add your own project settings here
resolvers += Resolver.url("GitHub Play2-elasticsearch Repository", url("http://cleverage.github.com/play2-elasticsearch/releases/"))(Resolver.ivyStylePatterns)
)
}
plugins.sbt:
// Comment to get more information during initialization
logLevel := Level.Warn
// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.0.3")
Stacktrace:
play debug ~run
Listening for transport dt_socket at address: 9999
[info] Loading project definition from /Users/kalle/Projects/Heroku/test/project
[info] Set current project to test (in build file:/Users/kalle/Projects/Heroku/test/)
[info] Updating {file:/Users/kalle/Projects/Heroku/test/}test...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin [warn] problem while downloading module descriptor: http://cleverage.github.com/play2-elasticsearch/releases/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml: Premature EOF (288ms)
[warn] module not found: com.github.cleverage#elasticsearch_2.9.1;0.4
[warn] ==== local: tried
[warn] /usr/local/play-2.0.3/framework/../repository/local/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml
[warn] ==== Typesafe Releases Repository: tried
[warn] http://repo.typesafe.com/typesafe/releases/com/github/cleverage/elasticsearch_2.9.1/0.4/elasticsearch_2.9.1-0.4.pom
[warn] ==== Typesafe Snapshots Repository: tried
[warn] http://repo.typesafe.com/typesafe/snapshots/com/github/cleverage/elasticsearch_2.9.1/0.4/elasticsearch_2.9.1-0.4.pom
[warn] ==== GitHub Play2-elasticsearch Repository: tried
[warn] http://cleverage.github.com/play2-elasticsearch/releases/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml
[warn] ==== public: tried
[warn] http://repo1.maven.org/maven2/com/github/cleverage/elasticsearch_2.9.1/0.4/elasticsearch_2.9.1-0.4.pom
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: com.github.cleverage#elasticsearch_2.9.1;0.4: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[error] {file:/Users/kalle/Projects/Heroku/test/}test/*:update: sbt.ResolveException: unresolved dependency: com.github.cleverage#elasticsearch_2.9.1;0.4: not found
[warn] some of the dependencies were not recompiled properly, so classloader is not avaialable
[info] Updating {file:/Users/kalle/Projects/Heroku/test/}test...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin [warn] problem while downloading module descriptor: http://cleverage.github.com/play2-elasticsearch/releases/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml: Premature EOF (264ms)
[warn] module not found: com.github.cleverage#elasticsearch_2.9.1;0.4
[warn] ==== local: tried
[warn] /usr/local/play-2.0.3/framework/../repository/local/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml
[warn] ==== Typesafe Releases Repository: tried
[warn] http://repo.typesafe.com/typesafe/releases/com/github/cleverage/elasticsearch_2.9.1/0.4/elasticsearch_2.9.1-0.4.pom
[warn] ==== Typesafe Snapshots Repository: tried
[warn] http://repo.typesafe.com/typesafe/snapshots/com/github/cleverage/elasticsearch_2.9.1/0.4/elasticsearch_2.9.1-0.4.pom
[warn] ==== GitHub Play2-elasticsearch Repository: tried
[warn] http://cleverage.github.com/play2-elasticsearch/releases/com.github.cleverage/elasticsearch_2.9.1/0.4/ivys/ivy.xml
[warn] ==== public: tried
[warn] http://repo1.maven.org/maven2/com/github/cleverage/elasticsearch_2.9.1/0.4/elasticsearch_2.9.1-0.4.pom
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: com.github.cleverage#elasticsearch_2.9.1;0.4: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[error] {file:/Users/kalle/Projects/Heroku/test/}test/*:update: sbt.ResolveException: unresolved dependency: com.github.cleverage#elasticsearch_2.9.1;0.4: not found
1. Waiting for source changes... (press enter to interrupt)
A:
Got a workaround from nboire from play2-elasticsearch project:
Download the project from github. Go to project
cd module
play compile
play publish-local
Then your other projects will download from your local instead of http://cleverage.github.com
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ubuntu に IPv6 接続したい
さくらインターネットで運用しているサーバーが IPv6 を受け入れていないことが判明して
受け入れるように設定中なのですがうまく行きません
https://manual.sakura.ad.jp/cloud/network/switch/ipv6.html#id3
こちらの設定を行って IPv6 アドレス自体は有効になりました
その後 ip6tables の設定が
ip6tables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
と何の設定もされていなかったので
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmpv6 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT
COMMIT
という HTTPS だけ許可するルールを書いて
ip6tables-restore < /etc/iptables/iptables.rules.v6
を実行したところ
外部からの curl がタイムアウトから
curl: (7) Failed to connect to xxxxxxxx port 443: Connection refused
に変わりました
IPv4 でアクセスすると nginx が応答するんですが
IPv6 でアクセスするにはこの状態からさらに何が足りないんでしょうか
A:
nginxの設定ファイルはどうなっていますか?たとえばserverディレクトリにlistenが
listen 443;
のみが存在していれば、
listen [::]:443;
のようなv6待受の設定が必要です。
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Validate Admin Inline form
I the Admin interface, I need to validate a field which is inside an Inline. Site has a name which has to be stored in lowercase.
How can I access to the name field in the inline to perform that validation?
I could also override its save method in models but I'd like to know how to do it in admin.
class SiteInline(admin.TabularInline):
model = Site
classes = ('grp-collapse grp-open',)
inline_classes = ('grp-collapse grp-open',)
class CompanyAdmin(admin.ModelAdmin):
ordering = ['name']
inlines = (SiteInline, )
A:
You can use Regex to validate the field.
admin.py
from django import forms
from django.contrib import admin
from django.core import validators
from django.utils.translation import ugettext_lazy as _
from .models import Company, Site
class SiteInlineAdminForm(forms.ModelForm):
name = forms.CharField(max_length=16,
help_text=_('Required. lower case character For Example: test'),
validators=[
validators.RegexValidator(r'^[a-z]*$',
message=_('Enter a valid name. This value may contain only lower case character.')),
])
class Meta:
model = Site
exclude = ()
class SiteInline(admin.TabularInline):
model = Site
form = SiteInlineAdminForm
classes = ('grp-collapse grp-open',)
inline_classes = ('grp-collapse grp-open',)
class CompanyAdmin(admin.ModelAdmin):
ordering = ['name']
inlines = (SiteInline, )
admin.site.register(Company, CompanyAdmin)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
levelplot does not display content
I am new to the function level plot. Ich have x,y,z that I want to visualize level plot the following way:
> require(lattice)
> head(z)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 4.5 4.7 4.6 4.6 4.6 4.6 4.6 4.6 4.7
[2,] 4.5 4.6 4.6 4.6 4.6 4.6 4.6 4.6 4.7
[3,] 4.5 4.7 4.6 4.6 4.6 4.6 4.7 4.6 4.7
[4,] 4.5 4.6 4.6 4.6 4.6 4.6 4.6 4.6 4.7
[5,] 4.6 4.6 4.6 4.6 4.6 4.6 4.6 4.6 4.7
[6,] 4.5 4.7 4.6 4.6 4.6 4.6 4.6 4.6 4.7
> head(y)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 5
[5,] 7
[6,] 10
> head(x)
[1] "2013-01-03 04:30:00 GMT" "2013-01-03 04:45:00 GMT" "2013-01-03 05:00:00 GMT"
[4] "2013-01-03 05:15:00 GMT" "2013-01-03 05:30:00 GMT" "2013-01-03 05:45:00 GMT"
z represents water temperatures and y water depths
I want to plot the data the following way:
> levelplot(z~x*y)
The axes and legend get plotted correctly, but the content is not plotted at all. Can anyone help me??
Best regards,
Philip
A:
Although I have no idea why what you tried didn't work, it seems that using levelplot.array instead of levelplot.formula works correctly (with aspect="fill" specified):
x <- as.POSIXct(x) #make sure x are POSIXct and not just characters
levelplot(z, row.values=x, column.values=y, aspect="fill")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between these two pointer to char initialisations
I know this has been answer before, but I can't find the question.
What are the differences between these two initialisations:
int main()
{
char* pch1;
char* pch2;
pch1 = (char*)malloc(sizeof(char) * 5);
strcpy(pch1, "Text");
pch2 = "Text";
}
A:
First: don't cast the return value from malloc - it's a common source of errors. Do I cast the result of malloc?
pch1 = malloc(sizeof(char) * 5);
assigns a pointer to a dynamically allocated block of 5 bytes on the heap.
pch2 = "Text";
should ideally be avoided because it assigns a pointer to a string literal. String literals are read-only on most OSes and is also a common source of mistakes. If you do this you should make the pointer to const
const char * pch2 = "Text";
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sliding divs only when clicking on buttons within the divs
I'm trying to use JQuery to slide a div with some content to the left and make the one from the right appear in the place of the previous one.
I already made it work but the thing is, it only works when I click on the div (box) that contains all the content.
I want to change that so it only changes when I click on the buttons within those divs (boxes).
Take a look at this: https://jsfiddle.net/Msiric/g8Lne34o/1/
So what I want to do is this:
$(document).ready(function () {
$('.buttons').click(function() {
$('.box').animate({
left: '-125%'
}, 500, function() {
$('.box').css('left', '150%');
$('.box').appendTo('#inputform');
});
$('.box').next().animate({
left: '25%'
}, 500);
});
});
Notice the $('.buttons).onclick instead of $('.box').onclick.
When I do this the code doesn't work as expected.
Thanks
A:
You need to bind the event to buttons and animate the boxes using $(this).closest(".box")
Demo
$(document).ready(function() {
$('.buttons').click(function() {
$(this).closest(".box").animate({
left: '-125%'
}, 500, function() {
$(this).css('left', '150%');
$(this).appendTo('#inputform');
});
$(this).closest(".box").next().animate({
left: '25%'
}, 500);
});
});
#inputform {
position: relative;
margin: 0px;
padding: 0px;
width: 100%;
height: 100px;
overflow: hidden;
}
.box {
position: absolute;
width: 100%;
height: 100px;
line-height: 300px;
font-size: 50px;
text-align: center;
left: 25%;
margin-left: -25%;
}
#box1 {
background-color: #333;
}
#box2 {
background-color: #333;
left: 150%;
}
#box3 {
background-color: #333;
left: 150%;
}
#box4 {
background-color: #333;
left: 150%;
}
#box5 {
background-color: #333;
left: 150%;
}
#requestbox {
width: 75%;
height: 25px;
display: block;
float: left;
margin-left: 3.1%;
border-radius: 5px;
font-size: medium;
line-height: 25px;
font-weight: bold;
transition: all 0.3s ease;
font-family: "Helvetica";
resize: none;
}
#requestbox:focus {
height: 100px;
}
.forms {
width: 75%;
height: 25px;
display: block;
float: left;
margin-left: 3.1%;
border-radius: 5px;
font-size: medium;
line-height: 25px;
font-weight: bold;
transition: all 0.3s ease;
font-family: "Helvetica";
resize: none;
}
.buttons {
display: block;
width: 18%;
height: 31px;
background: linear-gradient(rgb(70, 42, 24), rgb(244, 117, 33));
border-radius: 5px;
font-size: medium;
line-height: 15px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputform">
<div id="box1" class="box">
<textarea placeholder="Some text" id="requestbox" class="forms"></textarea>
<button id="next" class="buttons">Next</button>
</div>
<div id="box2" class="box">
<textarea placeholder="Some text" id="setbox" class="forms"></textarea>
<button id="set" class="buttons">Set</button>
</div>
<div id="box3" class="box">
<textarea placeholder="Some text" id="attachbox" class="forms"></textarea>
<button id="attach" class="buttons">Attach</button>
</div>
<div id="box4" class="box">
<textarea placeholder="Some text" id="confirmbox" class="forms"></textarea>
<button id="confirm" class="buttons">Confirm</button>
</div>
<div id="box5" class="box">
<textarea placeholder="Some text" id="publishbox" class="forms"></textarea>
<button id="publish" class="buttons">Publish</button>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get Windows user C#
I have a WPF application that needs to get the Windows username of the user. I am using the following line of code:
MessageBox.Show("Your username is:\n" + WindowsIdentity.GetCurrent().Name);
This works fine on my computer and computers of our other developers, but for others, it crashes. I'm assuming this is a permissions issue. Here is the error:
Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01: notesformultipleproperties.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 51cb04a1
Problem Signature 04: PresentationFramework
Problem Signature 05: 4.0.0.0
Problem Signature 06: 504dc7da
Problem Signature 07: 7b4d
Problem Signature 08: 0
Problem Signature 09: System.Windows.Markup.XamlParse
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 1033
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
Can I allow this line of code to run no matter what permissions the user has?
A:
How about Environment.UserName? It will return "the user name the current process is running under".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ggmap in R: How do I extract individual location features from geocoding?
I'm trying to clean up user inputted addresses, so I thought using GGMAP to extract the Longitude/Latitude and Address used would be a way to clean everything up. However, the Address it spits out sometimes has colloquial names in the address and it makes it hard to parse out the individual location aspects.
Here's the code I'm using
for(i in 1:nrow(Raw_Address))
{
result <- try(geocode(Raw_Address$Address_Total[i], output = "more", source = "google"))
Raw_Address$lon[i] <- as.numeric(result[1])
Raw_Address$lat[i] <- as.numeric(result[2])
Raw_Address$geoAddress[i] <- as.character(result[3])
}
I tried changing the "latlona" to "more" and going through the result numbers, but only got back different longitude/latitudes. I didn't see anywhere in the documentation that shows the results vectors.
Basically, I want Street Name, City, State, Zip, Longitude, and Latitude.
Edit: Here's an example of the data
User Input: 1651 SE TIFFANY AVE. PORT ST. LUCIE FL
GGMAP Output: martin health systems - tiffany ave., 1651 se tiffany ave, port st. lucie, fl 34952, usa
This is hard to parse because of the colloquial name. I could use the stringr package to try and parse, but it probably wouldn't be all inclusive. But it returns a distinct address while some users spell "Tiffany" wrong or spell out "Saint" instead of "St."
A:
Rather than using a for loop, purrr::map_dfr will iterate over a vector and rbind the resulting data frames into a single one, which is handy here. For example,
library(tidyverse)
libraries <- tribble(
~library, ~address,
"Library of Congress", "101 Independence Ave SE, Washington, DC 20540",
"British Library", "96 Euston Rd, London NW1 2DB, UK",
"New York Public Library", "476 5th Ave, New York, NY 10018",
"Library and Archives Canada", "395 Wellington St, Ottawa, ON K1A 0N4, Canada"
)
library_locations <- map_dfr(libraries$address, ggmap::geocode,
output = "more", source = "dsk")
This will output a lot of messages, some telling you what geocode is calling, e.g.
#> Information from URL : http://www.datasciencetoolkit.org/maps/api/geocode/json?address=101%20Independence%20Ave%20SE,%20Washington,%20DC%2020540&sensor=false
and some warning that factors are being coerced to character:
#> Warning in bind_rows_(x, .id): Unequal factor levels: coercing to character
#> Warning in bind_rows_(x, .id): binding character and factor vector,
#> coercing into character vector
which they should be, so you can ignore them all. (If you really want you can write more code to make them go away, but you'll end up with the same thing.)
Combine the resulting data frames, and you get all the location data linked to your original dataset:
full_join(libraries, library_locations)
#> Joining, by = "address"
#> # A tibble: 4 x 15
#> library address lon lat type loctype north south east west
#> <chr> <chr> <dbl> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 Librar… 101 In… -77.0 38.9 stre… rooftop 38.9 38.9 -77.0 -77.0
#> 2 Britis… 96 Eus… -0.125 51.5 stre… rooftop 51.5 51.5 -0.124 -0.126
#> 3 New Yo… 476 5t… -74.0 40.8 stre… rooftop 40.8 40.8 -74.0 -74.0
#> 4 Librar… 395 We… -114. 60.1 coun… approx… 83.1 41.7 -52.3 -141.
#> # … with 5 more variables: street_number <chr>, route <chr>,
#> # locality <chr>, administrative_area_level_1 <chr>, country <chr>
You may notice that Data Science Toolkit has utterly failed to geocode Libraries and Archives Canada, for whatever reason—it's marked as a country instead of an address. Geocoders are faulty sometimes. From here, subset out whatever you don't need.
If you want even more information, you can use geocode's output = "all" method, but that returns a list you'll need to parse, which takes more work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Attach physical menu button to my preferences screen
My app has a classic PreferenceScreen which activity is triggered by a dedicated button on my UI.
When I click the "Menu" button of the AVD, or the physical menu button on my device, a "Parameter" button shows at the bottom of the screen : pressing on it has no effect, how can I attach it to my actual preference screen, just like my button already does ? Thanks.
(I guess all I need is to be able to find it to attach a OnClick listener to it)
EDIT : I am targeting API Level 14+
A:
Found it : by tracking key "action_settings" that was automatically generated, I ended up un MyMainActivity.onOptionsItemSelected(MenuItem item), which is a stub for selected options.
I just had to create and launch an Intent to my Settings activity from here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Experts on ELU assure us that there is no subjunctive mood in English. How should we who have been mistaught refer to what we were taught?
Here are some examples.
"Until the Son of God appear" What I was taught: Subjunctive of indefinite future.
"It is required that the applicant be 18 years old and possess a valid driver's license." What I was taught: mandative subjunctive.
"Where be ye going," said the false knight on the road?" What I was taught: subjunctive of direct discourse.
"If I were you, which we both are thankful I am not, I wouldn't do that. What I was taught: The subjunctive mood is used for supposition contrary to fact.
"I dreamed I were a fireman in my Maidenform bra." What I was taught: The subjunctive mood can be used with words like dream.
"God bless you." I don't remember, so obviously I wasn't taught.
I can live with Pluto's not being a planet, but I must say it's irksome to find that so much of what I was told about English turns out to be nonsense.
A:
Unfortunately, learning names - such as subjunctive - does not necessarily constitute knowledge (on this see the humorous interview of Richard Feynman on the name of birds).
A difficulty of English grammar
What makes English grammar sometimes difficult to understand, especially for native speakers, is that it has very few inflections. Whereas in other languages (French, Italian), you would have different forms for infinitive, subjunctive, etc., in English the same "atom" has to be repurposed for many uses.
This economy of means is a truly remarkable feature of the English language and it might be a factor in the ease with which foreigners can learn it. On the other hand, that could also be a drawback in some cases.
For example eat in English could translate (among others) into French as:
manger (infinitive)
mange (1st/3rd person singular or imperative)
manges (2st person singular)
In those more inflected languages, grammar is often easier to learn, because it may be sufficient to look at the word itself to understand its function. And since categorizing things by shape rather than meaning is far easier, grammar may appear clearer on that account. In a language such as English, people are more liable to get confused when the same form is used to mean different things (polysemy).
Back to your question, we are dealing with two distinct phenomena:
Infinitive used as imperative, third person
God bless you.
It is required that the applicant be 18 years old and possess a valid driver's license.
What you were taught is a mandative subjunctive, in reality conveys an idea of imperative of the 3rd person (which could be said existed in Latin: caveat emptor: the buyer must beware; but it was also the form of the subjunctive). Since most Western languages of the Middle Ages are sadly missing this useful form, they had to resort the same gimmick: so they used prevalently the subjunctive form to convey that idea.
Que Dieu vous bénisse.
Nous exigeons que le candidat ait 18 ans.
Since (modern) English did not have even that tense (formally), it fell back to infinitive. Now, why English grammarians called their repurposed infinitive a subjunctive, instead of an imperative is (my guess) because they wanted to align their terminology on French, which used to be the aristocratic language under the Anglo-Norman monarchy and then remained a language of culture.
While the solution of the grammarians may have been handy, we could argue they could have carried their reasoning to its logical conclusion. Regardless of how we conventionally call this bird (there would not be a sufficient case to abolish the term subjunctive), it is semantically an imperative.
Simple past used as a hypothetical condition
If I were you, which we both are thankful I am not, I wouldn't do that.
In that case, it seems a calque (loan) from French:
Si j'étais vous (...)
... which was the imperfect (and not the French simple past), which kind of makes sense: the condition is not realized.
Unfortunately, the simple past in English is also used to convey the imperfect when needed. In this case again, a simple linguistic device was thrown into the big cauldron of polysemy. The problem is that the meaning of "if I were you", is easily understandable intuitively, but to explain why it takes this form becomes difficult, unless one already has notions of other languages.
Back to your "if I were", this pretended subjunctive is actually used to build a conditional sentence, which would be, in French:
Si j'étais vous, je ne ferais pas cela.
Again, English is lacking the inflections necessary for the conditional, which is why the auxiliary form would (invariable) is used. Hence:
If I were you, I would not do that.
As for:
I dreamed I were a fireman.
It is a simple past form ("I were" used to be common, before it became obsolete). While it has gone out of usage for most cases, it has remained acceptable for expressing unreal situations -- likely by analogy with the previous case, or perhaps a kind of attraction -- and it is conventionally called subjunctive. Actually, one would easily use the modern form and (at the cost of losing an almost imperceptible nuance) it might communicate the idea just as well:
I dreamed I was a fireman.
A:
Where be ye going?
This is not the subjunctive, it's an alternative conjugation of the verb to be which was used alongside the regular conjugation until the 17th Century, and is still present in some dialects of English.
I am, thou art, he is, we are, ye are, they are.
I be, thou beest, he is, we be, ye be, they be.
See this webpage.
The King James Bible uses both be and are for the indicative of verbs in the plural, although it uses the standard forms in the singular.
The rest of your examples really are some of the many uses of the subjunctive in Early Modern English.
There are only two common uses of the subjunctive left in current speech—the mandative subjunctive:
Calvin the Bold demands that he be addressed by his full title.
This is common in American English, less so in British English.
And the use of were for some hypothetical situations.
If I were a tiger, that would be neat!
This one is gradually being replaced with "If I was ..."
These two constructions look completely different now, so some grammarians decided it would be less confusing if we called the were-subjunctive the irrealis instead. So some people here insist that this is not a subjunctive, even though it is descended from one of a wide class of subjunctive uses in Middle English, which in turn were descendants of the subjunctive conjugation in Indo-European, just like the subjunctive conjugations in Romance languages.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Playing a Coltrane polychord and the limits of space
As I was the reading sheet music for John Coltrane's A Love Supreme, I noticed a chord I had never seen before. It looks like this:
I'm familiar with slash chords, but never had to practically encounter a polychord like Gm over Fm7.
The notes would be G, Bb, D played on top of F, Ab, C, Eb. Is this feasible to play on a six-string guitar? In other words, is there any theory of consolidation in terms of playing polychords with limited space?
A:
Unless you have a seven string guitar, this chord is impossible to play on guitar if you want all chord degrees represented. Since it is a G-minor chord over an Fm7, you can really think of the total composite chord as an Fm13, which is a pretty standard jazz chord for guitarists. . . or any jazz player for that matter.
What notes you leave out in part depends on the ensemble you're playing in. For example, if you're playing in a jazz trio with guitar, sax, and drums then you're going to need to cover at least some of the rudimentary harmony (root, third, seventh, etc) with a frugal selection of upper-tertian harmony (say, the ninth and thirteenth.) Choosing a five-note chord in this way is good for having an active bass line, which is important if you're playing fingerstyle.
If you're playing with a bassist or a pianist (or both) then usually with upper-tertian chords the guitar plays a lot of the "active" or "filler" harmonies - notably chord extensions and other active tones.
On the other hand, if you want to show a clear delineation between the chords (such as Coltrane notated) then it would be wise for you to voice the Fm7 below a Gm triad. Since you will have to obviously omit one note, the fifth of the Fm7 would be omitted since it is a four note chord and the fifth is almost always omitted first as it is the least harmonically active of the pitches.
Thus, an example of an appropriate voicing would be (from lowest to highest):
F, Ab, Eb, G, Bb, D
That said, the lead sheet does not indicate the inversion of the chord, so feel free to experiment with shapes that give you the easiest flexibility - as long as the two chords remain separate. As indicated in the score, one or both chords may be in inversion if necessary.
Hope that helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sphinx search:'total_found' not exact?
I found total_found not exact through several tests:
In one of the tests, the total_found was 40379, the limit i set was (0,20), then i set the offset to be 2000 and the result was null. Not Until I set the offset much more lower it returned results.
What's the problem? Can anyone help me out? Thank you!
A:
See the total variable - it is your current limit of max matches.
You can change max matches limit in searchd section of sphinx.conf
max_matches = 100000
Restart searchd.
And then in application
$cl->SetLimits(2000, 20, 100000);
Last variable is the max matches limit.
This is done in this way because of performance, lower value of max matches give you better performance.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I build an auto email alert system based on saved searches?
Ok, what I'm trying to do is build a feature for a real estate website that will allow users to do the following:
register on the site,
do a search of properties stored in a channel,
save the search criteria,
then receive an email alert when a new property is added that matches their saved search
I've done some research on this and there doesn't seem to be a straightforward way to do this in EE. I've seen MX Notify Control addon but it seems that this would alert on all new entries to a channel to all users.
Below is what I'm thinking of doing. I'm hoping I could get some input from the EE community on what they think of this approach, is it overcomplicating things or maybe there's a suggestion for a better approach.
Here goes:
Install Solspace Super Search and Email-from-Template addons
Allow users to register on the site using native EE functionality
Users can then search the entries in a "Property" channel based on keyword, price, location and/or status.
Then allow users to save their search using Solspace Super Search and their Save Search Form tag
I could create a standalone page then that loops through all saved searches using the exp:super_search:history tag, pull out the search criteria, use that criteria to do a search of the property channel and limit the results to ones added in the last 24 hours only.
If entries are retrieved, create an html email with the property details and send the mail using Email-from-Template addon or possibly through Postmark App or similar.
Set up a cronjob to run this page every 24 hours at a quiet time of the day, e.g. 4am
So, that's what I'm thinking. I know this page could become quite resource intensive with loops within loops (the more members and saved searches, the longer it will take to process) but I can't think of another way to do this.
Anybody got any suggestions, ideas or pitfalls I should consider?
Or maybe I should write a custom addon to do this?
Thanks,
Dave
A:
Not a complete answer though, I feel it could be one piece of the puzzle or at least an option.
Have you checked out Postmaster yet?
http://devot-ee.com/add-ons/postmaster
Postmaster is the definitive solution for emailing channel entries
within ExpressionEngine. Create beautiful email templates using the
live preview, and impose extremely fine levels of control to send
emails exactly when you want. Whether it be from the publish entries
page in the control, to Safecracker on the front-end, or in a custom
application using the channel entries API, Postmaster is the perfect
for almost any application.
Postmaster supports a variety of email services including MailChimp,
CampaignMonitor, SendGrid, Postmark, PostageApp, and even a full
featured API to create your own.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why didn't Project Mercury advance to an orbital flight on their second mission?
Manned programs are noted for progressing through a series of flights. Early missions focus on basic hardware and simple tasks; as the technology becomes proven, the scope and duration of later missions are increased. This is also affected by limited budgets and schedules; there simply aren't enough resources to repeat the same mission over and over. Thus, subsequent flights typically advance the spacecraft technology or have new scientific objectives.
Given the success of the first Mercury flight (Shepard), why was the next mission (Grissom) essentially the same? It wasn't until the third flight (Glenn) that NASA attempted an orbital mission.
A:
You have to remember that during Project Mercury, not only crewed spaceflight was in its infancy, but spaceflight itself was.
The Mercury-Redstone rocket could not achieve orbit, it wasn't powerful enough. Only Mercury-Atlas could, and the first crewed Mercury-Atlas flights was Glenns and thus orbital. So the answer is that they went orbital as soon as the LV allowed (and it took five uncrewed MA tests before they put a human in that stack).
The goals of MR-4 are described as following:
The main objective was to corroborate the man-in-space concept. The main configuration differences between the MR-3 spacecraft was the addition of a large viewing window and an explosively actuated side hatch.
The addition of the large viewing window was a result of a change requested by Mercury astronauts. This window allowed the astronauts to have a greater viewing area than the original side port windows. The field of view was 30 degrees in the horizontal plane and 33 degrees in the vertical. The window is composed of an outer panel of 0.35-inch thick Vycor glass and a 3-layer inner panel.
The explosively actuated side hatch was used for the first time on the MR-4 flight.
[...]
Flight successful but the spacecraft was lost during the post landing recovery period as a result of premature actuation of the explosively actuated side egress hatch.
Testing the new hatch before undertaking the next truly big step seems reasonable. The hatch blew early, so clearly the testing was warranted. You wouldn't want the hatch to blow during your orbit.
Another change from MR-3 to MR-4 was the addition of dampening material:
To reduce these vibrations, additional dampening material was added to the instrument compartment prior to the remaining flight.
Another facet is revealed by looking at the timeline.
MA-1 took place July 29, 1960
MA-2 took place February 21, 1961
MA-3 took place April 25, 1961
MR-3 took place May 5, 1961
MR-4 took place July 21, 1961
MA-4 took place September 13, 1961
MA-5 took place November 29, 1961
MA-6 finally took place February 20, 1962
By the time the suborbital flights were done, the Mercury-Atlas was not ready, making an orbital mission impossible at that time.
A:
Rocket reliability was a big factor. The first 2 flights were on the Redstone, which didn't have the power to launch to orbit, for that they needed the Atlas. The Atlas had many failures in testing, the unmanned Mercury-Atlas (MA) tests were as follows:
MA-1: Structural failure less than a minute in
MA-2: Success
MA-3: Failure on guidance
MA-4: Success
MA-5: Success (Unmanned but had a chimp named Enos on board)
There were also many non-Mercury, mostly ICBM tests which were failures as well including pad explosions and in-flight breakups. They needed a couple of successes before they were able to trust it with a human, and it still was considered a risky flight.
The other reason was that some doctors were concerned that the impact of weightlessness could render a human unable to function, or even kill them, so they wanted to send a primate to study first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating SQL triggers for full text search index in SQLite
I'm trying to create triggers for a regular table to then update a full text index in SQLite, but I'm getting some errors and I'm not sure where I've gone wrong.
The app I'm making is a bookmarking app and the database I save the bookmark data to is created using the following SQL statement:
create table "pages" (
"pageUrl" text not null unique on conflict replace,
"dateCreated" integer not null,
"pageDomain" text not null,
"pageTitle" text null,
"pageText" text null,
"pageDescription" text null,
"archiveLink" text null,
"safeBrowsing" text null,
primary key ("pageUrl")
);
Then the full text search index is created with:
create virtual table fts using fts5(
content='pages',
content_rowid='pageUrl',
pageDomain,
pageTitle,
pageText,
pageDescription
);
So then I'd like to update the fts index when the "pages" table is updated via an insert or a delete.
The trigger I have for insert:
create trigger afterPagesInsert after insert on pages begin
insert into fts(
rowid,
pageDomain,
pageTitle,
pageText,
pageDescription
)
values(
new.pageUrl,
new.pageDomain,
new.pageTitle,
new.pageText,
new.pageDescription
);
end;
The trigger I have for the delete:
create trigger afterPagesDelete after delete on pages begin
insert into fts(
fts,
rowid,
pageDomain,
pageTitle,
pageText,
pageDescription
)
values(
'delete',
old.pageUrl,
old.pageDomain,
old.pageTitle,
old.pageText,
old.pageDescription
);
end;
Here's an example of an sql insert statement I'm using:
insert into "pages" (
"pageUrl",
"dateCreated",
"pageDomain",
"pageTitle",
"pageText",
"pageDescription",
"archiveLink",
"safeBrowsing"
)
values(
'https://www.reddit.com/',
1456465040177,
'reddit.com',
'reddit: the front page of the internet',
'reddit: the front page of the internet',
'reddit: the front page of the internet',
NULL,
NULL
)
And the delete statement:
delete from "pages" where "pageUrl" = 'https://www.reddit.com/'
But, I'm getting an error of SQLITE_MISMATCH: datatype mismatch] errno: 20, code: 'SQLITE_MISMATCH' for both the insert and the delete trigger, which I guess seems to indicate that the wrong data is going in to the wrong column, but I'm not sure why. I've gone through the triggers section in the External Content Tables section in the docs here and I've followed what was listed, so I'm not sure where I'm going wrong.
Any help would be appreciated.
note: I'm using the fts5 version of the SQLite full text search: https://www.sqlite.org/fts5.html
A:
The content_rowid must refer to the rowid of the actual table, i.e., the INTEGER PRIMARY KEY column.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Different Custom Fields in Vaadin Table
I've a vaadin table backed by CrudBeanItemContainer:
CrudBeanItemContainer<MyBean> beanItemContainer = new CrudBeanItemContainer<MyBean>(
MyBean.class, getTableFields());
for (MyBean bean : beanCollection) {
beanItemContainer.addBean(bean);
}
table.setContainerDataSource(beanItemContainer);
MyBean has 3 fields:
public class ProcessInstanceVariable {
private String name;
private Object value;
private VariableType variableType;
...
}
VariableType stores the type of value: Integer, Date, String, Boolean etc.
I'm listing MyBeans in the table. I want user to be able to edit the value on the table. For that, I need to add a field to Value column, it can be DateField, CheckBox etc. according to VariableType.
I've tried this:
Collection<?> itemIds = getTable().getItemIds();
for (Object itemId : itemIds) {
Item item = getTable().getItem(itemId);
Property value = item.getItemProperty("value");
MyBean myBean = (MyBean) itemId;
Property property = getField(myBean);
boolean isRemoved = item.removeItemProperty("value");
boolean isAdded = item.addItemProperty("value", property);
}
getField method returns the required field(CheckBox, DateField...).
Although, isRemoved and isAdded is true, I don't see the field in the table.
How can I add the field w.r.t. the VariableType inside MyBean?
A:
Try generateCell():
table.addGeneratedColumn("ColumnName", new ColumnGenerator() {
@Override
public Object generateCell(Table source, final Object itemId, Object columnId) {
Class class = source.getItem(itemId).getItemProperty("variableType").getType();
if (class == Boolean.class){
CheckBox chk = new CheckBox(null);
...
return chk;
} else if (class == String.class){
TextArea text = new TextArea(null);
...
return text;
}
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bizzare nullref in C++
I have a small piece of C++ code that is making me insane. Whenever it runs, it throws a null reference exception in a very unexpected place.
void CSoundHandle::SetTarget(CSound* sound)
{
assert(_Target == nullptr);
if (sound == nullptr) { return; }
_Target = sound;
// This works just fine.
_Target->Play();
// This is the code that throws the exception. It doesn't seem possible, as
// we should not be able to get here if 'sound' is null.
_Target->Stop();
}
So what the heck is going on? The message in the output window is:
this->_Target-> was nullptr.
0xC0000005: Access violation reading location 0x00000014
I have confirmed in disassembly that it is not taking place inside of the Stop function as well. How is this possible?
EDIT:
The pointer for sound is indeed initialized, and 'this' and 'this->Target' are non-null.
EDIT 2:
I have somehow solved the problem by slightly changing the declaration of the Stop function:
// From this.
virtual void Stop();
// To this.
void Stop();
This seems especially odd since Play() is also virtual, but works without any trouble. I can't say I've ever seen anything like this before. There are no other functions named 'Stop' in the rest of the program, nor are there subclasses of CSound, so I'm a bit confused.
A:
Reading location 0x00000014 implies you're trying to access a field located 0x14 bytes from the beginning of an object. The pointer to that object is set to null. So the problem is in the caller of your function: it passes a bad pointer to sound, which is neither null nor valid. This is why the null check in your function passes (0x14 isn't null), but you still crash.
Update:
The second edit to the question indicates the problem is in calling a virtual function. The null here is the virtual pointer then, and 0x14 is the offset of the Stop virtual function. The virtual pointer is set (in code generated by the compiler) during object construction, and should never point to 0. If it does, some part of the program is corrupting the object. An easy to detect case would be an attempt to reset the object, but memory corruptions (e.g., out-of-bound write to an array) could also cause this issue.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add Fontawesome 5 to Symfony 4 using Webpack Encore
I want to add Font Awesome 5 to my Symfony 4 project, this is what I did :
I added font awesome to my project using yarn : yarn add --dev @fortawesome/fontawesome-free
I imported font awesome in my main scss file (assets/css/app.scss) :
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
my webpack encore configuration include my scss and js files :
.addEntry('js/app', './assets/js/app.js')
.addStyleEntry('css/app', './assets/css/app.scss')
I compiled :
./node_modules/.bin/encore dev
Everything seems ok, but when I try to use font awesome in my view I only get a square icon instead. The generated app.css file seems ok as I can see the font awesome icons definitions, for example :
.fa-sign-out-alt:before {
content: "\F2F5";
}
It just seems that the 'content' part is missing, I guess because the fonts are not loaded... Do I need to add something to load the webfonts? I tried to add the font awesome js in my app.js asset file but it doesn't change anything.
I also tried to add custom loaders to my webpack encore configuration (like this https://github.com/shakacode/font-awesome-loader/blob/master/docs/usage-webpack2.md#setup-for-webpack-2)
I also tried to clear the cache, same result...
Any idea?
A:
According font-awesome docs here, after install package
yarn add --dev @fortawesome/fontawesome-free
or
npm install --save-dev @fortawesome/fontawesome-free
Require font-awesome into your config file (in my case and default Symfony 4 location) assets/js/app.js:
require('@fortawesome/fontawesome-free/css/all.min.css');
require('@fortawesome/fontawesome-free/js/all.js');
Compile again yarn encore dev and icons should appear.
A:
Adding @import '~@fortawesome/fontawesome-free/scss/fontawesome'; is not enough. You need to add one (or any combination) of these files (depend on your use-case)
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/brands';
A:
The following as above works perfectly for me:
npm install @fortawesome/fontawesome-free @fortawesome/free-brands-svg-icons @fortawesome/free-regular-svg-icons @fortawesome/free-solid-svg-icons -D
Add the following into a .scss file
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/brands';
works with webpack 4
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: 'url-loader?limit=10000',
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader',
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [
'file-loader?name=images/[name].[ext]',
'image-webpack-loader?bypassOnDebug'
]
}]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What exactly does "semantically observable" side-effect mean?
I have question regarding pure functions. According to the Wikipedia page one of the requisites for a pure function is :
Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.
Now what does this really mean. Or rather how can i make a side effect which is not semantically observable?
A:
A semantics of a program is a model of its behavior which, like any scientific model, ignores aspects that you don't want to study.
An extremely detailed model of the execution of a program would model the physical behavior of the computer that executes it, including the execution time, power consumption, electromagnetic radiation, etc. Such aspects are very rarely taken into account because they are very rarely relevant. Nonetheless they do matter sometimes: a useful model of an airplane autopilot needs to include runtime information, a useful model of a credit card's security needs to include electromagnetic radiation, ...
In typical semantics, side effects such as timing and power consumption are ignored. Even if in a mundane setting where you type an expression at a Haskell interpreter prompt, the printing of the result is a side effect (if you try to print out an infinite object, it matters). If the Haskell interpreter runs out of memory, this is also an observable side effect in a “real-world” model, but not in an idealized model of Haskell that effectively allows unbounded computations.
An observable side effect is one which is modeled in the semantics. In typical models of programming languages, memory consumption is not modeled, so a computation that requires 1TB of storage can be pure, even though if you try to run it on your PC it would observably fail.
Another kind of non-observable side effect is one that is internal to the function. This is, I think, what most semanticists would think of when talking about non-observable side effects. Consider a computation that uses mutable data internally, but does not share this mutable data with any other part of the program. For example, a list sorting function which builds an array with the same elements as the list, sorts the array in place, and returns a list containing the elements as the array in their final order: a semantic model of subexpressions of this function exhibits side effects (modifications of the array), but the function itself has no external side effect, so it is pure.
For a more subtle example, consider a function that writes some data to a temporary file and cleans up after itself. In a semantics where there is always enough room for temporary files and programs do not share temporary files, the function has no side effect; the temporary file acts as extra memory used by the function. In a semantics which takes filesystem full conditions into account, the function has a side effect — it may fail due to external circumstances. In a semantics that allows the machine to crash, the function has a side effect: if there is a crash during the execution of the function, the temporary file may be left behind. In a semantics that allows concurrently executed programs to see and maybe modify the temporary file, the function has a side effect.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to upload video or image file using keycdn in php
I'm using core php, I have also created a pull and push zone in keycdn account. My problem is I need to be able to upload a video or image file to a specified zone but I do not know how to do this?
now how to add my file in specific zone that i have created..
Thank you in advance..
A:
I think you should achieve your goal via this trick.
Directly not any method available but via ftp using PHP it is possible.
<?php
function uploadFTP($server, $username, $password, $local_file, $remote_file){
// connect to server
$connection = ftp_connect($server);
// login
if (@ftp_login($connection, $username, $password)){
// successfully connected
}else{
return false;
}
ftp_put($connection, $remote_file, $local_file, FTP_BINARY);
ftp_close($connection);
return true;
}
uploadFTP("ftp.keycdn.com", "yourusername", "yourpassword", "test.jpg", "/cdn/test.jpg");
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Stop React "onClick" event in the middle of DOM tree
Image this structure:
<Item onClick={goToPage}>
<p>Example Title</p>
<div> // addition
<Menu>
<button onClick={toggleMenuItems}/>
<MenuItems />
</Menu>
</div>
</Item>
Menu component itself has an event handling logic: it is listening to click events on window and closes menu items. This is done because one page can have many menus, and opening one should close all others.
The whole parent Item component must also be clickable. A div inside the Item component (marked as "addition") must be independent - so it can be a menu, but can also be anything else - just a text e.g.
The problem here is that clicking on Menu's button click event is being bubbled to Item and down the line, though Item's onClick is also fired. If propagation is stopped inside the Menu' onClick - then Item's onClick is not fired anymore but also window.onClick is stopped too, and other menus cannot be then closed.
What would be a solution to this? How could I stop on onClick for Item but not anything else down the line?
A:
To solve the issue I had to stop bubbling when Menu button (or any other area within Menu component) is clicked, and use capturing instead of bubbling inside the Menu to do "close menu on window click outside of component".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to access a nested type from a variable of unknown type?
How to get member type of the class of a variable of unknown type? What should be instead of type_of.
auto v = get_container();
type_of(v)::value_type x;
For maintainability reasons I would like to use auto, so that if get_container's return type is changed nothing will break.
A:
I have the impression that you are looking for:
decltype(v)::value_type x;
decltype is a very powerful tool from C++11. Have a look at its documentation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AVQueuePlayer/AVPlayer loading notification?
I have an AVQueuePlayer (which obviously extends AVPlayer) that loads a playlist of streaming audio. Streaming is all working fine, but I'd like to have an activity indicator to show the user audio is loading. Trouble is, I can't seem to find any such Notification in AVQueuePlayer (or AVPlayer) that would indicate when the audio buffer has finished loading/is ready to play (nor does there appear to be a delegate method). Any thoughts?
A:
You will have to use KVO to get this done.
For each item you are adding to the queue, you may setup observers like this:
item_ = [[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://somefunkyurl"]] retain];
[item_ addObserver:self forKeyPath:@"status" options:0 context:nil];
[item_ addObserver:self forKeyPath:@"playbackBufferEmpty" options:0 context:nil];
Now you can evaluate the status of that item within the observer method;
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([object isKindOfClass:[AVPlayerItem class]])
{
AVPlayerItem *item = (AVPlayerItem *)object;
//playerItem status value changed?
if ([keyPath isEqualToString:@"status"])
{ //yes->check it...
switch(item.status)
{
case AVPlayerItemStatusFailed:
NSLog(@"player item status failed");
break;
case AVPlayerItemStatusReadyToPlay:
NSLog(@"player item status is ready to play");
break;
case AVPlayerItemStatusUnknown:
NSLog(@"player item status is unknown");
break;
}
}
else if ([keyPath isEqualToString:@"playbackBufferEmpty"])
{
if (item.playbackBufferEmpty)
{
NSLog(@"player item playback buffer is empty");
}
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Symbol or abbreviation for a particle?
Not sure if this is a silly question, but: is there a standardised symbol or abbreviation that can be used in formal definitions to refer to particles?
Writing "PARTICLE" or "PART" sounds...silly...
A:
In interlinear glosses, I think PTC or PTCL are most commonly used to abbreviate "particle".
PRT or PART are sometimes used too, but should rather be avoided due to confusion with "preterite" and "participle", respectively.
But the name actually doesn't matter that much given that you provide a list of the abbreviations that you used with their intended meaning (which is always good practice to do because of the lack of a definite universal standardisation).
In formal definitions, I generally wouldn't use abbreviations but always terminology as precise as possible.
For further reference:
Leipzig Glossing Rules – probably the most standard-like
Extension of the Leipzig Glossing rules (I didn't compare it in much detail, but the original Leipzig rules don't include an abbreviation for "particle")
List of glossing abbreviations on Wikipedia
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Performance with Entity Framework Code-First
We have a performance problem with EF (Entity Framework). The first screen that calls EF takes much more time to open than the second one. There is no difference in the loading time if the second screen is the same as the first or a completely different one; all other screens will be fast.
We use the Code First API to create a ‘database First’ version of EF. To do this, we use T4 Templates to generate our entities class from the database table. One class is created by table. They are mapped in ‘OnModelCreating()’ We decided to go this way because we needed to separate our entity in three different layers (namespaces and assemblies):
Common Framework
Project Framework
Project Sector
The entities of each of these layers need to be linked to other entities in the previous layers. We tried to use edmx files but we did not find how to put the entities in different namespaces in the same edmx.
We also generate additional classes that are linked to the entities class. Presently, with our T4 Template we generate additional classes that the programmer can use to extend the entities property or to add validation.
The generated entities are the classes that the T4 Template creates with properties for every table column. The Entities is a class that extends the generated class where the programmer can add code. This is the class that is mapped to the table. The validator class is called when the other classes are modified or when the data is saved to database.
We need to find a way to pre-generate our view with code first or to have the same flexibility of code first with the edmx.
Example:
ParameterBase.Generated.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
using Keops.Common.Data;
using Keops.Common.Validation;
using Keops.Common.Validators.Framework;
namespace Keops.Common.Entities.Framework
{
public abstract class ParameterBase
: EntityBase
, IHaveAValidator
, IDatabaseOriginAware
{
protected ParameterBase()
{
ParameterValueList = new HashSet<ParameterValue>();
Validator = new ParameterValidator((Parameter)this);
}
#region Database columns
public string Code
{
get { return _code; }
set
{
if (_code != value)
{
_code = value;
RaisePropertyChanged("Code");
}
}
}
private string _code;
public bool IsEditable
{
get { return _isEditable; }
set
{
if (_isEditable != value)
{
_isEditable = value;
RaisePropertyChanged("IsEditable");
}
}
}
private bool _isEditable;
public bool IsVisible
{
get { return _isVisible; }
set
{
if (_isVisible != value)
{
_isVisible = value;
RaisePropertyChanged("IsVisible");
}
}
}
private bool _isVisible;
public int ParameterID
{
get { return _parameterID; }
set
{
if (_parameterID != value)
{
_parameterID = value;
RaisePropertyChanged("ParameterID");
}
}
}
private int _parameterID;
public int ValueTypeID
{
get { return _valueTypeID; }
set
{
if (_valueTypeID != value)
{
_valueTypeID = value;
RaisePropertyChanged("ValueTypeID");
}
}
}
private int _valueTypeID;
public string Name
{
get { return _name; }
set
{
if (_name!= value)
{
_ name = value;
RaisePropertyChanged("Name ");
}
}
}
private string _ name;
#endregion Database columns
#region Navigation parents
[ForeignKey("ValueTypeID")]
public ValueType ValueType
{
get { return _valueType; }
set
{
if (_valueType != value)
{
_valueType = value;
ValueTypeID = value == null
? 0
: value.ValueTypeID;
RaisePropertyChanged("ValueType");
}
}
}
private ValueType _valueType;
#endregion Navigation parents
#region Navigation children
public virtual ICollection<ParameterValue> ParameterValueList { get; set; }
#endregion Navigation children
#region IHaveAValidator
public ValidatorBase<Parameter> Validator { get; private set; }
IValidator IHaveAValidator.Validator
{
get { return Validator; }
}
#endregion
#region IDatabaseOriginAware
public bool IsFromDatabase { get; set; }
string IDatabaseOriginAware.FullTableName { get { return "Framework.Parameter"; } }
#endregion
}
}
Parameter.cs
namespace Keops.Common.Entities.Framework
{
public class Parameter : Parameter Base
{
//Add custom methods here
}
}
ParameterValidatorBase.Generated.cs
using System;
using System.Data.Entity;
using System.Linq.Expressions;
using Keops.Common.Entities.System;
using Keops.Common.Validation;
namespace Keops.Common.Validators.System
{
public abstract class ParameterValidatorBase : ValidatorBase<Parameter>
{
private readonly Parameter _entity;
protected ParameterValidatorBase(Parameter entity)
: base(entity)
{
_entity = entity;
}
protected ParameterEntity { get { return _entity; } }
}
}
ParameterValidator.cs
using Keops.Common.Entities.System;
namespace Keops.Common.Validators.System
{
public class ParameterValidator : ParameterValidatorBase
{
internal ParameterValidator(Parameter entity)
: base(entity)
{
}
//Define custom rules here
}
}
A:
After more research, we found a blog post from Pawel Kadluczka:
Entity Framework Code First View Generation Templates On Visual Studio Code Gallery
He created a T4 Template that can be used to generate view from Code First.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding a dependency to an EJB
I want to add a dependency to an EJB. How do I do this using Spring? The dependent object is a general service object. Based on code below I want to wire myDependency without having to use 'new'.
The EJB runs in weblogic.
@Stateless(mappedName = "MyBean")
public class MyBean implements MyBeanRemote, MyBeanLocal {
@EJB(name = "MyOtherBean")
private MyOtherBean myOtherBean;
private MyDependency myDependency;
...
}
A:
This is well described in the Spring documentation:
For EJB 3 Session Beans and Message-Driven Beans, Spring provides a
convenient interceptor that resolves Spring 2.5's @Autowired
annotation in the EJB component class:
org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.
This interceptor can be applied through an @Interceptors annotation in
the EJB component class, or through an interceptor-binding XML element
in the EJB deployment descriptor.
@Stateless
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class MyFacadeEJB implements MyFacadeLocal {
// automatically injected with a matching Spring bean
@Autowired
private MyComponent myComp;
// for business method, delegate to POJO service impl.
public String myFacadeMethod(...) {
return myComp.myMethod(...);
}
...
}
Stateless EJBs and Spring beans, however, offer more or less the same possibilities. Mixing them together seems like unnecessary complexity.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding "this" reference to Array fails in Java Constructor
I am absolute clueless why the following code keeps throwing NullpointerExceptions. I was not able to understand or debug this (its stripped down code from a larger class)...
The code is based on the "Enum Pattern" and I want to keep a List/Map of all "Constants" that are contained in the class (I might be using Reflection for this but using a List/Map is much easier...)
public class Country {
public static final Country SWITZERLAND = new Country("SWITZERLAND");
private static ArrayList<Country> countries = new ArrayList<Country>();
private Country(String constname) {
//constname is currently not used (I will use it for a Key in a Map)
System.out.println(constname);
System.out.println("Ref debug:"+this);
//Ad this to the Countries
Country.countries.add(this);
}
}
Help would be very much appreciated. What am I missing here?
A:
SWITZERLAND, being static, is potentially initialized before countries, which is also static. Therefore, countries is still null in the constructor call of SWITZERLAND.
To force a well-defined order of initialization, use a static block:
public class Country {
public static final Country SWITZERLAND;
private static ArrayList<Country> countries;
static {
countries = new ArrayList<Country>();
SWITZERLAND = new Country("SWITZERLAND");
}
}
A:
To expand on what Konrad said, the static variable initializers are executed in textual order (as specified in JLS section 8.7). If you put the ArrayList first, it will work:
public class Country {
private static ArrayList<Country> countries = new ArrayList<Country>();
public static final Country SWITZERLAND = new Country("SWITZERLAND");
...
Konrad's suggestion of using a static constructor to keep the order clearly specified is a good one though.
Are you using Java "pre 1.5"? If not, use a straight enum...
A:
Because I think this deserves more than the cursory mention Jon gave it:
The "typesafe enum pattern" is obsolete!
Unless you are forced to use an ancient Java version (pre 1.5, which isn't even supported anymore by Sun), you should use Java's real Enums, which save you a lot of work and hassles (because old-style typesafe enums are very hard to get right) and are just all around awesome.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does stoppage time actually equal all non-playing time during a half?
After every half during a football (soccer) game, the refs add stoppage time to the clock to compensate for lost time due to injuries and penalties.
But how closely does stoppage time equal real game time lost? (Are there different stoppage time calculations for different leagues?)
And if it's nearly exact, then what's the logic in delaying or faking injuries, as players on a winning team are often accused of doing. Wouldn't that delay just be tacked on at the end of a game or half?
A:
From FIFA:Allowance for time lost
The fourth official indicates the minimum additional time decided by the referee at the end of the final minute of each period of play.
The announcement of the additional time does not indicate the exact amount
of time left in the match. The time may be increased if the referee considers it
appropriate but never reduced.
The referee must not compensate for a timekeeping error during the first half
by increasing or reducing the length of the second half.
Also, Allowance is made in either period for all time lost through:
substitutions
assessment of injury to players
removal of injured players from the field of play for treatment
wasting time
any other cause
A:
SahuKahn has correctly pointed out that additional time is added on for substitutions, assessment of injury to players, removal of injured players from the field of play for treatment, wasting time and any other cause (which seems like an overly liberal "catch-all" clause!?). The relevant reference is on page 29 of the 2014/15 FIFA Laws of The Game.
Generally, as seen in Les Arbitres, this is a rough estimate rather than an exact calculation (I can't remember which match it is in the documentary, but at the end of one of the matches, there is a conversation between the referee and fourth official in which the referee says "one minute will do" or similar).
Unlike many other sports, such as ice hockey and futsal, the clock is not stopped whenever the ball is out of play. The ball ends up being in play for 60 - 70 minutes (on average) in top-flight professional leagues. [1][2]
Since the referee will should add on all time lost by time wasting, the advantage is not necessarily in soaking up playing time, but in breaking the attacking rhythm of the opponents. Also, delaying the restart can also give enough time for defenders to get back and cover, especially if a foul is committed when there is a tactical advantage and the attacking team wants to take a quick free kick.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the effect "Blood oozes from you" on a Blood-Magic Blade?
The Blood-Magic Blade is a craftable level 60 legendary dagger. After the revamp of 1.0.4 legendaries, a new effect, described as "blood oozes from you" was added to the item description.
Given that the dagger looks like it still has incredibly low damage for a level 60 legendary, the only possible saving grace I could think of for this item is the effect. However, I can't find any details of what it actually does.
What does "blood ooz[ing] from you" actually do?
A:
As everybody said, it's just pure visual effect.
Just purchased a cheap one from AH and tested it a bit. You don't bleed, you lose no health, you don't hold the dagger by the blade. All what Blood oozes from you does is purely visual effect that also leaves some (very)tiny blood spots on the ground for a short period of time.
Here are a few screenshots:
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.