text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Selecting the next available number in a row
If i have a database like this one
[ id - post - num ]
[ 1 P1 1 ]
[ 2 P2 2 ]
[ 3 P3 3 ]
[ 4 P4 5 ]
[ 5 P5 7 ]
Now i have a code like this
$max_number = 7; // AFTER QUERY
$current_number = $_GET['num']; // = 1
if($current_number < $max_number){
echo "<a href='#'>The {$current_number++} in rating Post</a>";
}
the problem in this code that if the topic number is 3 and clicked it would give me number 4 which doesn't exist, Is there a possible way to do it better? using array if possible.
A:
A solution could be (in sql, you will have to implement it):
SELECT MIN(num) FROM tab WHERE num>$current_number;
This would give you your previous ($current_number++) value.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Perl: After merging text files into 1 file won't read the whole file
The code below puts text files given from the command line and puts them in a merged.txt file. This part makes a perfect copy with the correct amount of lines. My problem is that when trying to use the file for example with while(file) it doesn't go through every line. For example merged.txt will have 735 lines as counted by vim but numlines will only have 732.
my @file = map { open my $f, $_ or die "Can't Open $_:$!"; $f } @ARGV;
open my $out_file, ">merged.txt" or die "Can't Open out_file $!";
my $output;
do {
$output ='';
foreach(@file) {
my $line = <$_>;
if(defined $line) {
if($line !~/\n$/) {
$line .= "\n";
}
$output .= $line;
}
}
print {$out_file} $output;
}
while ($output ne '');
my $numlines =0;
open my $file, '<', 'merged.txt' or die "Could not open file 'merged.txt' $0";
while(<$file>) {
$numlines++;
}
A:
You got the answer, to close the file you wrote before opening it for reading.† Another way to have that happen is to use the same filehandle, which does get closed as it's being opened again. So
my $file = 'merged.txt';
open my $out_file, '>', $file or die ...
...
open $out_file, '<', $file or die "Can't open $file: $!";
if you are done writing by then.
Note that you want the variable $! (not $0, the name of the script).
I'd like to also mention that if your filenames are in @ARGV you can use the special <>
my $output;
$output .= $_ while <>;
or, if you don't need all merged content in a variable
open my $fh_out, '>', $file or die "Can't open $file: $!";
print $fh_out $_ while <>;
close $fh_out;
The <> is a synonym for the magical <ARGV>. It reads all lines from all files in @ARGV, but please see more in the linked documentation.
† Working with a file which is opened elsewhere can badly confuse things unless one is very careful. One way to keep it straight is by using seek
Due to the rules and rigors of ANSI C, on some systems you have to do a seek whenever you switch between reading and writing.
so
open my $out_file, '>', $file or die ...
...
seek $out_file, 0, 0;
and after this the reads should work correctly (you should get the correct line count).
While this is a little more efficient it is error prone and tricky. Unless there is a demonstrated need for seek-ing around a file I'd recommend just to re-open the file for reading after writing is done.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mountain bike tires
Would be safe to drive my mountain bike with little cracks on the tire?please help I will used it for university. Do I have to replace my tires?
A:
Looks harmless.
A tire gets its strength from the cloth casing (“carcass”). The rubber tread is mainly there for grip and durability. It also provides some puncture protection.
Cracks in the rubber usually form due to age (+exposure to the elements) and/or insufficient tire pressure.
My main concern would be that if the rubber is old and hard your grip will be worse, especially on wet surfaces.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Verb [will] -- in [Door won't budge] and [Husband won't budge] -- same meaning?
1B. Battery won't hold a charge.
1N. Noise from the device won't stop.
2D. [ Door is stuck and won't budge. ]
2H. [ Husband stuck on name and won't budge! ] --- (Baby Name Game)
For the auxiliary verb [will], three dictionaries I checked all have separate entries for
(P). -- A person desiring or wishing something, and
(Obj). -- An inanimate object having capability --- [the back seat will hold three passengers]
I believe that there is no difference between these two meanings (P) and (Obj), which you can confirm by trying to assign these two meanings to the 4 examples at the top.
(You will eliminate by deduction, [futurity] and other meanings.)
What do you think?
The (Obj) meaning in the 3 dictionaries :
http://www.merriam-webster.com/dictionary/will
4 —used to express capability or sufficiency ---- [the back seat will hold three passengers]
https://en.wiktionary.org/wiki/will
6. (auxiliary) To be able to, to have the capacity to. [from 14th c.] ---- [ Unfortunately, only one of these gloves will actually fit over my hand. ]
http://www.dictionary.com/browse/will
am (is, are, etc.) capable of; can: [ This tree will live without water for three months.]
used as an auxiliary to express capacity or ability: [this rope will support a load]
A:
You have submitted a lengthy question, but what it boils down to is, in door won't budge and husband won't budge, whether the won't (short for will not), in each case, has the same meaning.
All I would say is that we often ascribe human volition, not only with will, to inanimate things e.g. the car won't start, my computer has lost all its memory, my oven keeps bleeping at me etc.
One might also argue that the volitional will is actually only the future will in disguise. Isn't the door will not open only short for if you push it, it will not open (future tense).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Limit fixed div vertical scrolling
I have 2-columns layout with fixed sidebar on the left and page content on the right column. I also have the footer. I want my fixed sidebar to scroll right to the coordinates of the end of the page content div.
However, if the height of sidebar is bigger than the height of page content, I need to automatically assign new height to the page content div. This code works for the first case (Content higher than sidebar), but the second case works only if I reload page one more time (when, for example, I go to this kind of page from another page, script doesn't assign new height, but when I reload page, it does)
here is the code:
$(window).load(function(){
var windw = this;
var contentHeight = $('#content').height(); // fetch Сontent div height
var sideHeight = $('.sidebar-nav-fixed').height(); // fetch sidebar div height
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(windw);
$window.scroll(function(e){
if ($window.scrollTop() >= pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 100
});
}
});
};
if (sideHeight > contentHeight) {
$('#content').css ({
height: contentHeight + (sideHeight - contentHeight)
}),
contentHeight = $('#content').height() // Assign a new height to page content div
}
$('.sidebar-nav-fixed').followTo(contentHeight - sideHeight);
});
I will be really glad if you have any ideas
Thanks!
A:
Looks like I resolved this problem.
In my sidebar I had facebook widget which loads dynamically, so when I open the page, script fetches height without Facebook div height, as it has not loaded yet. I just made few manipulations to load scroll script after facebook widget is loaded.
Or even the better way - to put this widget into container and specify height for it manually in css.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the idea behind Kotlin removing checked exceptions?
And how do we handle this when we are calling a method in Java which throws exceptions ?
my code is in kotlin and I am using a 3rd party library which is written in java. I call a method of this library which throws few custom exceptions in some cases. Now kotlin doesn't enforce me to handle this exceptions and in which case application would crash. What's the best way to handle this ?
A:
When Java introduced checked exceptions — where the compiler enforces that most exceptions are either caught or declared to be thrown — it was a fairly new idea. Java was a much safer language than most of its predecessors: all behaviour defined and consistent across all platforms, and many features intended to prevent crashes, unexpected behaviour, or fragile coding. So checked exceptions fitted in well with the language's philosophy.
But in the years since, many people have come to the conclusion that checked exceptions were a mistake. I'm not totally convinced, but here are some of the reasons:
They're verbose. It's common for methods to include many try…catch blocks, and/or to declare many exceptions. Also, if there are 6 levels of method call between where an exception is thrown and where it's caught, the exception will need to be declared by 5 methods.
Kotlin does away with much of Java's boilerplate, and doing away with checked exceptions fits in with that.
They encourage bad practices:
Trying to handle exceptions in the wrong place, i.e. at the wrong level of abstraction, where nothing useful can be done.
Pointless catch blocks (especially dangerous ones which do nothing but logging the error).
Catching/declaring Exception instead of the specific subtypes.
Cheating by wrapping checked exceptions in unchecked ones such as RuntimeException.
They increase coupling between modules. If you're using a library method which adds a new exception, then all code calling that method needs to be updated to handle or rethrow it.
They require exceptions to be translated between different levels of abstraction. (For example, a DB-access layer might have to convert a socket-timeout exception into a database-unavailable exception.) This is tedious, but necessary to avoid exposing implementation details.
They don't work well with inheritance. If the method you're implementing/overriding isn't declared to throw a particular checked exception, then your implementation can't throw it either.
They don't work well with lambdas. In Java, lambdas are implemented using Single-Abstract-Method interfaces, and so those methods must either declare the possible exception (in which case every usage must handle or declare it), or the lambda body must catch the exception. Both options greatly increase the conceptual weight as well as the code needed to use lambdas, destroying the conciseness which is one of their main benefits.
Kotlin's implementation is fairly similar (though it uses its own KFunction interfaces), and would suffer the same problems.
With all these problems, it's clear that checked exceptions are a mixed blessing at best. And I can see why Kotlin has done away with them.
I do worry that it may result in programs that are less robust (and less well documented). But in the two years I've been using Kotlin, I haven't seen any obvious cases of this. So I'm holding off judgement for now :-)
(See also this question.)
As to how to handle your particular case, I suggest you do the same as you'd do if Kotlin had checked exceptions: see what exceptions the method you're calling can throw, work out how/where best to handle them, and handle them! Just because Kotlin isn't forcing you to do so, doesn't mean it's not still a good idea!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Obtaining a de-focus event other than from Stage - JavaFX
I have a piece of code much like this:
package blah;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextInputControl;
import javafx.stage.Stage;
public class SimpleExample {
TextInputControl textFieldForWork;
LocalTextChangeListener localTextChangeListener;
public SimpleExample(TextInputControl textFieldForWork, Stage s) {
this.textFieldForWork = textFieldForWork;
localTextChangeListener = new LocalTextChangeListener();
System.out.println("Creating new focus listener for TextField component");
LocalFocusListener localFocusListener = new LocalFocusListener();
s.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (observable.getValue().toString().equals("false")) {
System.out.println("Removing TextField focus listener");
textFieldForWork.focusedProperty().removeListener(localFocusListener);
} else {
System.out.println("Adding TextField focus listener");
textFieldForWork.focusedProperty().addListener(localFocusListener);
}
}
});
}
private class LocalFocusListener implements ChangeListener {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if (observable.getValue().toString().equals("true")) {
System.out.println("Adding text change listener");
textFieldForWork.textProperty().addListener(localTextChangeListener);
} else {
System.out.println("Removing text change listener");
textFieldForWork.textProperty().removeListener(localTextChangeListener);
}
}
}
private class LocalTextChangeListener implements ChangeListener {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
System.out.println("Textfield changed - do processing");
}
}}
The purpose of this code is to fire a listener each time the user types something in the textfield. The other necessary function of this code, is that upon dialog defocus, the textfield listeners should be removed.
Any help appreciated!
A:
I'm not sure I really understand why you need to observe the focused property of the stage. Can't you just register the listener with the text field once and leave it there? It won't be invoked unless the text changes.
If you really need the functionality you describe, you can do it. Here's a description of what's going on:
The focusedProperty of the text field tracks whether or not the Node with focus within the current scene graph is the text field. It is "local to the scene graph", which means it is independent of whether or not the window is the active or focused window.
The focusedProperty of the window tracks whether or not the window has focus. This changes if you move the application to the background, etc.
Obviously, at the point where you create the text field, is hasn't been added to a scene or window, so just doing
textFieldForWork.getScene().getWindow().focusedProperty().addListener(...)
won't work, because getScene() will return null at this point. Even if the scene is non-null, it might not yet belong to a window, so you may have getScene() non-null but getScene().getWindow() null at some point.
So what you actually want to do is observe the sequence of properties. Start with textFieldForWork.sceneProperty() and observe it; if it changes and is non-null, then observe textFieldForInput.getScene().windowProperty(); when that changes and is non-null, observe textFieldForInput.getScene().getWindow().focusedProperty().
You could handle this yourself, creating listeners for each step in the chain and adding and removing them as necessary, but the EasyBind framework has API that manages exactly this use case. Using EasyBind you can do
MonadicObservableValue<Boolean> stageFocused =
EasyBind.monadic(textFieldForWork.sceneProperty())
.flatMap(Scene::windowProperty)
.flatMap(Window::focusedProperty)
.orElse(false);
stageFocused.addListener((obs, wasFocused, isNowFocused) -> {
if (isNowFocused) {
// stage now has focus...
} else {
// stage has lost focus...
}
});
If you want to check the condition that the text field has focus and the window containing it has focus, you can do
BooleanBinding stageAndTextFieldFocused = Bindings.createBooleanBinding(() ->
stageFocused.get() && tf.isFocused(),
stageFocused, tf.focusedProperty());
with stageFocused as above. Then just do
stageAndTextFieldFocused.addListener((obs, wasFocused, isNowFocused) ->
{ /* etc ... */ });
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Animate with OpenGL, compute with CUDA
I've written a CUDA Random Walk simulation. I.e. I have two vectors X and Y containing the position of all the particles I simulate. During each timestep I update their position according to my computation.
/* Calculate velocity magnitude */
CURAND_CALL(curandGenerateNormal(gen, dev_v, Nrand,0,1.0));
/* Generate direction on device */
CURAND_CALL(curandGenerateUniform(gen, dev_alpha, Nrand));
/* X_t+1 = X_t + V */
scosaxpy<<<blocksPerGrid,threadsPerBlock>>>(Nrand,dev_alpha,dev_v,dev_x);
ssinaxpy<<<blocksPerGrid,threadsPerBlock>>>(Nrand,dev_alpha,dev_v,dev_y);
Where sscosaxpy() updates my position as x+=cos(alpha)*vx. My code is then structured as
/* initilize memory */
/* set up CURAND */
for(t=0;t<T;t++){
/* calculate velocity magnitude and direction */
/* update position */
/* eventually copy memory to host */
}
Now comes the part, where I have no background in. Visualizing with OpenGL. I have looked up some examples (NVIDIA also provides some examples for the interaction between CUDA and OpenGL), but most of them are either to complex, or don't handle the case where the computation is done by CUDA.
My Question: Can anybody give me the steps to visualize my output in the following way
for(t=0;t<T;t++){
/* calculate velocity magnitude and direction */
/* update position */
/* eventually copy memory to host */
/* Update the position of my particles in a 2D plot */
}
Could you provide a complete working example?
A:
There are many ways to do this in OpenGL. They vary on complexity and performance. Since you're using CUDA I believe that you'd like your visualization to run quite fast. This is a bit more complex than just rendering those points without thinking about performance. If you have no previous OpenGL experience i suggest using the most straightforward solution where you draw one point at the time. Take a look at this tutorial (It's just an example. You can try any tutorial that has a working code): http://openglsamples.sourceforge.net/triangle.html
Try to run it and see a triangle. Now find a display() function and see that the code responsible for drawing is placed between glBegin(GL_TRIANGLES); and glEnd();
You will need to modify it, since you don't want to draw triangles. Instead here's what you should do. After the CUDA step I'm expecting you to have an array of 3D points.
for(t=0;t<T;t++){
/* calculate velocity magnitude and direction */
/* update position */
/* eventually copy memory to host */
}
/* Now your points are stored in an array. Let's say float particles[T][3]; */
/* Update the position of my particles in a 2D plot */
display();
You should modify the display() part that I've already mentioned like that:
glBegin(GL_POINTS);
for(int t=0;i<T;t++)
{
glColor3f(1.0f,1.0f,1.0f); //In case you want to give them unique colors in future
glVertex3f( particles[t][0], particles[t][1], particles[t][2]);
}
glEnd();
Now you should see your particles. If the number T is relatively high the rendering may be slow, but just to picture where your particles are located it should be enough. Keep in mind, that positions of your particles have to be in the view angle of your camera which in that cas is located in point (0,0,3) and looks in the negative direction of Z axis having 45 degrees of view angle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to handle login between different domains?
I've a website with 2 domains (.nl and .com) and a translated version of the content is displayed depending on the domain.
My issue is that when a client login under a .nl domain, and he moves to the .com domain, he is not anymore logged in.
thanks
A:
This is essentially the same problem StackExchange had with 'global network auto-login'.
Here is what Jeff wrote on the blog about their implementation:
While subdomains such as chat.serverfault and meta.serverfault are easy if you store your cookies the right way, getting access to cookies at different domains is, to put it charitably, a friggin’ nightmare. The whole third party cookie story — that is, reading or writing cookies stored at a domain other than the one you’re currently on — is irreversibly screwed up, and getting worse with every new browser release, thanks mostly to unscrupulous ad networks.
So, we gave up on using third-party cookies. Instead, we use HTML 5 Local Storage for global authentication, at our centralized domain stackauth.com. Now, this does require a modern browser, though not unreasonably so: IE8+, Chrome, Safari, FireFox 3.6+, and Opera 10.61+ are all supported.
I'm assuming that the user is accessing your site via HTTP. If it is via HTTPS, you are out of luck, the user will have to log in again.
Overall however, I would urge you to design the site in such a manner that the user never has to move between top level domains. You could for instance replicate example.nl on nl.example.com and rely on the latter if the user is already logged in on example.com (and vica versa).
For SEO purposes you would probably want to disallow all crawling of nl.example.com
|
{
"pile_set_name": "StackExchange"
}
|
Q:
missing values,classification task
I am using this dataset breastcancer from UCI but it contains missing values. Can anyone help me to fix it? I am new to ML and I don't know a lot about missing values techniques. Here is the link for dataset cancerdata.
I tried this code on R :
data <- read.csv('D:/cancer.csv', header=FALSE) # Reading the data
for(i in 1:ncol(data)) {
data[is.na(data[,i]), i] <- mean(data[,i], na.rm=TRUE)
}
but it gives me an error (sorry it may be trivial but I am really pretty new
here is a screenshot of the
thank you for your time and consideration
here is the output I have
A:
Try the missForest package in R: https://cran.r-project.org/web/packages/missForest/missForest.pdf
It is really easy to use, fast and does a great job imputing categorical and numeric values.
For a quick tutorial, see here: https://www.analyticsvidhya.com/blog/2016/03/tutorial-powerful-packages-imputing-missing-values/
Edit:
You have total 16 missing values in the data, all in column 7 (V7). You can check this by
data <- read.csv('D:/cancer.csv', header=FALSE) # Reading the data
sum(data == "?")
sum(data$V7 == "?")
Now, missForest will impute all in NAs in data, no matter where they are. If you want to retain some NAs, separate that data first.
To impute all NAs:
data[data == "?"] <- NA
library(missForest)
data <- missForest(data)$ximp
Now all the NAs have been imputed and replaced with some meaningful values. To verify this:
sum(is.na(data))
Use this data with imputed values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Count how many pages are needed
How do I count how many pages my data needs to fit?
I got 23 rows of data and every page takes 20 rows = 2pages.
When I divide it, I get 1:
var pages = totalRows / 20;
When I use modulus, I get 3:
var pages = totalRows % 20;
So please explain to me what calculation I should use to resolve this issue.
A:
You should divide and then round up, which will account for a final page that has less than 20 rows.
var pages = (int)Math.Ceiling(totalRows / 20.0);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to call to the copy constructor from the copy-assignment operator?
I'm implementing a linked list. I wrote a copy constructor:
// --- copy constructor ---
IntList(const IntList& last_list) {
first = new IntNode(last_list.getFirst()->getData());
cout << "copy first " << first->getData() << endl;
IntNode* last_node = first;
IntNode* node = last_list.getFirst()->getNext();
while(node!=NULL) {
IntNode* new_node = new IntNode(node->getData());
last_node->setNext(new_node);
cout << "copy " << new_node->getData()<< endl;
last_node = new_node;
node = node->getNext();
}
}
As I understand, my copy-assignment operator (operator=) should have 2 goals:
delete the current list.
copy the new list.
I can achieve this 2 goals by calling the destructor which I already wrote and then call the copy constructor. How can I do it?
A:
For your copy assignment operator, you can use the copy-and-swap idiom.
For example in your case, you could add this into your IntList class definition (given the code of your copy constructor, I'm assuming that your only data member is IntNode* first;):
// --- swap non-member function ---
friend void swap(IntList& a, IntList& b) /* no-fail */ {
// swap data members one by one
std::swap(a.first, b.first);
}
// --- (copy) assignment operator ---
IntList& operator=(const IntList& other) {
IntList temp(other); // copy construction
swap(*this, temp); // swap
return *this;
// destruction of temp ("old *this")
}
Actually, this may be better style:
// --- swap non-member function ---
friend void swap(IntList& a, IntList& b) /* no-fail */ {
using std::swap; // enable ADL
// swap data members one by one
swap(a.first, b.first);
}
// --- (copy) assignment operator ---
IntList& operator=(IntList other) { // note: take by value
swap(*this, other);
return *this;
}
The /* no-fail */ comment can be replaced with throw() (or maybe just a /* throw() */ comment) in C++98/03, noexcept in C++11.
(Note: Don't forget to beforehand include the right header for std::swap, that is, <algorithm> in C++98/03, <utility> in C++11 (you can as well include both).)
Remark: Here the swap function is defined in the class body but it is nevertheless a non-member function because it is a friend.
See the linked post for the whole story.
(Of course, you must also provide a correct destructor definition in addition to your copy constructor (see What is The Rule of Three?).)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rearranging equation with division using Maxima
I'm trying to rearrange equation using maxima, but coefmatrix function does not work well with equation that has some division such as RL_parallel
I am getting all zeroes for the coefficients
RL_series: Rs + %i*w*Ls;
RL_parallel: ratsimp( 1 / [1/Rp + 1/(%i*w*Lp)] );
display2d : false $
eq : RL_series = RL_parallel $
vars : [Rs, Rp, Ls, Lp] $
coeffs : coefmatrix ([eq], vars);
coeffs . vars;
A:
The main problem here is that the equation isn't linear in the variables specified, so extracting a coefficient matrix doesn't make any sense, unfortunately.
I am guessing that you want to solve the equation for vars. It seems to me that you'll need additional data, but it could well be that I'm missing something.
Here's what I get. Note that [ ... ] is a list; use ( ... ) for grouping expressions.
(%i1) RL_series: Rs + %i*w*Ls;
(%o1) %i Ls w + Rs
(%i2) RL_parallel: ratsimp( 1 / (1/Rp + 1/(%i*w*Lp)) );
Lp Rp w
(%o2) ------------
Lp w - %i Rp
(%i3) eq : RL_series = RL_parallel;
Lp Rp w
(%o3) %i Ls w + Rs = ------------
Lp w - %i Rp
(%i4) vars : [Rs, Rp, Ls, Lp];
(%o4) [Rs, Rp, Ls, Lp]
(%i5) denom(rhs(eq)) * eq;
(%o5) (Lp w - %i Rp) (%i Ls w + Rs) = Lp Rp w
(%i6) expand (%);
2
(%o6) %i Lp Ls w + Lp Rs w + Ls Rp w - %i Rp Rs = Lp Rp w
Assuming that vars are real, we can separate the real and imaginary parts of the equation.
(%i7) [realpart(%), imagpart(%)];
2
(%o7) [Lp Rs w + Ls Rp w = Lp Rp w, Lp Ls w - Rp Rs = 0]
(%i8) first(%) / (Lp*Rp*w);
Lp Rs w + Ls Rp w
(%o8) ----------------- = 1
Lp Rp w
(%i9) expand (%);
Rs Ls
(%o9) -- + -- = 1
Rp Lp
So one of the equations has a product Xs*Xp and the other has the ratio Xs/Xp. Maybe that helps direct the search for additional data.
At this point I don't know what more can be said. If anyone can comment on this point I would be interested to hear it.
EDIT: OP says that the goal is to solve for Rp and Lp in terms of Rs and Ls. Given that, we can solve the two equations we obtained in %o7.
(%i10) %o7[2];
2
(%o10) Lp Ls w - Rp Rs = 0
(%i11) solve ([%o9, %o10], [Rp, Lp]);
2 2 2 2 2 2
Ls w + Rs Ls w + Rs
(%o11) [[Rp = ------------, Lp = ------------], [Rp = 0, Lp = 0]]
Rs 2
Ls w
(%i12) subst (%o11[1], [%o9, %o10]);
2 2 2
Ls w Rs
(%o12) [------------ + ------------ = 1, 0 = 0]
2 2 2 2 2 2
Ls w + Rs Ls w + Rs
(%i13) ratsimp(%);
(%o13) [1 = 1, 0 = 0]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can Decode Json data in relational table laravel 5.8
I have a table Pemeliharaan with a column pertanyaan. In this column, I have data json like this ://
I update my question, this is dd not showing array on relational table user and alat. How? I need declare again in my controller? I update again, now I can show the data json. How can I parse it?
Pemeliharaan {#274 ▼
#table: "pemeliharaan"
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▼
"id" => 42
"user_id" => 2
"alat_id" => 1
"pertanyaan" => array:8 [▼
"question1" => "Periksa kondisi kelistrikan dan kabel"
"answer1" => "false"
"question2" => "Periksa kondisi kabel dan tempat sambungan"
"answer2" => "false"
"question3" => "Periksa kondisi pencetakan (tinta dan kertas printer)"
"answer3" => "false"
"question4" => "Fix and squish bugs"
"answer4" => "false"
]
"catatan" => "22-11-1996"
"status" => "Harian"
"deleted_at" => null
"created_at" => "2019-03-28 15:41:44"
"updated_at" => "2019-03-28 15:41:44"
]
#original: array:9 [▶]
This data is question and answer. And I have a view like this. I have a function show and showQuestion.
And view like this
//View // no problem on here
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>Waktu</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
@php
$no=0;
@endphp
@foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> <a href="/user/show/question/{{ $i->id }}" > <span class="label label-primary">Lihat Data</span> </a></td>//in here redirect to showQuestion
<td>{{ $i->created_at}}</td>
</tr>
@endforeach
</tbody></table>
</div>
viewQuestion (if I click the button on the table will view this data)
@if( !is_null($pemeliharaan) )
<p> Laporan : {{ $pemeliharaan->status }} </p>
<p> Tanggal : {{ $pemeliharaan->created_at }} </p>
<p> Jenis Alat : {{ $pemeliharaan->alat->nama_alat }} </p>
<p> User : {{ $pemeliharaan->user->name }} </p>
<p> pertanyaan : {{ $pemeliharaan['question1'] }} </p>// now showing anything
@endif
@foreach(json_decode($pemeliharaan, true) as $value)
pertanyaan : {{ $value->pertanyaan['question1'] }}
@endforeach //corect me at here
//this is I want to decode this json but i dont
know what i do haha :(
this view (without question and answer) is don't have an error.
this is my controller :
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->get();
return view('users.view',['pemeliharaan' => $pemeliharaan]);
}
public function showQuestion($id)
{
$pemeliharaan = Pemeliharaan::find($id);
$pemeliharaan->pertanyaan = json_decode($pemeliharaan->pertanyaan,true);
return view('users.view_question',compact('pemeliharaan'));
}
Having error like this
Undefined index: alat (View: /var/www/html/new/resources/views/users/view_question.blade.php)
I don't know how to decode and how to view in blade
A:
You need to decode the specific column, not the whole object, try:
public function showQuestion($id)
{
$pemeliharaan = Pemeliharaan::find($id);
$pemeliharaan->pertanyaan = json_decode($pemeliharaan->pertanyaan,true);
return view('users.view_question',compact('pemeliharaan'));
}
And check in the viewQuestion if $pemeliharaan is null or not :
@if( !is_null($pemeliharaan) )
<p> Laporan : {{$pemeliharaan['status']}} </p>
<p> Tanggal : {{ $pemeliharaan['created_at'] }} </p>
<p> Jenis Alat : {{ $pemeliharaan->alat->nama_alat }} </p>
<p> User : {{ $pemeliharaan->user->name}} </p>
<p> pertanyaan : {{ $pemeliharaan['question1'] }} </p>
@endif
To parse all the Questions/Answers try :
@foreach($pemeliharaan->pertanyaan as $key => $value)
pertanyaan : {{ $key . ' - ' . $value}}
@endforeach
Play with this as you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple annotations found error comes when adding dependency in pom.xml while creating spring, hibernate with maven
I am creating a sample project with maven for spring and hibernate. I am very new to this development. After placing the dependency such as
<dependencies>
<dependency>
<groupid>org.hibernate</groupid>
<artifactid>hibernate-core</artifactid>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring</artifactid>
<version>${springVersion}</version>
</dependency>
In eclipse it gives an error as Multiple annotations found at this line:
- Project build error: 'dependencies.dependency.groupId' for null:null:jar is
missing.
- Project build error: 'dependencies.dependency.artifactId' for null:null:jar is
missing.
I guess, the jar files for spring and hibernate are missing. Can someone let me know how to resolve this issue.
A:
Because your pom.xml has the invalid format
It should be
<groupId> instead of <groupid>
<artifactId> instead of <artifactid>
You can check the correct format of pom.xml at here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compiler warnings conversion
We are compiling using gcc with -Wconversion enabled. I get following warnings when I left shift result returned by isBitSet function below.
warning: conversion to 'u_int16_t {aka short unsigned int}' from 'int'
may alter its value [-Wconversion]
#include <stdint.h>
using namespace std;
void convertToPos(uint16 in) {
auto isBitSet = [&in](uint8_t position) -> bool{
return (in & (1 << position));
};
uint16_t signal = 0;
signal |= isBitSet(1) << 9; // Calibrated
signal |= isBitSet(2) << 10; // Corresponds to digital map
signal |= isBitSet(5) << 13; // DR
signal |= isBitSet(8) << 15; // 3D Fix
}
int main(int argc)
{
convertToPos(4);
return 0;
}
I tried changing lambda to below, but still I get the same error. How can I fix it?
auto isBitSet = [&in](uint8_t position) -> uint16_t {
return (in & (1 << position)) ? 1u:0u;
};
A:
To avoid the warning, you may do:
signal = uint16_t(signal | isBitSet(1u) << 9);
as operator | promotes operator uint16_t to int.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
write.table() results in permission denied - common solutions don't work
Can't seem to get permission to write files in R.
Using Windows 10. Only one user account in my computer, have tried running RStudio and Rgui as administrator. getwd() confirms 'C:/Users/name/R' is my working directory. I've gone to properties of the folder and SYSTEM and user have all permissions to write. Have tried changing the directory to no avail.
Using
write.table(dataframe, "C:/Users/name/R", sep = "|") and I get the following error:
Error in file(file, ifelse(append, "a", "w")) : cannot open the
connection In addition: Warning message: In file(file, ifelse(append,
"a", "w")) : cannot open file 'C:/Users/name/R': Permission denied
A:
The path you give to write.table should name a file. You have it naming a directory. R won't replace that directory with a file (thank goodness).
Try this:
write.table(dataframe, "C:/Users/name/R/dataframe.txt", sep = "|")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
docker swarm container communication
I create a swarm and join a node, very nice all works fine
docker swarm init --advertise-addr 192.168.99.1
docker swarm join --token verylonggeneratedtoken 192.168.99.1:2377
I create 3 services on the swarm manager
docker service create --replicas 1 --name nginx nginx --publish published=80,target=80
docker service create --replicas 1 --name php php:7.1-fpm published=9000,target=9000
docker service create --replicas 1 --name postgres postgres:9.5 published=5432,target=5432
All services boots up just fine, but if I customize the php image with my app, and configure nginx to listen to the php fpm socket I can’t find a way to communicate these three services. Even if I access the services using “docker exec -it service-id bash” and try to ping the container names or host names (I even tried to curl them).
What I am trying to say is I don’t know how to configure nginx to connect to fpm since I don’t know how one container communicates to another using swarm. Using docker-compose or docker run is simple as using a links option. I’ve read all documentation around, spent hours on trial and error, and I just couldn’t wrap my head around this. I have read about the routing mesh, wish will get the ports published and it really does to the outside world, but I couldn’t figure in wish ip its published for the internal containers, also that can't be an random ip as that will cause problems to manage my apps configuration, even the nginx configurations.
A:
To have multiple containers communicate with each other, they next to be running on a user created network. With swarm mode, you want to use an overlay network so containers can run on multiple hosts.
docker network create -d overlay mynet
Then run the services with that network:
docker service create --network mynet ...
The easier solution is to use a compose.yml file to define each of the services. By default, the services in a stack are deployed on their own network:
docker stack deploy -c compose.yml stack-name
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Inputting data from a text file with multiple numbers on each line - Python
Lets say I have a data file that has this inside it:
23 33 45
91 81 414
28 0 4
7 9 14
8 9 17
1 1 3
38 19 84
How can I import it into a list so that each individual number it its own item?
A:
You could alternatively use the python builtin functions like open file, split and readlines
with open('file.txt') as f:
for line in f:
a, b, c = map(int, line.split())
Another approach is
file = open(filename)
file_data = file.readlines()
But, the output will be a list of strings.
That is the each element in the list will represent one line in the file.
If you use the above code the output will look like
file_data = ['23 33 45', '91 81 414', '28 0 4 ', '7 9 14', '8 9 17', '1 1 3', '38 19 84']
You might want them to convert to either float or int.
you could do that using again numpy's fromstring module
from numpy import fromstring
data = [fromstring(i, dtype=float, sep=' ') for i in file_data ]
Notice that, I have used a list comprehension in the above code(which is faster than the conventional python for loop.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Chunk nested lists starting on their deepest level
I would like to have a function that chunkes my list into a sublist, and then these sublists into further sublists, according to this scheme. The number of nestings and block_sizes will vary. Please be aware of the [4] and [9] in lst2, this is essential.
block_sizes = [5, 2, 1]
my_lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# desired return
lst1 = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11]] # chunked into sublists of size 5
lst2 = [[0, 1], [2, 3], [4], [5, 6], [7, 8], [9], [10, 11]] # chunked into sublists of size 2; be aware of [4] and [9]
lst3 = [[0], [1], [2], [3], [4], [5], ... [11]]
I already tried this, but the chunking does not work as intended:
block_sizes = [5, 2, 1]
def chunk_into_list(lst, chunk_size):
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
for i, block_size in enumerate(block_sizes):
for step in range(len(block_sizes[:(i + 1)])):
my_lst = chunk_in_sizes(my_lst, block_sizes[step])
print(my_lst)
But this leads to:
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11]]
[[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], [[10, 11]]]
[[[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]], [[[10, 11]]]]
I will be using this for simulations, so efficiency would be important, if possible.
A:
I guess that it's not the most optimal way, but as far as i understand it will do what you want.
block_sizes = [5, 2, 1]
my_lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
def chunk_into_list(lst, chunk_size):
if lst and isinstance(lst[0], list):
lst_new = []
for nested_lst in lst:
lst_new += (chunk_into_list(nested_lst, chunk_size))
return lst_new
else:
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
for i, block_size in enumerate(block_sizes):
for step in range(len(block_sizes[:(i + 1)])):
my_lst = chunk_into_list(my_lst, block_sizes[step])
print(my_lst)
#Output
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11]]
[[0, 1], [2, 3], [4], [5, 6], [7, 8], [9], [10, 11]]
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Two step subfolder to include javascript
How to include deep folder in ruby on rails.
The norman subfolder //= require subfolder/filename how do make it
--javascript
-- subfolder
--subfolder
two step sub?
A:
Just like how you think it should be
//= require subfolder/subfolder/filename
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disable external keyboard input
I do not want an external keyboard to be allowed in my app. I realize this is an edge case but I do not like how the keyboard will not be shown when an external keyboard is used. Especially because I have a custom view above the keyboard that will now be shown at the bottom of the screen. Also, I have textfields that should only require numbers (phonenumber for example). Instead of checking input, I would rather just show the numbers keyboard. Obviously this can't happen with external keyboard.
I saw a post here: How to detect external keyboard connectification in objective-c?
but that's not enough to just detect it...I want to disable!
Thanks,
-Adam
A:
This seems to be a sloppy way of handling input. Do proper input checking and validation, rather than trying to force a single input method. What if someone tries to use the iOS copy/paste functionality on your field? What if there is some future update that provides another input method that you were not anticipating?
A:
Here are two things you can do to circumvent this problem:
You can force the keyboard to appear even when there is an external keyboard present.
You can validate text input using the UITextField delegate method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
For example, to allow only numbers to be entered, you can do:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
if ([[string stringByTrimmingCharactersInSet:myCharSet] length]) {
return YES;
} else {
return NO;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Iterative DNS query faster than recursive query due to more entries cached in Iterative DNS query
In an iterative DNS query, requests made by the local DNS server to the root, TLD and authoritative servers can be cached inside the local DNS. Whereas in the recursive query, only the specific hostname to IP address can be cached in local DNS server. Does this mean that iterative DNS queries are faster since it contains more entries cached in the local DNS server ?
If that is not the case would there be a difference between the two methods.
A:
In recursive DNS query, the client only sends the query to the first DNS server.
The server, if it cannot answer, will send the request to next server and so on,
until the query is resolved.
Here the DNS client requires that the DNS server respond to the query,
so the burden is on Server to resolve the query.
In iterative DNS query, the client is responsible for sending the query to successive
servers, until the query is resolved by hitting a server that is authorized for
the domain name (or until an error or time-out).
Here the burden is on the client to resolve the query.
I don't think that there is a big difference in speed between the two,
except that a DNS server that is high enough in the hierarchy will likely
have available a faster Internet connection than the client.
For the iterative DNS query, the client will end up with having the successive
intermediate DNS servers in its cache, but I don't see how it may use this
to advantage.
In more detail, these are the four most common answers a DNS server can provide:
Authoritative - a positive answer returned to the client with the Authoritative Answer (AA) bit set in the response.
Positive - an answer that contains the resource record (RR) or list of RRs that match the query.
Referral - an answer that contains a list of alternate servers the client can use to resolve the name. This type of answer is given if Recursion is not supported.
Negative - this answer indicates that an Authoritative server reported that the name (or record type) does not exist in the DNS name space.
In the Iterative query, the client sends a query to the server.
If recursion is disabled, and the server cannot answer the query,
the server will respond with a Referral answer.
The client will then use that information to query another DNS server.
This process will continue until a server responds with an Authoritative or
Negative response, or until the client runs out of time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
customize multicolumn footnote XeLaTeX
I want customized footnote with this specification in document:
1) footnote number appear superscript in text body
(like: foo1 foo2 foo3 foo4)
2) footnote number appear as normal number in footnote part
(like: 1. foot1 2. foot2 3. foot3 4.foot4)
This is MWE i try it. I try writing (English/persian) document using
XePersian package an XeLaTeX.
\documentclass[12pt,oneside]{book}
\usepackage[extrafootnotefeatures]{xepersian}
\settextfont{B Nazanin}
% footnote customization code.
\makeatletter
\long\def\@makefntext#1{\parindent 1em
\noindent\hbox to 2em{}%
\llap{\@thefnmark.\,\,}#1}
\makeatother
\begin{document}
\chapter{مقدمه}
% command for 2 column footnotes (when XePersian
% package load with [extrafootnotefeatures], its
% possible using this command)
\twocolumnfootnotes
مدل
\RTLfootnote{
خلاصهای از واقعیت را مدل گویند.
}
مدل
\LTRfootnote{Simulation is the imitation of the operation of ...}
\end{document}
A:
I Found the right answer from this Q/A website, I should add this two
command before begin{document}:
\RTLfootmarkstyle{#1. }
\LTRfootmarkstyle{#1. }
And Finally
\documentclass[12pt,oneside]{book}
\usepackage[extrafootnotefeatures]{xepersian}
\settextfont{B Nazanin}
% footnote customization code.
\RTLfootmarkstyle{#1. }
\LTRfootmarkstyle{#1. }
\begin{document}
\chapter{مقدمه}
% command for 10 column footnotes (when XePersian
% package load with [extrafootnotefeatures], its
% possible using this command)
\tencolumnfootnotes
مدل
\RTLfootnote{
خلاصهای از واقعیت را مدل گویند.
}
مدل
\LTRfootnote{Simulation is the imitation of the operation of ...}
\end{document}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add button to put extra in Intent and Remove button to empty all
I have and Add and Remove button in my listView Adapter class as below. I want to remove everything i add when i click on Add button, by clicking on Remove button. The thing is i tried getIntent.removeExtra(); but it's not working.
Any ideas?
public class CustomRestaurantMenuAdapter extends ArrayAdapter<Restaurant> {
private List<Restaurant> items;
public CustomRestaurantMenuAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public CustomRestaurantMenuAdapter(Context context, int resource, List<Restaurant> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.menu_item_list, null);
}
Restaurant p = getItem(position);
if (p != null) {
TextView foodId = (TextView) v.findViewById(R.id._id);
final TextView foodName = (TextView) v.findViewById(R.id.name);
TextView foodDescription = (TextView) v.findViewById(R.id.description);
final TextView foodPrice = (TextView) v.findViewById(R.id.price);
final Button addButton = (Button) v.findViewById(R.id.addButton);
final Button removeButton = (Button) v.findViewById(R.id.removeButton);
if (foodId != null) {
foodId.setText("" + p.getId());
}
if (foodName != null) {
foodName.setText("" + p.getName());
}
if (foodDescription != null) {
foodDescription.setText(p.getDescription());
}
if (foodPrice != null) {
foodPrice.setText(p.getPrice());
}
removeButton.setVisibility(View.INVISIBLE);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sName = foodName.getText().toString();
String sPrice = foodPrice.getText().toString();
Intent orderDetails = new Intent(getContext(), OrderActivity.class);
orderDetails.putExtra("name", sName);
orderDetails.putExtra("price", sPrice);
Log.d("NAME ", sName);
Log.d("PRICE ", sPrice);
removeButton.setVisibility(View.VISIBLE);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//remove what is added to intent here or undo the add action
removeButton.setVisibility(View.INVISIBLE);
}
});
}
return v;
}
}
A:
Instead of removing all extras one by one, you can reinitialize your intent like that:
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Re-init your intent
orderDetails = new Intent(getContext(), OrderActivity.class);
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is Firebase Cloud Messaging HIPAA Compliant?
I want to use Firebase Cloud Messaging in a healthcare application. I want to know is FCM HIPAA Compliant and does it provide BAA?
A:
We’ve just completed the HIPAA audit with a 3rd party for a Firestore Chat sample app (iOS and Android) that’s using End-to-End Encryption. If you’re implementing a healthcare Chat app, keep reading. Otherwise, this isn’t relevant.
The challenge: if you know how E2EE works, you realize that it alone should protect your patients’ data from Firebase/Firestore: apparently, lawyers don’t agree with that. So we had to implement an artificial data redaction that deletes chat messages from Firestore as soon as the messages are delivered. This enables your app to qualify for HIPAA’s Conduit exception, because it only acts as a message delivery system, it doesn’t store permanent health data. This way, your chat solution is exempt of HIPAA.
We’ve compiled the solution into a How-to blog post: https://VirgilSecurity.com/hipaa-firebase - with pointers to reusable sample apps.
Whitepaper that contains our HIPAA audit & 3rd-party data privacy expert’s notes: https://VirgilSecurity.com/firebase-whitepaper
A:
According to the co-founder, as of now Firebase is not HIPAA compliant.
You can take a look at the updates here: https://groups.google.com/forum/#!topic/firebase-talk/sg-WCHVXs5k
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript array.push in Promise.all returning undefined
I have a promise and I'm pushing a value to Promise.all but it's returning undefined.
Here's the code:
var arr = [];
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
arr.push(mypromise);
});
Promise.all([arr]).then(values => {
console.log(values);
});
How can I fix this?
A:
var arr = [];
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
});
arr.push(mypromise);
Promise.all(arr).then(values => {
console.log(values);
});
Try this.
Your Implementation for Promises is not proper, refer this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Also, you are making syntax mistakes like arr.push should be after
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
});
and Promise.all accepts an array and what you are doing is wrapping an array with another array.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Want to create a Lead Time chart based on the selection of two releases rally
Want to create a Lead Time chart based on the selection of two releases rally
like below
Something like this, with the options to select two releases start release and end release. So this chart should be prepared for those releases time period, rather than for whole year.
Any suggestions, examples for this. Which calculator should I use. Any help will be appreciated, thanks in advance
A:
Cycle/Lead Time cannot be customized beyond what's available in the Settings because it is actually a report served by a legacy analytics service. Generally, this applies to all the reports available on Reports>Reports page even when they can be installed via AppCatalog. Anything that can be accessed via StandardReports component available in older AppSDK1 falls into this category. AppSDK2 also has a thin wrapper over it via Rally.ui.report.StandardReport but the same limitation applies since underneath it is using the same built-in reports that predate LookbackAPI.
If you decide to write an app from scratch that displays cycle time use AppSDK2's SnapshotStore that gets historic data from LookbackAPI.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Default constructor cannot handle exception type SocketException thrown by implicit super constructor
I'm working on an android app that will be able to switch between 3G and 4G manually by making a call and sending out a package simultaneously. When I end the call, the package will continue to send keeping the phone in 3G, but then when I push a button, it terminates the package.
I'm fine on most of the code, but I got the program to send the package from someone else and I'm a bit confused on how I get it running, specifically this one error I'm getting when I declare the field socket. I get an error message saying "Default constructor cannot handle exception type SocketException thrown by implicit super constructor. Must define an explicit constructor."
Here's my class file for the package:
package com.example.derpphone;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.TimerTask;
public class timer extends TimerTask {
DatagramSocket socket = new DatagramSocket();
@Override
public void run() {
if (socket != null) {
byte[] bytes = new byte[100];
SocketAddress serverAddress = new InetSocketAddress("131.179.176.74",
9998);
try {
DatagramPacket packet = new DatagramPacket(bytes,
bytes.length, serverAddress);
socket.send(packet);
} catch (Exception e) {
}
}
}
}
A:
Change your code to:
DatagramSocket socket;
public timer() throws Exception {
socket = new DatagramSocket();
}
When you write:
DatagramSocket socket = new DatagramSocket();
without a default constructor, it is equivalent to:
DatagramSocket socket;
public timer() {
super();
socket = new DatagramSocket();
}
As DatagramSocket constructor throws an exception, this needs to be caught or declared.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Box2D, what exactly does a fixture represent?
In Box2dWeb, when we create a body we attach a fixture to the body object.
We make the shape, friction, restitution and so on by tinkering with the fixture object.
So from this can we conclude that the fixture is what we really need to tinker with to get the body we want, and the body object we create just an abstract entity? Abstract in the sense that by itself, it is invisible in the canvas after we draw and animate the canvas? The body is just the abstract, formless object that becomes physical once we attach the fixture. Is this right to conclude?
A:
Yep, sounds right.
A body abstractly represents a physical entity. A fixture defines its shape, physical properties and which other fixtures it collides with. Technical details in the Box2D manual, Chapter 7: Fixtures.
Some reasons they are separate:
This separates concerns by allowing the same fixtures to be used for all types of bodies (dynamic, static, kinematic).
It allows you to create a compound body that has multiple fixtures. Fixtures in the same body are stationary relative to each other. (This is superior to a weld joint, which can flex slightly due to Box2D being an iterative solver.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are there any HTML widgets for embedding Hudson results?
Because, if there are, I can't find them. Basically, I would love to be able to show the build history on another web page. Has this been done before?
A:
Hudson provides rss feeds of build histories. Links are at the bottom of the build page and will look something like this: http://hudson.company.com/rssAll
Then you can use the Google AJAX Feed API: http://www.google.com/uds/solutions/wizards/dynamicfeed.html which will generate all the code for you!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
External Storage distinction
My question is related to storing files on android devices. I want to store files created in an app to an SD, if it is mounted. The problem i am having is that the device I am using has a non-removable external storage unit. All attempts to find the SD card result in finding that external storage and the files being saved there. Is there a work around, or a way to get a list of the external storage's, or way to directly save to the SD card?
A:
Android 4.4 offers getExternalFilesDirs() (note the plural name), which may be able to give you locations on removable media like an SD card, depending upon where it is located and how the manufacturer elected to interpret Google's rules.
Everything else on Android 4.4+, in terms of removable media, cannot be written to, except presumably via apps running with superuser privileges on rooted devices.
There is no support at all for anything beyond standard external storage on Android 4.3 and below. You will find various recipes online for trying to find other partitions that might represent removable media. These recipes are not supported, may not be reliable across all devices, and will not work on many Android 4.4+ devices.
Hence, I strongly encourage you to focus on standard external storage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Acceder a una variable de un objeto que esta dentro de un arraylist
tengo un arraylist creado que dentro de el tiene los mismos tipos de objetos {participante(String nombre, int puntos, String tiempo). Bien, ahora queria ordenar el array segun el int puntos de cada objeto. He probado con el metodo sort de List pero no accedo bien a la variable de el objeto que esta dentro o no se si se puede de la manera que yo lo hago. Mi codigo seria el siguiente:
for (int a = 0; a < i; a++) {
participantes.add(a, pat.introducir(sc));
}
for( int x=0;x<participantes.size();x++){
participantes.sort(participantes.get(x).puntos);
}`
Muchas gracias por toda la ayuda ofrecida!
A:
Si quieres ordenar los items mediante Collections.sort() debes hacer que Participante implemente la interfaz Comparable como te lo sugirió Glenn Sandoval.
Para hacer eso simplemente pasa de:
class Participante
a
class Participante implements Comparable<Participante>
y sobreescribe el método compareTo(), teniendo en cuenta que puntos es private y has definido un Getter llamado getPuntos(), de una manera como la siguiente:
@Override
public int compareTo(Participante p2) {
int puntosDelOtro = p2.getPuntos();
// Orden ascendente (menor a mayor)
return this.puntos - puntosDelOtro ;
// Orden descendente (mayor a menor)
//return puntosDelOtro - this.puntos;
}
Luego solo debes llamar a Collections.sort() pasándole como parámetro el ArrayList que quieres ordenar y listo.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How should data be synchronized between a WinForms GUI control and the client class?
What method is considered the "standard" for keeping data structures within GUI controls synchronized with the data structures that are maintained by the application?
For example:
In WinForms, if one creates a ListView instance, rather than pointing it to a data structure that represents the items to appear within the list, one must programmatically instantiate ListViewItem(s) and call an .Add method to manually replicate them, one by one, into a data structure that is internal to the ListView itself. This makes sense from a threading standpoint, and it also makes sense within the context of rendering that a control should require a specialized data structure to exist for which the control alone knows the details regarding maintenance.
However, this creates two issues:
Redundancy:
If the client class manages its own list of entities, to allow the user to select among them from the WinForms UI, this entire list must be read, converted and then recreated inside of the UI control via methods such as: .Add(ListViewItem item) Lists now occupy twice as much memory.
Complexity:
Since two lists now exist, one must programmatically ensure that they remain synchronized. This can be achieved with events that are fired from the client class's collection object, or a programmer can simply be careful to always add/remove from one list when they add/remove from the other.
I have seen many instances where programmers will take the shortcut of using a UI element like a ListView as the actual collection object used to maintain the list. For example, each user entered item will be immediately inserted into the ListView, and then when it comes time to access to user's entires, the application just iterates through the ListView. This method fails to apply when you are properly seperating business/application logic from UI logic.
Overall, something just doesn't seem right about storing application data within a data structure that is internal to a GUI control. Likewise, storing two lists and keeping them programmitically synchronized doesn't seem like an elegant solution either. Ideally, one would need only to supply a UI element with a reference to a list that resides within the scope of the client.
So, what is the "right" way to approach this problem?
A:
Every UI control needs some state of its own. With complex controls (like ListView) that state is correspondingly complex. The trick is to make the maintenance of the controls state as simple as possible. With a standard ListView, that's not possible -- the programmer has to do the work.
That's one reason I wrote ObjectListView (an open source wrapper around .NET WinForms ListView). It allows you to use a ListView at a higher level where the maintenance of the controls state is invisible. An ObjectListView operates on your model objects directly:
this.objectListView1.Objects = listOfModelObjects;
this.objectListView1.SelectedObject = aPerson;
Once you can work at this level, data binding itself is no so useful. But, if you really want to use it, you can use the data-bindable DataListView from the ObjectListView project. It gives you the best of both worlds.
With an ObjectListView, there is no reason to switch to the far less interesting DataGridView. An ObjectListView gives you the ease of DataGridView with the nice UI features of a ListView, then plus some more:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Retag ecmascript-harmony into ecmascript-6?
The tag ecmascript-harmony appears to be related to the fact that ecmascript-6 is labeled as ES6 Harmony in places or something or other.
A quick perusal of the questions appears to show a bunch of questions dual-tagged with 6 and harmony, and a few regarding Node.js that I am not proficient enough to establish a connection with whether it relates to ES-harmony or something else called harmony.
There's also the tag ecma that I've found that seems to be disorganized as all heck that probably needs to be looked at.
Someone who is more familiar with ES6
A:
Actually it seems that the entire family of ecma tags needs to be reviewed.
So far we have:
ecma
ecmascript-5
ecmascript-6
ecmascript-harmony
ecma262
ecmascript-4
ecmascript
es5
es7
es2015
es2016
ecmascript-2015
ecmascript-7
I found at least one questionable synonym where "ecmascript" is redirected to "javascript". They are not the same. One is a specification and another - one of the existing implementations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unix UIDs vs Windows SIDs - why?
From what I've read UIDs in Unix are assigned by the administrator while the SIDs are random in Windows. Is there a security reason behind this, or is it just different ways to solve IDs?
Thanks
A:
UUIDs and SIDs are essentially the same thing.
They're a combination of a system specific part and a timestamp, generated according to a specific algorithm (which might be different between implementations, but that's irrelevant).
Essentially they're both semi-random. Maybe some Unix admins are convinced there's some "security" reason for not handing them out or whatever, but that's nonsense.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CAShapeLayer get current scale
I have a CAShapeLayer that scales to an unknown scale number:
myCAShapeLayer.transform = CATransform3DMakeScale(newScale, newScale, 1)
Then at a certain point, I have to run a CABasicAnimation from current scale back to 1:
let animation1 = CABasicAnimation(keyPath: "transform.scale")
animation1.fromValue = myCAShapeLayer.value(forKeyPath: "transform.scale") as! CGFloat
animation1.toValue = 1.0
animation1.duration = 0.5
myCAShapeLayer.add(animation1, forKey: nil)
when I log myCAShapeLayer.value(forKeyPath: "transform.scale") as! CGFloat after each CATransform3DMakeScale, its always 1.0, though visually the layer is scaled up.
I also tried myCAShapeLayer.presentation()?.value(forKeyPath: "transform.scale") as! CGFloat and its also 1.0
A:
If we go to the declaration of CATransform3DMakeScale. We have this information
/* Returns a transform that scales by `(sx, sy, sz)':
* t' = [sx 0 0 0; 0 sy 0 0; 0 0 sz 0; 0 0 0 1]. */
@available(iOS 2.0, *)
public func CATransform3DMakeScale(_ sx: CGFloat, _ sy: CGFloat, _ sz: CGFloat) -> CATransform3D
So, as we know what indices in matrix are changed for this transform, we can get each as below,
shape.transform = CATransform3DMakeScale(2.09, 4.88, 3.49)
print(shape.transform.m11)
print(shape.transform.m22)
print(shape.transform.m33)
Output:
2.09
4.88
3.49
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flex: Tab Navigator tab position
I need to develop a Tab Navigator with a few tabs on the left hand side and one tab on the right hand side, I have experimented with the "tabOffset" property, but this does not seem to be able to help
Thanks in advance!
A:
I made custom TabNavigator component.
package
{
import mx.containers.TabNavigator;
import mx.controls.Button;
import mx.events.FlexEvent;
public class CustomTabNavigator extends TabNavigator
{
public function CustomTabNavigator()
{
super();
}
override protected function createChildren(): void
{
super.createChildren();
tabBar.addEventListener(FlexEvent.CREATION_COMPLETE, addSpacer);
}
public function addSpacer(event: FlexEvent): void
{
var buttonCount: int = tabBar.getChildren().length;
var _width : Number = this.width;
var button: Button = tabBar.getChildAt(buttonCount-1) as Button;
_width = _width - button.width;
button.x = _width;
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A colored ball problem - $2$
Say you have $2n+2b$ balls where $2n$ balls are colored white, $b$ balls are colored blue and $b$ balls are colored red.
You have two urns. You randomly choose $n+b$ balls and throw in urn $1$ while you place the remaining $n+b$ balls in urn $2$.
What is the probability that the blue balls and red balls are in separate urns?
I am most interested in case $\frac{n}b\rightarrow\infty$ such as $b=n^{\frac1c}$ with $c>1$ being fixed and in case $\frac{n}b\rightarrow c$ such as $b={\frac nc}$ with $c>1$.
A:
Given the explicit answer received in the previous version of this question, which was $2\frac{{2n}\choose{n}}{{2n+2b}\choose {n+b}}$, and assuming $n\rightarrow\infty$, you can use the Stirling approximation for the factorial to get $2\sqrt{\frac{n+b}{n}}\left(\frac{1}{2}\right)^{2b}\simeq\left(\frac{1}{2}\right)^{2b-1}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to identify fantasy fonts
I can clearly identify wacky fonts like this one:
to be of the "fantasy" type, but some fonts look almost like regular serif or sans serif fonts only with some strange things going on. As an example take this other one:
It's advertised as serif, and it does have some serif characteristics as far as I can tell, but it also has some strange characters that seem out of place, like the lower case "a" or "f". It just doesn't strike me as being a proper serif font, but I'm no expert in type.
How can I be sure a font is fantasy or not?
A:
Like "fantasy," "wacky" is not in the Dictionary of Spiffy Type Terminology. :)
I get from your question, and the exchange with e100, that you're asking about decorative type rather than "typefaces that would be good when designing a fantasy MMORPG."
A decorative face is, for the most part, one that doesn't fit in any of the categories used to describe text or ordinary display faces, such as "transitional", "modern", "slab serif", etc.
Decorative faces are okay for headline or display applications, never for longer passages of text.
Your first example goes beyond "decorative" and is what's often called a "novelty" typeface. "Novelty" songs are basically musical jokes ("A Boy Named Sue" and the old Sonny and Cher "Rockefeller song are good examples) that you get the first time and don't find so amusing or interesting the second or later times. Novelty fonts are the same way. Use those dragons in a headline, everybody gets the dragon joke, then it's stale.
Blue Island is a decorative font. Toybox Blocks is a novelty font.
A:
I'm not 100% sure what you're asking for, but:
Serifs are a specific feature of a typeface; ModernAntiqua has serifs so it would definitely be considered a serif font. But you could also give it other classifications, such as "post-modern", perhaps.
"Fantasy" isn't really a very specific or commonly used classification, although it is defined as a generic font-family in CSS:
Fantasy fonts, as used in CSS, are primarily decorative while still
containing representations of characters (as opposed to Pi or Picture
fonts, which do not represent characters). Examples include:
Latin fonts Alpha Geometrique, Critter, Cottonwood, FB Reactor, Studz
This would only be used as a final fallback if none of the fonts specified are available.
I think "decorative" is more likely to be used.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I transform a Play application to an Eclipse project
In the play documentation I found the link (http://www.playframework.com/documentation/1.2.4/ide) describing how to convert a Play project into a Eclipse project.
I followed the following steps but Play doesn't accept the newly created application.
Why Play doesn't accept my application?
I am using:
Scala: Scala code runner version 2.9.2 -- Copyright 2002-2011, LAMP/EPFL
Play 2.2.1
I create a play application
/play-2.2.1$ ./play new hello
_
_ __ | | __ _ _ _
| '_ \| |/ _' | || |
| __/|_|\____|\__ /
|_| |__/
play 2.2.1 built with Scala 2.10.2 (running Java 1.7.0_40), http://www.playframework.com
The new application will be created in /home/<user>/programming/play-2.2.1/hello
What is the application name? [hello]
>
Which template do you want to use for this new application?
1 - Create a simple Scala application
2 - Create a simple Java application
> 1
OK, application hello is created.
Have fun!
However, play does not accept hello as an application
~/programming/play-2.2.1$ ./play eclipsify hello
_
_ __ | | __ _ _ _
| '_ \| |/ _' | || |
| __/|_|\____|\__ /
|_| |__/
play 2.2.1 built with Scala 2.10.2 (running Java 1.7.0_40), http://www.playframework.com
This is not a play application!
Use `play new` to create a new Play application in the current directory,
or go to an existing application and launch the development console using `play`.
You can also browse the complete documentation at http://www.playframework.com.
A:
You are looking at the documentation for a previous version of Play. The documentation for your version is http://www.playframework.com/documentation/2.2.1/IDE.
The command you need to use is eclipse. It changed sometime between 2.0 and 2.1.
There is also a tutorial on the Scala IDE website
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get an element from an ArrayList?
I have an arraylist of arraylists having string[]s i.e.,
ArrayList<ArrayList> arraymain = new ArrayList<>();
ArrayList<String[]> arraysub = new ArrayList<>();
Now, adding the elements to arraysub,
arraysub.add(new String[]{"vary","unite"});
arraysub.add(new String[]{"new","old"});
I tried:
arraymain.get(0).get(0)[1];
But I'm getting an error : Array type expected; found 'java.lang.Object'
How can I now retrieve the data(the string stored in the string[])?
A:
Change the type of the inner ArrayList:
ArrayList<ArrayList<String[]>> arraymain = new ArrayList<>();
ArrayList<String[]> arraysub = new ArrayList<>();
This way arraymain.get(0).get(0) will return a String[] instead of an Object.
It would be even better if you declare the variables as Lists, instead of forcing a specific List implementation:
List<List<String[]>> arraymain = new ArrayList<>();
List<String[]> arraysub = new ArrayList<>();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does the preparedStatement avoid SQL injection?
I have read and tried to inject vulnerable sql queries to my application. It is not safe enough. I am simply using the Statement Connection for database validations and other insertion operations.
Is the preparedStatements safe? and moreover will there be any problem with this statement too?
A:
Using string concatenation for constructing your query from arbitrary input will not make PreparedStatement safe. Take a look at this example:
preparedStatement = "SELECT * FROM users WHERE name = '" + userName + "';";
If somebody puts
' or '1'='1
as userName, your PreparedStatement will be vulnerable to SQL injection, since that query will be executed on database as
SELECT * FROM users WHERE name = '' OR '1'='1';
So, if you use
preparedStatement = "SELECT * FROM users WHERE name = ?";
preparedStatement.setString(1, userName);
you will be safe.
Some of this code taken from this Wikipedia article.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
meaning of kannel status
we have configured kannel, and the status look like
SMS: received 0 (0 queued), sent 15133 (0 queued), store size 0
SMS: inbound (0.00,0.00,0.00) msg/sec, outbound (3.08,15.23,0.02) msg/sec
DLR: received 14232, sent 0
DLR: inbound (11.45,5.64,0.02) msg/sec, outbound (0.00,0.00,0.00) msg/sec
DLR: 980 queued, using internal storage
Box connections:
smsbox:vsmsc, IP 127.0.0.1 (0 queued), (on-line 8d 21h 38m 41s)
smsc1[smsc1] SMPP:xxxxx.xxxxx.com:2775/2775:xxxxx:SMPP (online 769120s, rcvd: sms 0 (0.00,0.00,0.00) / dlr 1 (0.00,0.00,0.00), sent: sms 1 (0.00,0.00,0.00) / dlr 0 (0.00,0.00,0.00), failed 0, queued 0 msgs)
in the DLR inbound, it showing (11.45,5.64,0.02) msg/sec. There is 3 value inside (). What is the meaning of each?
thanks
A:
Average for the last minute;
Average for the last 5 minutes;
Average for all of runtime.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the names of interrupt service routines for the msp430 series of microcontrollers?
Is there a comprehensive list of names of interrupt service routines (ISR), specifically for msp430F5438A? Any help would be appreciated, thanks.
A:
A function is connected to an interrupt vector with #pragma vector=nr or __attribute__((interrupt(nr))), depending on the compiler used.
The name of the function does not matter, only that vector number.
You can name the function after the hardware module (see kfx's answer for an example list), but it might make more sense to name it after the actual function you have assigned to that part of the hardware (e.g., red_button_gpio_interrupt() instead of port1_interrupt()).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CS0266 cannot convert type
I have an error:
CS0266 C# Cannot implicitly convert type
'System.Linq.IQueryable' to
'System.Linq.IOrderedIQueryable'. An
explicit conversion exists (are you missing a cast?)
Here is my controller:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSurnameSortParm = sortOrder == "NameSurname" ? "NameSurname_desc" : "NameSurname";
ViewBag.ReasonSortParm = sortOrder == "Reason" ? "Reason_desc" : "Reason";
ViewBag.AccessSortParm = sortOrder == "Access" ? "Access_desc" : "Access";
ViewBag.UserOrAdminSortParm = sortOrder == "UserOrAdmin" ? "UserOrAdmin_desc" : "UserOrAdmin";
ViewBag.DepartmentSortParm = sortOrder == "Department" ? "Department_desc" : "Department";
ViewBag.UNCPathSortParm = sortOrder == "UNCPath" ? "UNCPath_desc" : "UNCPath";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var request = from c in _context.RaidRequest
orderby c.Id
select c;
if (!String.IsNullOrEmpty(searchString))
{
request = request.Where(s => s.NameSurname.Contains(searchString));
}
switch (sortOrder)
{
case "NameSurname_desc":
request = request.OrderByDescending(c => c.NameSurname);
break;
case "Reason":
request = request.OrderBy(c => c.Reason);
break;
case "Reason_desc":
request = request.OrderByDescending(c => c.Reason);
break;
case "Access":
request = request.OrderBy(c => c.Access);
break;
case "Access_desc":
request = request.OrderByDescending(c => c.Access);
break;
case "UserOrAdmin":
request = request.OrderBy(c => c.UserOrAdmin);
break;
case "UserOrAdmin_desc":
request = request.OrderByDescending(c => c.UserOrAdmin);
break;
case "Department":
request = request.OrderBy(c => c.Department);
break;
case "Department_desc":
request = request.OrderByDescending(c => c.Department);
break;
case "UNCPath":
request = request.OrderBy(c => c.UNCPath);
break;
case "UNCPath_desc":
request = request.OrderByDescending(c => c.UNCPath);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(request.ToPagedList(pageNumber, pageSize));
}
This part of its broken :
if (!String.IsNullOrEmpty(searchString))
{
request = request.Where(s => s.NameSurname.Contains(searchString));
}
Can you please explain what to do ?
I followed the tutorial word by word. It worked until I added pagination.
could it be something with my View?
A:
All your queries contain an orderby, therefore returning an IOrderedQueryable, except the query where you use the searchstring. This query returns an IQueryable.
Since IOrderedQueryable is inheriting from IQueryable you can assign an IOrderedQueryable to an IQueryable, but not the other way around.
Remove the orderby from the first query, and it will become an IQueryable, add a default: to the switch statement to do the default sorting. This will also prevent you sorting the resulting query twice.
var request = from c in _context.RaidRequest
select c;
// Your code
switch (sortOrder)
{
// other cases
case "UNCPath_desc":
request = request.OrderByDescending(c => c.UNCPath);
break;
default:
request = request.OrderBy(c => c.Id);
break;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Recover data from BLOB file S-Health
I am trying to get data from a blob file I am getting with the Samsung S-health SDK.
What I actually do is:
Cursor c = null;
int i = 0;
c = result.getResultCursor();
if (c != null) {
while ( c.moveToNext() ) {
byte[] live_data = c.getBlob( c.getColumnIndex( HealthConstants.Exercise.LIVE_DATA ) );
if ( live_data != null ) {
// Do something with data.
} else {
Log.d(APP_TAG, "there is no live data.");
}
}
} else {
Log.d(APP_TAG, "There is no result.");
}
"live_data" is a compressed file containing a json with all the data.
I tried to decompress it with ZipInputStream without success.
How can I do?
A:
Finally I found the solution after several attempts.
The problem was that the blob file was a gzip file.
Below is a simple code to decompress the byte array ( in my case live_data ):
ByteArrayInputStream inputStream = new ByteArrayInputStream(live_data);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
BufferedReader bf = new BufferedReader(new
InputStreamReader(gzipInputStream, "UTF-8"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
Where outStr is the content of the file I wanted to retrieve and live_data is the blob byte array.
I hope this can be of help to others as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как сделать чтоб результат в numericUpDown не округлялся?
Например numericUpDown1 умножается на numericUpDown2 и результат в numericUpDown1: если 49 * 1,18 = 57,82, тогда если в numericUpDown1 decimalplaces = 0, результат округляется и в numericUpDown1 будет 58. Если decimalplaces = 2, в результате в numericUpDown1 будет 57,82. Как сделать чтоб при decimalplaces = 0, результат не округлялся? Или чтоб в примере 49 * 1,18 в результате в numericUpDown1 было = 57?
A:
numericUpDown1.Value = Math.Floor(numericUpDown1.Value * numericUpDown2.Value);
Update
как сделать чтоб результат округлялся также только до десятых
https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx
numericUpDown1.Value = Math.Round(numericUpDown1.Value * numericUpDown2.Value, 1);
Update
Нужно сделать метод Math.Floor, только не для целых чисел, а для
десятых.
numericUpDown1.Value = Math.Floor(numericUpDown1.Value * numericUpDown2.Value * 10) / 10;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why Genysis did not have any backup servers?
Look, its year 2017. While I love idea of people going to software company and shooting into servers, most technical companies would respond:
Oh, shoot. We got our main building destroyed. Luckily we offshored most of IT developement to India, so we just load up the system from last SVN/GIT commit.
Also, if it has about one billion pre-orders, even test environment would be sized appropriately, so destroying test env. in main building should not have big effect.
I know there is "cliffhanger" at the end of the movie, but still: Is there any in-universe explanation why destroying Genysis (Skynet) labs would have such big effect on whole system?
Edit: After reading the comments: If there is no in-universe explanation, is there any out-of-universe explanation other than "awful writing"?
A:
The "cliffhanger" denies the premise of this question and is the in-universe explanation why destroying Genisys does not have a large effect.
The 'bad writing' could just be that our protagonists do not understand very well how modern computer software is deployed. They thought it would work, so that became their objective.
Why they thought that is the real question - but it's a moot one, as that's not in the script.
Out-of-universe, the author realized that you don't end a franchise that could later net you millions of dollars. There's an alternate ending for T2 which was filmed, but was not included in the release, because it brought the entire story to an end.
The "problem" with the first two James Cameron-directed Terminator films is that they were satisfying. They told a complete story and left the viewer with the distinct sense that the tale had ended, though the final moments in Terminator 2 included the visual of a dark road with a note that no one knew what the future would hold.
–Terminator 2's original ending would have made the sequels impossible, polygon.com
As opposed to the deleted scene where grandma Sarah sits on a park bench watching John push his child on a swing.
SARAH (V.O.)
August 29th 1997 came and went. Nothing much
happened. Michael Jackson turned forty. There
was no Judgment Day. People went to work as
they always do, laughed, complained, watched
TV, made love.
–T2: Alternate Ending, killermovies.com
Not including the cliffhanger in Genisys would have been the same mistake of including that scene in T2. Not that it was really necessary, given that most people understand what The Cloud is and how it works.
So, somewhere during the post production of T2 it was decided that, no matter how much the ending of a story might invalidate its plot, awful writing it must leave room for the search for more money.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If $f: \Bbb R\rightarrow \Bbb R $ is monotonic and onto, prove that $f$ is continuous.
If $f: \Bbb R\rightarrow \Bbb R $ is monotonic and onto, prove that $f$ is continuous. (Hint: given any $x \in \Bbb R$ and any $\epsilon \gt 0$, there is $x_1$ with $f(x_1)= f(x) - \epsilon$ and $f(x_2) = f(x) +\epsilon. $Use this to get $\delta \gt 0$.)
I need to show if $\exists \delta \gt 0: |x-a|\lt \delta$ then $|f(x) - f(a)| \lt \epsilon $
$f(x_1) \lt f(x) \lt f(x_2)$ is all I can come up with.
A:
HINT
You are right, $f(x_1) < f(x) < f(x_2)$. Consider using
$$
\delta = \max\{x-x_1, x_2-x\}
$$
What can you say about $f(z)$ for any $z \in (x-\delta, x+\delta)$?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How many directed graphs with N nodes contain a given directed cycle of length L?
Given a directed graph $C$ that only contains a directed cycle of length $L$ (and all resulting sub-cycles), that visits each node at least once,
$$C=(V, D)$$
where $V$ is a fixed set of vertices and $D$ is a set of directed edges, and:
$$|V| = N$$
$$|D| = L$$
$$ 1 \leq \deg^+(v) \leq 2, v \in V$$
How many directed graphs $G=(V,E)$, where $E$ is a set of directed edges and,
$$ \deg^+(v) = 2, v \in V$$
contain $C$? I am not considering $G$ that contains a graph isomorphic to $C$, I am only interested in $G$ that contain exactly $C$.
That is, if F is the set of all G that contain exactly C as a subgraph, and
$$ n = |F| $$
what is n?
A:
Let $a_0,a_1,a_2$ be the vertices with out-degree $0,1,2$ in $C$; so $a_0+a_1+a_2=N$. Following David's advice, it seems that since you're (for now) ignoring the in-degree, the number of graphs is exactly
$$ \binom{N+1}{2}^{a_0} N^{a_1}. $$
Now according to your (current) spec, in fact $a_0 = 0$, and moreover $a_1 + 2a_2 = L$. Since $a_2 = N-a_1$, we get that $a_1 + 2(N-a_1) = L$ and so $a_1 = 2N-L$. Therefore
$$ n = N^{2N-L}. $$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Characteristics of abelian groups
If $A,\ B,\ C$ are each abelian and of infinite cardinality, then is it inherently true that:
$$
(B-C)\times A = (A\times B)-(B\times C)
$$
When I visualize/graph this idea using these sets as an example:
$$
(\mathbb{R}-\mathbb{Z})\times \mathbb{N} = (\mathbb{R}\times \mathbb{N})-(\mathbb{Z}\times \mathbb{N})
$$
I get the same looking graph, but maths can be tricky sometimes and two graphs may not always mean the same thing. Does this work for ALL abelian groups of infinite cardinality?
A:
This is true for any sets, and, as Alejo points in a comment, it has nothing to do with group structure (I think you should take out the tag about groups).
\begin{align}
(B - C) \times A
&= \{ (x,y) : x \in B - C,\, y \in A\}\\
&= \{ (x,y) : x \in B,\, x \notin C,\, y \in A \}\\
&= \{ (x,y) : x \in B, \, y \in A \} - \{ (x,y) : x \in C,\, y \in A\}\\
&= B \times A - C \times A.
\end{align}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove a value from a JavaScript array
I have the following code which when a button is clicked checks to see the previous value stored and concatenates it with the new value - essentially to get a long list of latitudes and longitudes.
(arrayvalues is declared globally)
var previousvalues = document.getElementsByName('arrayvalues')[0].value
arrayvalues = previousvalues + latitude+ "," + longitude+"##";
//alert(arrayvalues);
document.getElementById("arrayvalues").value = arrayvalues;
The document.getElementById stores the new value here:
<input type="text" value="" name="arrayvalues" id="arrayvalues" />
However the issue I am having is the user can at any point undo their last click meaning the last latitude and longitude values stored need removing. How can I go about doing this the way I have coded it?
A:
Use the pop method available for JavaScript arrays, which will remove the last stored element. Here's a brief tutorial on pop():
So if your array is the following:
var coords = [[lat1,long1],[lat2,long2],[lat3,long3]]
Running coords.pop() will result in coords being the following:
[[lat1,long1],[lat2,long2]]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Irreducibility of the derived representation
Let $G$ a linear Lie group with lie algebra $\mathfrak{g}$.
If $(\pi, \mathcal{H})$ is a irreducible representation of $G$. Does the irreducibility of $\pi$ imply the irreducibility of derived representation $d\pi$?
$$d\pi:\mathfrak{g}\longrightarrow End(\mathcal{H}),\,\,
X\longmapsto \frac{d}{dt}\Bigr|_{t=0}\pi(\exp(tX))$$
A:
If all vectors in $\pi$ are differentiable, then yes. It suffices to show that a closed subspace $V \subset \mathcal{H}$ which is invariant under $G$ is also invariant under $\mathfrak{g}$. Let $v \in V$ and let $X \in \mathfrak{g}$. Then by $G$-invariance of $W$, we have $t^{-1}(\pi(\exp{tX})v-v) \in V$ for all $t \in \mathbb{R}^{\times}$. Since $V$ is assumed to by closed, the limit as $t \rightarrow 0$ also belongs to $V$.
If $G$ is conected and $\mathcal{H}$ is finite dimensional a (necessarily closed) subsapce $W$ of $\mathcal{H}$ which is $\mathfrak{g}$-invariant, is also $G$-invaraint.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Translating WIGeoEU projection from ArcGIS to QGIS?
I have a Layer with this projection in ArcGIS:
PROJCS["WIGeoEU",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",10.0],PARAMETER["Standard_Parallel_1",40.0],PARAMETER["Standard_Parallel_2",60.0],PARAMETER["Central_Parallel",30.0],UNIT["Meter",1.0]]
Whenever I try to open it with QGIS, this layer is somewhere out of space and I can't display it together with any other layers which should overlay.
I try to convert this by hand to the format QGIS is using without any success.
That's how the description of the shape looks in QGIS:
Layer Spatial Reference System:
+proj=lcc +lat_1=40 +lat_2=60 +lat_0=0 +lon_0=10 +x_0=0 +y_0=0 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
Is anyone able to help me with my issue?
A:
The value of CENTRAL_PARALLEL = 30.0 has got lost in the conversion.
Try lat_0=30 and see if it fits.
Is the datasource publicly available?
No need to be frustrated, you are not the first one: http://trac.osgeo.org/gdal/ticket/3191
Unfortuantely, the ticket has not got much attention :-(
|
{
"pile_set_name": "StackExchange"
}
|
Q:
¿Cómo obtener el width?
Intento obtener el ancho de un div pero siempre sale el mismo valor, hice un ejemplo para ng-repeat obtengo el mismo valor, ¿qué estoy haciendo mal?
cada que incremento por cada repeat se supone que aumente el ancho como se hace eso?
ojo sin jquery solo js puro
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{
id: 1,
name: "maria"
}, {
id: 2,
name: "juan"
}]
});
var s = document.getElementById('new');
console.log(s.offsetWidth );
#new {
width: 30px;
display: inline-block
}
#dox {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div id="new" ng-repeat="x in records">
<div>{{x.id}}.- {{x.name}}</div>
</div>
</div>
</div>
El width de ng-repeat debería ir aumentando por cada repeat que haga o no?
aqui un grafico:
A:
El problema en tu ejemplo es que el div con id="new" es el que tiene la directiva ng-repeat, esto provoca que se creen n elementos con id="new", con JS buscas el elemento por id (pero siempre obtienes el primero) y es por esto que siempres obtienes el mismo resultado.
Solución simple:
Si el div con id="new" es el que necesitas que contenga los elementos creados con ng-repeat, entonces podrías mover dicha directiva a un span hijo de éste.
Ejemplo:
var app = angular.module("myApp", []);
app.controller("myCtrl", ['$scope', '$timeout', function($scope, $timeout) {
$scope.records = [
{id: 1, name: "maria"},
{id: 2, name: "juan"},
{id: 3, name: "antonio"},
{id: 4, name: "fernando"},
{id: 5, name: "josé"},
{id: 6, name: "julio"},
{id: 7, name: "marisel"},
{id: 8, name: "julia"},
{id: 9, name: "rosario"},
{id: 10, name: "dolores"},
{id: 11, name: "maria"},
{id: 12, name: "juan"},
{id: 13, name: "antonio"},
{id: 14, name: "fernando"},
{id: 15, name: "josé"}
];
$timeout(function() {
var s = document.getElementById('new');
console.log(s.offsetWidth);
});
}]);
#new {
display: inline-block;
white-space: nowrap;
clear: both;
}
#new>span {
margin-right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div id="new">
<span ng-repeat="x in records">{{x.id}}.- {{x.name}}</span>
</div>
</div>
</div>
Solución avanzada:
Para esperar hasta que realmente se hayan renderizado todos los elementos podrías crear una directiva (afterRender) para obtener el ancho.
Ejemplo:
var app = angular.module("myApp", []);
app.directive('afterRender', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: function($scope) {
$timeout($scope.afterRender, 0); //Llamamos al metodo del scope
}
};
}]);
app.controller("myCtrl", ['$scope', function($scope) {
$scope.records = [
{id: 1, name: "maria"},
{id: 2, name: "juan"},
{id: 3, name: "antonio"},
{id: 4, name: "fernando"},
{id: 5, name: "josé"},
{id: 6, name: "julio"},
{id: 7, name: "marisel"},
{id: 8, name: "julia"},
{id: 9, name: "rosario"},
{id: 10, name: "dolores"},
{id: 11, name: "maria"},
{id: 12, name: "juan"},
{id: 13, name: "antonio"},
{id: 14, name: "fernando"},
{id: 15, name: "josé"}
];
$scope.afterRender = function() {
var s = document.getElementById('new');
console.log(s.offsetWidth);
};
}]);
#new {
display: inline-block;
white-space: nowrap;
clear: both;
}
#new>span {
margin-right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div after-render id="new">
<span ng-repeat="x in records">{{x.id}}.- {{x.name}}</span>
</div>
</div>
</div>
A:
Los elementos div siempre tomarán el ancho del elemento padre. Si te fijas, he tomado tu propio código y le he pintado los borders, como ves miden exactamente lo mismo porque tú no les has puesto un ancho fijo.
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{
id: 1,
name: "maria"
}]
});
var s = document.getElementById('new');
console.log(s.offsetWidth + 'xxxxxxxxx');
var s2 = document.getElementById('dox');
console.log(s2.offsetWidth + 'xxxxxxxxx');
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div style="border: 1px solid green;" ng-app="myApp">
<div ng-controller="myCtrl">
<div id="new" ng-repeat="x in records">{{x.id}}.- {{x.name}}</div>
</div>
</div>
<div style="border: 1px solid red;" id="dox">aaaaaaaaaaaaaaaaaaaaa</div>
A:
Según entendí de que quieres poner en forma lineal lo que colocas dentro del div que contiene la información a través del ng-repeat
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{
id: 1,
name: "maria"
}, {
id: 2,
name: "juan"
}]
});
var s = document.getElementById('new');
console.log(s.offsetWidth );
#new {
width: 30px;
display: inline-block
}
#dox {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul id="new" ng-repeat="x in records">
<li>{{x.id}}.- {{x.name}}</li>
</ul>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Почему вылетает exception при десериализации?
Есть класс :
[Serializable]
public class UserAccount
{
public string Name { get; set; }
public string Surname { get; set; }
public string Login { get; set; }
public PasswordBox Password { get; set; }
public UserAccount(string _name, string _surname, string _login, PasswordBox _password)
{
Name = _name;
Surname = _surname;
Login = _login;
Password = _password;
}
}
Метод десериализации:
public void Deserialize()
{
try
{
FileStream fs = new FileStream("..\\..\\Accounts.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
listUsers = (List<UserAccount>)formatter.Deserialize(fs);//вылетает exception
fs.Close();
}
catch
{
listUsers = new List<UserAccount>();
}
}
Ошибка:
Exception thrown: 'System.Windows.Markup.XamlParseException' in
PresentationFramework.dll
Additional information: 'The invocation of the constructor on type 'Gallery.ViewModels.LoginViewModel' that matches the specified
binding constraints threw an exception.' Line number '15' and line
position '10'.
Update
public class LoginViewModel : INotifyPropertyChanged
{
private List<UserAccount> listUsers;
public LoginViewModel()
{
_currentName = String.Empty;
_currentSurname = String.Empty;
_currentLogin = String.Empty;
_currentPasswordBox = new PasswordBox();
Deserialize();
}
private string _currentSurname;
public string CurrentSurname
{
get
{
return _currentSurname;
}
set
{
_currentSurname = value;
OnPropertyChanged();
}
}
private string _currentName;
public string CurrentName
{
get
{
return _currentName;
}
set
{
_currentName = value;
OnPropertyChanged();
}
}
private string _currentLogin;
public string CurrentLogin
{
get
{
return _currentLogin;
}
set
{
_currentLogin = value;
OnPropertyChanged();
}
}
private PasswordBox _currentPasswordBox;
public PasswordBox currentPassword
{
get { return _currentPasswordBox; }
set
{
_currentPasswordBox = value;
OnPropertyChanged();
}
}
private RegistrationCheckCommand checkReg;
public ICommand ButtonClick
{
get { return checkReg ?? (checkReg = new RegistrationCheckCommand(o => AddNewAccount())); }
}
private void AddNewAccount()
{
UserAccount user = new UserAccount(CurrentName, CurrentSurname, CurrentLogin, currentPassword);
listUsers.Add(user);
Serialize();
MessageBox.Show("Account adding!");
}
public void Serialize()
{
try
{
FileStream fs = new FileStream("..\\..\\Accounts.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, listUsers);
fs.Close();
}
catch
{
}
}
public void Deserialize()
{
//try
//{
FileStream fs = new FileStream("..\\..\\Accounts.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
listUsers = (List<UserAccount>)formatter.Deserialize(fs);
fs.Close();
//}
//catch
//{
// listUsers = new List<UserAccount>();
//}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Xaml
<Controls:MetroWindow x:Class="Gallery.LoginWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Gallery.ViewModels"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
mc:Ignorable="d"
Title="Login window" TitleCaps="False" Height="433.735" Width="300.803"
ResizeMode="NoResize"
BorderBrush="White">
<Controls:MetroWindow.Resources>
<local:LoginViewModel x:Key="LoginWindow"/>
</Controls:MetroWindow.Resources>
<Controls:MetroAnimatedTabControl HorizontalAlignment="Center" DataContext="{StaticResource LoginWindow}">
<Controls:MetroTabItem Header="Sign In">
<StackPanel VerticalAlignment="Center">
<TextBlock Text="Login" Foreground="White" FontSize="25" HorizontalAlignment="Center" ></TextBlock>
<TextBox Name="login" Controls:TextBoxHelper.ClearTextButton="True"></TextBox>
<TextBlock Text="Password" Foreground="White" FontSize="25" HorizontalAlignment="Center" ></TextBlock>
<PasswordBox Name="pass" Controls:TextBoxHelper.ClearTextButton="True"></PasswordBox>
<Button Style="{StaticResource AccentedSquareButtonStyle}"
Margin="0,20,0,0" Content="sign in"
IsEnabled="{Binding Text.Length, ElementName=login}">
</Button>
</StackPanel>
</Controls:MetroTabItem>
<Controls:MetroTabItem Header="Registration">
<StackPanel VerticalAlignment="Center">
<TextBlock Text="Login" Foreground="White" FontSize="20"></TextBlock>
<TextBox Name="regLogin" Controls:TextBoxHelper.ClearTextButton="True"></TextBox>
<TextBlock Text="Password" Foreground="White" FontSize="20" ></TextBlock>
<PasswordBox Controls:TextBoxHelper.ClearTextButton="True"></PasswordBox>
<TextBlock Text="Name" Foreground="White" FontSize="20"></TextBlock>
<TextBox Name="regName" Controls:TextBoxHelper.ClearTextButton="True"></TextBox>
<TextBlock Text="Surname" Foreground="White" FontSize="20"></TextBlock>
<TextBox Name="regSurname" Controls:TextBoxHelper.ClearTextButton="True"></TextBox>
<Button Style="{StaticResource AccentedSquareButtonStyle}"
Margin="0,20,0,0" Content="Register" Command="{Binding ButtonClick }">
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource RegistrationFormConverter}">
<Binding ElementName="regLogin" Path="Text.Length" />
<Binding ElementName="regName" Path="Text.Length" />
<Binding ElementName="regSurname" Path="Text.Length" />
</MultiBinding>
</Button.IsEnabled>
</Button>
</StackPanel>
</Controls:MetroTabItem>
</Controls:MetroAnimatedTabControl>
StackTrace
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler
handler, __BinaryParser serParser, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage)
at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream, HeaderHandler handler, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage)
at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream)
at Gallery.ViewModels.LoginViewModel.Deserialize() in
C:\Users\Константин\Documents\Visual Studio
2015\Projects\Gallery\Gallery\ViewModels\LoginViewModel.cs:line
121
A:
Замените тип данного свойства
public PasswordBox Password { get; set; }
на string или любой другой тип, не являющийся коллекцией и помеченный как сериализуемый.
PasswordBox - контрол, контролы не сериализуются с помощью стандартных сериализоторов, т.к. являются рекурсивной коллекцией, т.е. любой контрол содержит коллекцию дочерних котролов, пустую или нет - неважно.
После изменений, удалите файл данных, повторите сериализацию и десериализацию.
С ограничениями может быть использован специальный сериализатор либо ручная сериализация.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
internal server error the server encountered an internal error and was unable to complete your request
I know this isn't exactly python but I just started learning flask as i am done with python. Whenever i try to execute the following line of code i get the 500 error. Can someone please help me. Thank you.
from flask import Flask
app = Flask(__name__)
@app.route('/<name>')
def helloWorld():
return '<h1> Hello {} </h1>'.format(name)
When i do this without name in brackets in route i get no error. But with that i do. What is happening here?
I think the answer should be something like this :
Hello Angad(if angad is provided in the parameter of link)
A:
Your hello function makes use of name, which hasn't been defined anywhere in the function. You must include it in the parameters:
from flask import Flask
app = Flask(__name__)
@app.route('/<name>')
def helloWorld(name):
return '<h1> Hello {} </h1>'.format(name)
This way, Flask can pass the name retrieved from the URL to your function, and your function can use it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to use DataTable.Select() to select Null/ empty values?
My data table filled from db is having empty values in some cells.
The results database SP return has Null in them but in DataTable these values are appearing as '' or empty cells.
Please guide me how to use Select() to select these dbnull/ empty rows.
Thanks
A:
The correct way to check for null is to check for it:
DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");
A:
For one column
DataRow rows = DataTable.Select("[COLUMN 1]=''");
For more than one column
DataRow rows = DataTable.Select("[COLUMN 1]='' OR [COLUMN 2]=''");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between [object method] vs CGRectMake or NSRangeMake
I know that calling a method's instance like [object theMethod] is a message to that instance asking to perform an action (a method named theMethod).
Apple's documentation doesn't help when it comes to CGRectMake.
For example:
When sending a message to an instance the compiler converts a message expression:
[receiver message]
into a call to a messaging function, objc_msgSend.
This function takes the receiver and the name of the method mentioned in the message—that is, the method selector—as its two principal parameters:
objc_msgSend(receiver, selector)
Any arguments passed in the message are also handed to objc_msgSend:
objc_msgSend(receiver, selector, arg1, arg2, ...)
But what about CGRectMake? Where is that function is located? What's the main differences (procedure) when calling the functions?
Update: What about memory? For example blocks are created in the stack. What about CGRectMake?
A:
The difference between methods and “plain functions” is a sad consequence of Objective-C being a relatively simple wrapper around C. Some types that were considered too lightweight to implement as classes were implemented using structs or other more primitive types, and are accompanied by plain C functions or macros to work with them. You can Command-click a function name in Xcode to see the declarations and definitions:
// CoreGraphics / CGGeometry.h
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CGRect CGRect;
CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = width; rect.size.height = height;
return rect;
}
As for the calling differences, you mostly already know them. Messages are translated into objc_msgSend, whereas functions such as CGRectMake are plain C functions or macros with the usual semantics.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ignore case in JDO query
I would like to select a list of results from a database, but the == operator for JDO queries is case-sensitive. Is there a way to select "USER", "user", and "User" from a table using a single parameter?
In MySQL you have the LIKE operator, and in Java the equalsIgnoreCase function. However, neither of them work in this example.
PersistenceManager pm = JDO.factory.getPersistenceManager();
Query query = pm.newQuery(User.class, "username == usernameParam");
query.declareParameters("String usernameParam");
List<User> results = (List<User>) query.execute(username);
A:
You need to store a copy of your field in a case insensitive manner - lower case, for example, though a 'collation case' is better if it's available. Then, query on that.
The reason for this is that there's no way to efficiently search a regular index in a 'case insensitive' manner.
A:
JDOQL has some String methods available. Check the documentation here.
To Fix your issue you could do the following:
PersistenceManager pm = JDO.factory.getPersistenceManager();
Query query = pm.newQuery(User.class, "username.toUpperCase() == usernameParam");
query.declareParameters("String usernameParam");
List<User> results = (List<User>) query.execute(username.toUpperCase());
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SSL_write returns SSL_ERR_SYSCALL while ERR_get_error and errno are both 0
I'm facing a strange problem and the openssl error handling and documentation didn't help.
I use SSL_dup(after an SSL_new), SSL_set_fd and SSL_connect to start an SSL session.
But then when I use SSL_write, it returns 0. The openssl documentation says to check SSL_get_error. I did and it gave me SSL_ERROR_SYSCALL.
The docs also suggest checking error queue and errno. But they are both zero. Now things get intereseting. The documentation says
SSL_ERROR_SYSCALL
Some non-recoverable, fatal I/O error occurred. The OpenSSL error queue may contain more information on the error. For socket I/O on Unix systems, consult errno for details. If this error occurs then no further I/O operations should be performed on the connection and SSL_shutdown() must not be called.
This value can also be returned for other errors, check the error queue for details.
It says it's non recoverable but when I call SSL_write again with the same parameters, it works successfully. But obviously I cannot leave the code like this ignoring the error code of the first call. Here is what I have tried to troubleshoot the problem from what I found on the Internet.
I used select to wait for the underlying socket to become ready for writing.
I checked for EOF on SSL_get_rbio and SSL_get_wbio. BIO_eof returns 0 for both of them.
I tried SSL_do_handshake before calling SSL_write. This may be unnecessary anyway because according the openssl source it is called when I do SSL_connect.
I tried checking SSL_is_init_finished but it returns 1 and doesn't indicate an issue here.
My openssl version is 1.1.1 and I'm on Ubuntu 18.04.3
Why does this problem occurs? How can I find the reason and fix it?
A:
I'm answering my own question as I found what the issue was. It wasn't even an OpenSSL problem.
First, see this GitHub issue: SSL_write() returns SSL_ERROR_SYSCALL when size is 0
My code looks like this,
SSL_write(ssl, foo(), var);
foo creates a payload and returns a const char * and var is the length of that data. The thing is, they are actually member function and member variable of a C++ class and var is set by foo. According to C++ standard, evaluation order of function arguments are not specified. From 5.2.2,
The order of evaluation of arguments is unspecified. All side effects
of argument expression evaluations take effect before the function is
entered.
So, it is possible for the third parameter(var) to be evaluated before the second parameter(foo()). Indeed, it is what was happening according to the assembly output of the program. Below is an example.
class myclass {
public:
int l;
const char *foo(){
l = 10;
return "mystring";
}
};
int main()
{
SSL *ssl;
myclass instance;
SSL_write(ssl, instance.foo(), instance.l);
}
and the assembly,
_ZN7myclass3fooEv:
.LFB1778:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movq %rdi, -8(%rbp)
movq -8(%rbp), %rax
movl $10, (%rax)
leaq .LC0(%rip), %rax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1778:
.size _ZN7myclass3fooEv, .-_ZN7myclass3fooEv
.text
.globl main
.type main, @function
main:
.LFB1779:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
pushq %rbx
subq $40, %rsp
.cfi_offset 3, -24
movq %fs:40, %rax
movq %rax, -24(%rbp)
xorl %eax, %eax
movl -36(%rbp), %ebx
leaq -36(%rbp), %rax
movq %rax, %rdi
call _ZN7myclass3fooEv
movq %rax, %rcx
movq -32(%rbp), %rax
movl %ebx, %edx ; rdx is the third parameter, var. ebx was set before the foo() call
movq %rcx, %rsi ; rsi is the second parameter, return value of foo()
movq %rax, %rdi ; rdi is the first parameter, ssl
call SSL_write@PLT
movl $0, %eax
movq -24(%rbp), %rdx
After SSL_write, foo() is guaranteed to be executed and var is set to the correct value, that's why the SSL_write was working the second time I suppose.
Moreover, the docs for SSL_write says
You should not call SSL_write() with num=0, it will return an error. SSL_write_ex() can be called with num=0, but will not send application data to the peer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there any document of Jhipster entire command list?
I need to get all the commands that jhipster can execute. I am unable to find any proper documentation. Most online tutorials provide only starter commands for Jhipster.
A:
with command :
jhipster -help
I was able to list out many commands that Jhipster supports.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to edit image online on own site
Hot to add functionality to the site that allows users upload, edit online and save images? Edit - resize, rotate, some color effects. Maybe there are some frameworks? The target platform is asp.net mvc 5.
A:
There's a great API you can integrate in your app.
ImageRsizing
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Correctly using stacktrace to debug
The following line of code is causing me an Exception
plug.Instance.AddDocuments(new Int32[] { val_pid }, val_ptype, val_doccat, val_subcat, val_doctype, val_notes, val_summary, SummaryAppendOptions.None, val_docStatus, new String[] { PDFFile })
And this is the exception detail.
System.Exception was caught
Message=Object reference not set to an instance of an object. - Error when trying to save document
Source=SimsBridge
StackTrace:
at SimsBridge.Bridge.AddDocuments(Int32[] personIds, Int32 PersonType, String docCatagory, Int32 subCatagory, String docType, String notes, String summary, SummaryAppendOptions summaryOptions, String documentStatusCode, String[] filePaths)
at ManagedScanDesktop.Form1.SimsScanComplete(String[] files) in C:\Working\ManagedScanDesktop 1.8\v1.8\ManagedScanDesktop\ManagedScanDesktop\Form1.cs:line 2619
InnerException:
I'm not looking for a solution to the actual exception.
My question is, does the stacktrace point to which part of the method doesn't have a reference set? Or is stacktrace just to trace to where the method is called?
A:
The stack trace shows you the call stack when an exception is thrown. From what you've provided you can only deduce that an exception was thrown from AddDocuments. Any of the reference type parameters passed in could be null. The best way to pinpoint the problems is to set a breakpoint and than inspect the values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$scope vs instance variables and methods in controller
I am rewriting my AngularJS application using TypeScript. In my application I have used $scope to define variables and methods:
defectResource.defectByDefectId($scope.defectid).then(function (data) {
$scope.defect = data;
});
$scope.postDefect = function () {
defectResource.postDefect($scope.defect).then(function () {
$location.path('defects/' + $stateParams.itemid);
});
};
I can rewrite my controller something like this:
interface IDefectDetailModel {
}
class DefectDetailController implements IDefectDetailModel {
static $inject = ['$scope', '$stateParams', '$location', 'defectResource', 'entityProvider'];
constructor($scope: any, $stateParams: any, $location: any, defectResource: any, entityProvider: any) {
defectResource.defectByDefectId($scope.defectid).then(function (data) {
$scope.defect = data;
});
$scope.postDefect = function () {
defectResource.postDefect($scope.defect).then(function () {
$location.path('defects/' + $stateParams.itemid);
});
};
}
}
But if I understood correctly it is not good way. I need to create Interface and TypeScript class which will implement this interface. All my variables must be class variables (so $scope.defectid must be this.defectid) and all my $scope methods must be class methods (this.postDefect()).
Do I understood correctly? If I am using AngularJS with TypeScript the best way is not use $scope variables and methods and use only instance variables and methods (using this) ?
A:
If I am using AngularJS with TypeScript the best way is not use $scope variables and methods and use only instance variables and methods (using this) ?
+100.
Key reason being that scope variables are susceptible to become disconnected due to angular's scope inheritance mechanism. Even without TypeScript it is recommended not to use scope varaibles and this is why the controller as syntax was created.
More on Angular controllers in typescript: https://www.youtube.com/watch?v=WdtVn_8K17E
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AES GCM symmetric encryption of data at rest in c#, ciphertext much longer than plaintext
I've written encryption/decryption routines using AES GCM. Code can be found here.
I recently realized that the cipher text is longer than I believe it should be. It should add the tag and IV onto the encrypted plaintext, but the result is still longer than it should be.
Here is the portion of the code doing the encrypting
using (MemoryStream ms = new MemoryStream())
{
using (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
// Write through and retrieve encrypted data.
cs.Write(message, 0, message.Length);
cs.FlushFinalBlock();
byte[] cipherText = ms.ToArray();
// Retrieve tag and create array to hold encrypted data.
byte[] authenticationTag = encryptor.GetTag();
byte[] encrypted = new byte[cipherText.Length + aes.IV.Length + authenticationTag.Length];
// Set needed data in byte array.
aes.IV.CopyTo(encrypted, 0);
authenticationTag.CopyTo(encrypted, IV_LENGTH);
cipherText.CopyTo(encrypted, IV_LENGTH + TAG_LENGTH);
// Store encrypted value in base 64.
return Convert.ToBase64String(encrypted);
}
}
}
Here are two examples of the encryption:
plaintext: example
ciphertext: XtmTBIqKxKdYKWH2zXRUp8jN6etGNUiTyffAFZYV3KB2WVU=
plaintext: much longer example, blah blah blah blah blah
ciphertext: H17hnG4CSmZQ0UeEcY6wirtjW1il+dw7JHqXwWm908Tvb8/+q0E1HerN0chbuUbhL0jLOs8HIpp7ypQQ/ LTacnWW22CyiwAuiA==
The IV is 12 bytes. And I believe the authentication tag is 16 bytes. Why is the cipher text coming out so much longer than expected and how should I fix this issue?
Thank you.
A:
If you go through the math, it appears that exactly the expected amount of ciphertext expansion is happening. Here's what's happening:
The GCM takes the plaintext as a byte string of size N, and generates a ciphertext which is a byte string of size N+28, where 12 of the 28 is the nonce, and the other 16 is the authentication tag.
Then, that octet string undergoes a base-64 encoding, which converts 3 bytes into 4 printable characters; this gives an average ciphertext expansion of a factor of 4/3.
In the first case, you had a plaintext of 7 bytes; after encryption, that gives you a ciphertext of 35 bytes; the base-64 encoding of these 35 bytes would be expected to be 47 bytes long, which is exactly what you see.
In the second case, you had a plaintext of 46 bytes (assuming there's a trailing space to the string you gave); after encryption, that gives you a ciphertext of 74 bytes; the base-64 encoding is then 99 bytes, which is exactly what you see.
Now, you ask how you should fix this issue. Well, the transform is working as designed; what is the issue? If the issue was that you were concerned that something wasn't working properly, well, everything appears to be correct. If the issue was that the ciphertext was too long for your application, well, you'd need to consider how to trim it. Here are some easy ways:
Do you really need the output to be printable? Well, I see you put the 'database' tag on the question; are you encrypting a database field? If so, can the database store arbitrary bytes, or is it restricted only to printable strings? If it can store arbitrary bytes, then you can get rid of a good part of the overhead simply by not base-64 encoding the text. If you do, well, if you're desperate, there are some more aggressive encoding methods (which use more characters in their outputs); going to one of those would save you some small amount.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it better to use pre-existing bad practices, or good practices that don't fit well with old code?
I was thinking of this because I was trying to write an extension for an existing 3rd party software, and their database is horribly denormalized. I needed to use their existing tables and add a bunch of new fields.
I had the option of either creating new tables in their design style (which consists of almost all the propeties being in one big table), or creating a new set of tables alltogether and using something extra such as Triggers to synchronize data between the new and old tables.
I ended up going with the first option of using the existing poor design style, but I was left with this question: Is it better to go with pre-existing bad practices, or to implement good practices that do not play nicely with existing code? Is there some situations where I should choose one over the other?
NOTE: Many answers so far have to do with slowly refactoring the bad code, however I am unable to do that. The code is not ours, and it frequently gets updated by the vendor. I can only build onto it.
A:
You should choose better design if:
You are going to be taking over a large part of future coding
Better design isn't more expensive to the client in the long run. For instance, I have witnessed multi-month "refactorings" for projects that were discontinued by the end of the year.
You should choose "same bad style" if:
You're just helping out. It's unrealistic to think you can take an existing group and will them to higher design standards if you're just a part-time fill-in on the project. Better design is subjective and almost always has a learning curve. If that new design isn't learned by the rest of the team then the project will end up with a mish-mash of styles, and your better designed code may end up in the pile of stuff that nobody changes because they can't understand it. In your example above, what happens if there are updates to the third party software?
Sacrificing "better" design will get you a tangible business advantage. Like adding feature X badly will get you a large contract, but missing the deadline causes you to end up with nothing. This is where the historic conflict between mgmt and the technical team come in. Like renovating a house, someone has to decide when to pay. You can pay down the debt initially by living with no electricity or plumbing for a year. Or you can pay 3x as much with the benefit of having those utilities.
A:
In the long run, it is better to use good practices. It will save time and effort as changes will take less time to implement.
If possible, take little steps to refactor to good practice (for example: in SQL that would be breaking denoramlized tables to normalized one and using views with the old table names).
You will note that I said in the long run - the "quality, time, money" triangle applies here as well (i.e - choose two). If you don't have the time you may have to go with old practices, but this will mean that you are adding to the problem and that your design will also need to be fixed.
If you keep working and adding code of bad design, you will never end up with a codebase that uses good design. As much as possible try to use good design and refactor to good design.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails 3.2 nested route on simple form
I have a nested route between object1 and object2. When I try to edit an object2 I got an error:
undefined method `object2_path' for #<#Class:0x000000040b2fa8>:0x000000029c8810>.
config/routes.rb
resources :object1 do
resources :object2
end
view/object2/_form.html.haml:
= simple_form_for [@object1, @object2] do |f|
If I change the view to add a specific url like:
= simple_form_for [@object1, @object2], :url => object1_object2_path, do |f|
then the edit works but new doesn't.
If instead of object1_object2_path as url I set object1_object2s_path (the index path), both views are rendered but edit fails because the form is pointing to the wrong url (that's obvious, is just a part of the tries I did).
A:
It seems @object1 is nil in this case:
simple_form_for [@object1, @object2] do |f|
So rails attempts to use the object2_path instead of object1_object2_path. Try to check the value of @object1.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find out next character alphabetically?
How we can find out the next character of the entered one. For example, if I entered the character "b" then how do I get the answer "c"?
A:
Try this:
char letter = 'c';
if (letter == 'z')
nextChar = 'a';
else if (letter == 'Z')
nextChar = 'A';
else
nextChar = (char)(((int)letter) + 1);
This way you have no trouble when the char is the last of the alphabet.
A:
How about:
char first = 'c';
char nextChar = (char)((int) first + 1);
A:
Note that a char will implicitly cast to an int. Here's a simplified solution:
char incrementCharacter(char input)
{
return (input == 'z'? 'a': (char)(input + 1));
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I rob the church collection box if I'm not playing a rogue?
I've just picked up the Tithe Box from Dawnbringer Natrisse, who has asked me to deliver it to Brother Merring back in West Harbor. I remember from past playthroughs that it's possible, through some skill checks, to open the box, and skim a little off the top before making the delivery for some bonus XP, Gems, and Gold. Unfortunately, while I seem to be able to buff myself enough to pass the initial Search check, I can't pass the Disable Device check, nor can I pawn it off to Neeshka.
What's the minimum Disable Device skill required to rob the church box? Are there other, further skill checks required that I'm forgetting about? Or is it just flat out impossible to get enough Disable Device from buffs and equipment alone to pass this check as anything other than a Rogue?
A:
Minimum Disable Device skill rank required: 16
It uses the raw skill rank only, and does not take into account any skill buffs or ability bonuses.
To figure this out, I opened up the NWN 2 campaign in the toolset editor, and tracked down the conversation script for the tithe box.
Conversation Script
Click the image to open in the entire window. You may have to click on the image again to zoom in.
Key Points from the Script
gc_skill_rank(19,15) Player can detect the trap if they have a Search skill of 15.
gc_skill_rank(7,16) Player can disarm the trap if they have a Disable Device skill of 16.
gc_skill_rank function
gc_skill_rank(int nSkill, int nRank)
Determine if PC Speaker has sufficient rank in a particular skill.
Parameters:
int nSkill = skill int to check (19 == Search, 7 == Disable Device)
int nRank = minimum rank to return TRUE
gc_skill_rank checks for raw skill ranks only; It does not consider skill buffs or ability bonuses.
Assuming the Player has both a Search skill rank of 15, and a Disable Device skill rank of 16, they will be able to find the trap and disarm it. There are no other conditions in the script that would prevent robbing from the church box.
Achieving the Required Skill Level
Skill Caps
Class Skills: (Character Level + 3)
Cross-Class Skills: (Character Level + 3) / 2 [rounded down]
Four classes have Disable Device as a Class Skill: Rogue, Arcane Trickster, Assassin, Shadow Thief. Your skill cap will stay at Class Skill level as long as you have at least 1 level of one of these classes, even if your current class is different.
So, in order to get your Disable Device skill rank up to 16, you need one to do one of the following:
Be at least character level 13, and one of your classes has to be a Rogue, Arcane Trickster, Assassin, or Shadow Thief of Amn.
Be at least character level 29.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Geography puzzles -- find the one-word answer
Below are two separate puzzles, but you will need to solve both to find the one-word answer.
Good luck!
A:
I think the answer is
Nationalism
Completed crossword
Completed wordsearch
Finally
Reading the unused letters in the wordsearch backwards gives TRANSPARENT which clues overlaying the wordsearch locators on the crossword (the wordsearch is a transparent overlay). This gives the following result
Now rearranging the uncrossed letters give NATIONALISM
Thanks to Mathgeek for suggesting overlaying the images in the comments.
2 down in the crossword
This is about the alphabetical neighbours and not the physical ones.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grunt.js - Running watch two watch tasks together at the same time?
ok, I have setup Grunt to concat and to min all my JS files, I also have set it up to run my sass files. This is working fine, I set up the watch call to watch all .js and .scss files, then it runs the tasks set to each.
I am playing around with backbone.js and therefore have lots of library files to contact each time I make a change to one of the files, this is not a problem in its self but when any of the sass files changed, it would run my closure compiler at the same, even if there had been not change to any of my js files.
So I did some research, and from some questions/answers found on here, it looked like I could set up two watch functions to watch different folders and run set task when the files changed on each watched folder. Simple right? If so I am not sure what went wrong, but it would only watch the first set task, the second it would not watch at the same time?
I know that JavaScript is non-blocking but the watch task is a blocking task, which from how I understand it (please correct me if I am wrong) when my first watch call is started, it stops grunt from running the second watch call?
I then found out about concurrent, which I thought would solve my problem. But it just does the same thing, the first watch call seems the stop the second one from been run, while grunt is watching my first group of folders.
Here is the current grunt file code :
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
options: {
logConcurrentOutput: true
},
target1: ['watch:ScssFiles'],
target2: ['watch:JSFiles']
}, //End of Concurrent
'closure-compiler': {
frontend: {
closurePath: '/usr/lib',
cwd: 'raw_assets/javascript/',
js: ['jquery-2.1.0.js','underscore.js','backbone.js','vars.js','bb_models.js','bb_collections.js','bb_views.js','master.js'],
jsOutputFile: 'assets/js/showcase_master.js',
options: {
compilation_level: 'SIMPLE_OPTIMIZATIONS',
language_in: 'ECMASCRIPT5_STRICT',
}//End of Options
} //End of frontend
}, //End of Closure Compiler
sass: {
dist: {
options: {
style: 'compressed'
}, //End of Options
files: {
'assets/css/Master.css': 'raw_assets/sass/main.scss'
} //End of Files
} //End of Dist.
}, //End of SASS
watch: {
'JSFiles': {
files: [ 'raw_assets/javascript/*.js' ],
tasks: ['closure-compiler'],
options: {
spawn: false,
},
}, //End of Watch call for JS Files
'ScssFiles': {
files: ['raw_assets/sass/*.scss'],
tasks: ['sass'],
options: {
spawn: false,
},
} //End of Watch SCSS Files
} //End of Watch
});
// Load the plugins
grunt.loadNpmTasks('grunt-closure-compiler');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-concurrent');
//When 'Grunt' is run perform watch function
grunt.registerTask('default', ['concurrent:target2', 'concurrent:target1']);#
}; //End of GruntFile
So what I really want, is this grunt file to watch both folders at the same time and only preform the action/task I need when files in that group are changed, is this doable?
I do have (or at lest think I do) have a work around, I am developing on Windows but have a virtual machine running Ubuntu server. I am running my grunt file inside a putty terminal. In which case, I could have two putty terminal, one set to one watch call for js files, the other to watch my scss files. Would this setup just be the easier way of doing it?
All help most welcome.
Glenn.
PS. Sorry if my spelling is off I am dyslexic, also may not have explained things right, so let me know and I will improve my wording, thanks.
A:
grunt-concurrent isn't necessary, grunt-contrib-watch can watch multiple directories in the way you've defined it. I gutted your file to try it out and caught two issues
A hyphen doesn't seem to be allowed in a Grunt task name.
grunt watch doesn't suspend if the directory is empty. Once there's something in there, it will suspend.
Here's the simplified version:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
watch: {
'JSFiles': {
files: [ 'raw_assets/javascript/*.js' ],
tasks: ['closure_compiler'],
options: {
spawn: true,
},
}, //End of Watch call for JS Files
'ScssFiles': {
files: ['raw_assets/sass/*.scss'],
tasks: ['sass'],
options: {
spawn: true,
},
} //End of Watch SCSS Files
} //End of Watch
});
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-watch');
//When 'Grunt' is run perform watch function
grunt.registerTask('closure_compiler', function() {
grunt.log.writeln("in closure_compiler");
});
grunt.registerTask('sass', function() {
grunt.log.writeln("in sass");
});
}; //End of GruntFile
I then ran npm install grunt grunt-cli grunt-contrib-watch, and created the raw_assets directory with javascript and sass subdirectories. I then created a single empty JS file and SCSS file, and ran grunt watch.
Any modifications in either of the two subdirectories run the correct task.
$ grunt watch
Running "watch" task
Waiting...OK
>> File "raw_assets/sass/foo2.scss" added.
Running "sass" task
in sass
Done, without errors.
Completed in 0.381s at Mon Mar 03 2014 00:21:46 GMT+0100 (CET) - Waiting...
OK
>> File "raw_assets/javascript/new.js" added.
Running "closure_compiler" task
in closure_compiler
Done, without errors.
Completed in 0.381s at Mon Mar 03 2014 00:27:50 GMT+0100 (CET) - Waiting...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add org.apache.http.legacy into sbt
I am using apache httpclient and it could not find
import org.apache.http.impl.client.HttpClients;
quick search on google lead me to org.apache.http.legacy but I couldnt find group, artifact and revision of org.apache.http.legacy
What are they and how do I add that dependency into my build.sbt file? Total stacktrace is
[error] /Users/vangapellisanthosh/Development/coupon-engine-play/app/utils/LocalUtils.java:13: cannot find symbol
[error] symbol: class HttpClients
[error] location: package org.apache.http.impl.client
[error] import org.apache.http.impl.client.HttpClients;
[error] /Users/vangapellisanthosh/Development/coupon-engine-play/app/utils/LocalUtils.java:66: cannot find symbol
[error] symbol: variable HttpClients
[error] location: class utils.LocalUtils
[error] HttpClient httpclient = HttpClients.createDefault();
[info] /Users/vangapellisanthosh/Development/coupon-engine-play/app/controllers/CouponsController.java: /Users/vangapellisanthosh/Development/coupon-engine-play/app/controllers/CouponsController.java uses or overrides a deprecated API.
[info] /Users/vangapellisanthosh/Development/coupon-engine-play/app/controllers/CouponsController.java: Recompile with -Xlint:deprecation for details.
[error] (compile:compileIncremental) javac returned nonzero exit code
[info] Compiling 6 Scala sources and 18 Java sources to /Users/vangapellisanthosh/Development/coupon-engine-play/target/scala-2.11/classes...
[error] /Users/vangapellisanthosh/Development/coupon-engine-play/app/utils/LocalUtils.java:13: cannot find symbol
[error] symbol: class HttpClients
[error] location: package org.apache.http.impl.client
[error] import org.apache.http.impl.client.HttpClients;
[error] /Users/vangapellisanthosh/Development/coupon-engine-play/app/utils/LocalUtils.java:66: cannot find symbol
[error] symbol: variable HttpClients
[error] location: class utils.LocalUtils
[error] HttpClient httpclient = HttpClients.createDefault();
[info] /Users/vangapellisanthosh/Development/coupon-engine-play/app/controllers/CouponsController.java: /Users/vangapellisanthosh/Development/coupon-engine-play/app/controllers/CouponsController.java uses or overrides a deprecated API.
[info] /Users/vangapellisanthosh/Development/coupon-engine-play/app/controllers/CouponsController.java: Recompile with -Xlint:deprecation for details.
[error] (compile:compileIncremental) javac returned nonzero exit code
[error] application -
My code is
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(URL);
httppost.addHeader(API_KEY, X_API_KEY);
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(GRANT_TYPE, "password"));
params.add(new BasicNameValuePair(USERNAME, _USERNAME));
params.add(new BasicNameValuePair(PASSWORD, O_PASSWORD));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
System.out.println(instream);
} finally {
instream.close();
}
}
A:
quick search on google lead me to org.apache.http.legacy
Not sure what you searched for, but I know that is a dependency used for Android projects?
What you are looking for can be found at MvnRespository
libraryDependencies += "org.apache.httpcomponents" % "httpclient" % "4.5.2"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Transforming collection using ramda
I want to do the following transformation using ramba
Input collection
const vals = [
{metric: "Sales", measure:100, period_end_date: "2021-12-31", period_type: 'Annual' },
{metric: "EBT", measure:101, period_end_date: "2021-12-31", period_type: 'Annual' },
{metric: "Sales", measure:100, period_end_date: "2021-09-30", period_type: 'Qtr' },
{metric: "EBT", measure:101, period_end_date: "2021-09-30", period_type: 'Qtr' }
]
Output
{
"2021-09-30|Qtr": [{"Sales": 100}, {"EBT": 101],
"2021-12-31|Annual": [{"Sales": 100, }, {"EBT": 101,}]
}
I was able to come pretty close with this
const keyGen = compose(objOf('key'), join('|'), props(['period_end_date','period_type']))// + '|' + prop("period_type",o) }
const valGen = compose(apply(objOf), R.ap([R.prop('metric'), R.prop('measure')]), of )
const f4 = map(compose(apply(merge), R.ap([keyGen, valGen]), of))
const result =compose(groupBy(prop('key')),f4 ) (vals)
This gives me the following result
{"2021-09-30|Qtr": [{"Sales": 100, "key": "2021-09-30|Qtr"},
{"EBT": 101, "key": "2021-09-30|Qtr"}],
"2021-12-31|Annual": [{"Sales": 100, "key": "2021-12-31|Annual"},
{"EBT": 101, "key": "2021-12-31|Annual"}]}
Now I need to remove the key from the inner collections. I wanted to know if there was a better alternative.
A:
R.reduceBy can be used to group items in a list and then reduce each group of items that have the same key.
const vals = [
{metric: "Sales", measure:100, period_end_date: "2021-12-31", period_type: 'Annual' },
{metric: "EBT", measure:101, period_end_date: "2021-12-31", period_type: 'Annual' },
{metric: "Sales", measure:100, period_end_date: "2021-09-30", period_type: 'Qtr' },
{metric: "EBT", measure:101, period_end_date: "2021-09-30", period_type: 'Qtr' }
]
const fn = R.reduceBy(
(list, {metric, measure}) => R.append({[metric]: measure}, list),
[],
({period_end_date, period_type}) => `${period_end_date}|${period_type}`,
)
console.log(fn(vals))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
taking log of very small values using numpy/scipy in Python
I have an Nx1 array that corresponds to a probability distribution, i.e. the sum of the elements sums to 1. This is represented as a regular numpy array. Since N might be relatively large, e.g. 10 or 20, many of the individual elements are pretty close to 0. I find that when I take log(my_array), I get the error "FloatingPointError: invalid value encountered in log". Note that this is after setting seterr(invalid='raise') in numpy intentionally.
How can I deal with this numerical issue? I'd like to represent vectors corresponding to a probability distribution and their take log without rounding to 0, since then I end up taking log(0) which raises the error.
thanks.
A:
You can just drop the tails according to the accuracy you need.
eps = 1e-50
array[array<eps]=eps
log(array)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to access an external stylesheet through the Document interface in Java?
I have an interface reference (instanceof Document) pointing to a valid object. The problem is that I want to view the style attribute associated with a particular element in DOM, but it will only expose inline attributes (while style has been set through an external stylesheet). The end goal is to acquire a reference to ViewCSS, as I want to view the associated computed style - how would I do this? I'm presuming, that acquiring a DocumentView object might be needed (if so, how, as I did not find any method that will return the aforementioned object)?
Document document = ...;
document.getImplementation().hasFeature("Views", "2.0"));
this returns true.
Object obj = document.getImplementation().getFeature("Views", "2.0");
this throws an java.lang.UnsupportedOperationException: Not supported yet.
What am I doing wrong, how to fix it and what is the best way to go about this (I want to view/change the associated computed style for this document)? Thank you.
Edit:
I think this is an important part of details that should have been provided initially:
java.lang.UnsupportedOperationException: Not supported yet.
at com.sun.webpane.webkit.dom.NodeImpl.getFeature(Unknown Source)
the Document object returned was from a javafx package triggered on WebEngine.
A:
May be this fragment solves your problem:
Document doc = ???;
HTMLDocument htmlDoc = (HTMLDocument)doc;
final HTMLBodyElement body = (HTMLBodyElement)htmlDoc.getBody();
//JS [window] access
DOMWindowImpl wnd =
(DOMWindowImpl)((DocumentView)htmlDoc).getDefaultView();
//Style access
CSSStyleDeclaration style = wnd.getComputedStyle(body, "");
assertEquals("Style extraction", "blue", style.getPropertyValue("background-color"));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to teach a 4 year-old-child to handle tantrums?
My 4 year old son only accepts appreciation, he cannot accept "No,Don't..".
A few neighbor kids came home to play with my son, he slightly tapped a 2 year old friend in his head, a 12 year girl who saw it told me "aunt, your son is beating him". On hearing this my son got angry, went alone to the open terrace.
When he was playing with toys by building a tower, his 2 year-old friend pushed his tower over, then he threw a piece upon his friend. If his friend sits in his chair he pulls him in anger. If I am supporting his friends he shouts. Even in a crowd if any advice is given he shouts or sits down, removes his footwear.
I told him "If you beat or touch your friends, I will not allow them to play with you." He said no, I will not fight. Next time when his friend asks for the toy he has, he pulls him or throws the toy upon him and shouts.
He is a single child and whether that is the problem with sharing.
A:
I see two things happening in your story
1) you can't reason with kids. There is no next time. So if you say behave or next time no friends that doesn't work. The only thing you can do is respond to what you are seeing now (punch a kid, get a timeout)
2) kids do anything for attention, even negative attention. So if daughter shouts I'll ignore her. I might say something like "I can't hear you over the shouting" or "if someone wants to whisper for a cookie". But generally i ignore shouting or pick them up and move them to the hall (and ignore them)
Ow and there is no slightly tapping other kids. There is touching and not touching. Especially if he gets your sympathy when someone points it out
A:
4 year-old-child only accepts appreciation he cannot accept
"No,Don't.."
Okay, then change how you phrase things. Don't tell kids what you don't want them to do, tell them what you want them to do.
Don't say "Don't hit". Say "Play nice" or "play gentle".
On hearing this my son got angry went alone to open terrace.
Leaving a stressful situation instead of melting down in place? That's actually pretty mature behavior.
If I advice him that if you are beating or touching your friends I
will not allow them to play with you.
This isn't really going to work at this age. He can't think ahead to far away consequences like that. He's acting on impulse.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is $\partial (A)$ and $\overline{A}$ of the following space?
Consider in $\mathbb R$ the topology $\mathscr{T}$ generated by the basis $\mathscr{B}=\{[a, b): a, b\in\mathbb R, a<b\}$. What would be the closure and the boundary of the set $A=(0, 1]\times [0, 1)\subset \mathbb R\times \mathbb R$ where $\mathbb R\times \mathbb R$ is endowed with the product topology determined by $\mathscr{T}$.
I know $\overline{(0, 1]\times [0, 1)}=\overline{(0, 1]}\times \overline{[0, 1)}$ and I think $[0,1)$ is closed so that $\overline{[0, 1)}=[0, 1)$. As to $\overline{(0, 1]}$ I'm not sure but I guess it is $[0, 1]$.
I have already proven $\textrm{int}((0, 1]\times [0, 1))=(0, 1)\times [0, 1)$ so it is easy to find $\partial(A)$ if I know $\overline{A}$.
Any help will be valuable!
Thanks!
A:
Your thoughts so far are spot on! To see why $\overline{(0,1]}=[0,1],$ note/prove first that $[0,1]$ is closed under the topology $\mathscr{T}.$ Thus, $\overline{(0,1]}\subseteq[0,1].$ Now, if $U$ is a $\mathscr{T}$-open set containing $0,$ can you show that $U$ must intersect $(0,1]$? That will prove that $0$ is an element of $\overline{(0,1]},$ and so the reverse inclusion follows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ckeditor and rails 3 app. formatted text not displaying as it should be
I am using ckeditor for rails 3 and I have it set up already in form, works nice except the view part, when I go to the model show page I tags that I used for text formatting but there is no bold font or any other modifications I did to the text. Where is the problem? Do I have to put something next to the field that is rendering this text like I did in form?
code for form that works just fine
<div class="field">
<%= f.cktext_area :comments, :cols => 80, :rows => 20 %>
</div>
and in show.html.erb
<p style="margin-left:5px;text-align:justify;padding:5px;"><%= @car.comments %></p>
<p> <em>The 2011 Cadillac Escalade ranks 1 out of 9 Luxury Large SUVs. This ranking is
based on our analysis of 86 published reviews and test drives of the Cadillac Escalade, and
our analysis of reliability and safety data.The 2011 Cadillac Escalade is not for shrinking
violets. It’s an SUV for buyers who like to be noticed, but who also need the
capabilities of a full-sized truck-based SUV – and are willing to pay to get them.
</em>
That is the result, as you see there are tags around the text but they are escaped.
Thanks for your time.
A:
OK. I got it. I just needed the raw before the field. for example <%= [email protected] %> or
<%= raw(car.comments) %> depending where you need them. Thanks to Google :).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I run a static constructor?
I'd like to execute the static constructor of a class (i.e. I want to "load" the class) without creating an instance. How do I do that?
Bonus question: Are there any differences between .NET 4 and older versions?
Edit:
The class is not static.
I want to run it before creating instances because it takes a while to run, and I'd like to avoid this delay at first access.
The static ctor initializes private static readonly fields thus cannot be run in a method instead.
A:
The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (i.e. reflection), you can use RunClassConstructor:
Type type = ...;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
A:
Just reference one of your static fields. This will force your static initialization code to run. For example:
public class MyClass
{
private static readonly int someStaticField;
static MyClass() => someStaticField = 1;
// any no-op method call accepting your object will do fine
public static void TouchMe() => GC.KeepAlive(someStaticField);
}
Usage:
// initialize statics
MyClass.TouchMe();
A:
The cctor (static constructor) will be called whenever one of the following occurs;
You create an instance of the class
Any static member is accessed
Any time before that, if BeforeFieldInit is set
If you want to explicitly invoke the cctor, assuming you have other static members, just invoke/access them.
If you are not doing anything very interesting in your cctor, the compiler may decide to mark it BeforeFieldInit, which will allow the CLR the option to execute the cctor early. This is explained in more detail here: http://blogs.msdn.com/davidnotario/archive/2005/02/08/369593.aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
__NSCFString size Error when calling image out of dictionary and into imageview
I've got multiple pieces of JSON'd data being pulled into an array called "jsonArray". I'm calling each of the text items out of the array and displaying them in UILabels successfully. But, the image that is in jsonArray is not playing well with the imageview on my view controller. I can see that the data for the image is being stored successfully:
The error that I'm receiving is "reason: '-[__NSCFString size]" I'm not sure where to go from here. My code is below. (I've got dynamic prototype cells, so I have created a separate class for the cell itself.)
FeedTableViewController.m
NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/json2.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
NSError *error;
jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
[tableView reloadData]; // if tableView is unidentified make the tableView IBOutlet
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"needCard" forIndexPath:indexPath];
NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
cell.textNeedTitle.text = [needs objectForKey: @"needTitle"];
cell.textNeedPoster.text = [needs objectForKey: @"needPoster"];
cell.textNeedDescrip.text = [needs objectForKey: @"needDescrip"];
cell.imageProfPic.image = [needs objectForKey:@"userImage"];
return cell;
}
NeedCardTableViewCell.h
@interface NeedCardTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *textNeedTitle;
@property (weak, nonatomic) IBOutlet UILabel *textNeedPoster;
@property (weak, nonatomic) IBOutlet UILabel *textNeedDescrip;
@property (weak, nonatomic) IBOutlet UIImageView *imageProfPic;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
A:
So what exactly is [needs objectForKey:@"userImage"]; returning? Is its a string of a URL, or a block of data?
If its a block of data then you might say something like: cell.imageProfPic.image = [UIImage imageWithData:[needs objectForKey:@"userImage"]];
If its a URL string then you should asynchronously load it and then update using the data when its ready.
EDIT: Now that I know its a string, the following will work
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSURL *url = [NSURL URLWithString:[needs objectForKey:@"userImage"]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how can i import a project to cakephp?
I have my cakephp in this path of my computer C:\xampp\htdocs\cakephp and everything work fine, i made a few exercises and examples to know and learn more of cakephp and that projects and examples works fine too but her is the question, now i have other project with whole files how comes cakephp (app,lib,plugin,vendors etc..) this files running fine but i need to see his functionality because i need to modified or add some features (this is my goal) but i dont know how import or modified the route.php file in cakephp for use this whole project in my localhost.
One idea through my mind is take every single model,ctp file component etc.. and copy and paste from this new project to my cakephp but i dont have a very good feel about this idea, if some one could help me i'm going to be very grateful and thanks
A:
From your question, I am getting that you want to maintain an existing CakePHP project.
Why don't you take a backup of the original working project, make a copy of it (with a different name in your XAMPP) and work on it? Once satisfied, you can present the new copy as the final project. You may have to change some settings to make the copied project work.
In other words, if you can get one project to work on XAMPP, why not just take a backup, then edit it as per the requirements.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Best way to return a string from an HTTPHandler to a page that POSTs this .ashx file
I have an ASP.Net HTTPHandler that gets POSTed from a ColdFusion web page whose FORM looks something like:
<form name="sendToHandler" action="http://johnxp/FileServiceDemo2005/UploadHandler.ashx" method="post">
<input type="hidden" name="b64fileName" value="fileservice.asmx.xml" />
<input type="hidden" name="strDocument" value="Document" />
<input type="submit" name="submitbtn" value="Submit" />
What is the best way for this .Net Handler to return a string to the POSTing ColdFusion page?
EDIT update Aug 14, 2009:
The solution I came up in my .ashx file involves saving the URL of the .cfm file that POSTed my handler and appending a querystring with the result string(s) that I want to communicate back to ColdFusion. My CF colleague uses the presence or absence of this querystring data to format the .cfm webpage accordingly:
public void ProcessRequest(HttpContext context)
{
string returnURL = context.Request.ServerVariables["HTTP_REFERER"]; // posting CFM page
string message = UploadFile(context); // handles all the work of uploading a file
StringBuilder msgReturn = new StringBuilder(returnURL);
msgReturn.Append("?n=");
msgReturn.Append(HttpUtility.UrlEncode(TRIMrecNumAssigned));
msgReturn.Append("&m="); // this is just a msg with performance data about the upload operation (elapsed time, size of file, etc.)
msgReturn.Append(HttpUtility.UrlEncode(message));
context.Response.Redirect(msgReturn.ToString());
}
A:
Just write the string directly to the response object in your ProcessRequest method.
public void ProcessRequest(System.Web.HttpContext context)
{
context.Response.Write(mystring);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get a particular module's information programmatically
Is there any function to retrieve all the hook used by a particular
module and also
A function to return all menu links (along with its description) created by
a particular module
I looked into module_hook and module_implements but both
were used to find whether a particular hook is used in a module. But
what I need is vice versa.
I need it because configuration options for a particular module can be easily found by getting menu links in a page as a overview.
A:
No - as you've already discovered, the association is the other way around (i.e. a list of modules against each hook, not a list of hooks against each module). Nothing in Drupal's core needs to know a list of all hooks a module implements, so no such function exists. As there's no requirement for a module to declare which hooks it provides (though they can through hook_hook_info()), such a function would be difficult or impossible to implement reliably.
If you can trust that all the modules you have installed are well documented, you could write something that looks in the comment block of each function for Implements hook_, and build a list yourself that way. Or you could compile a list of all the hooks you're interested in knowing about, run each of them through module_implements, and build your list.
Assuming by "menu link" you mean a path provided by a module that has the default menu type, and will subsequently appear in a menu automatically, something like this will do it for all modules:
$menu_items = array();
foreach (module_implements('menu') as $module) {
$func = $module . '_menu';
if (function_exists($func)) {
foreach ($func() as $router_path => $item) {
if ($item['type'] == MENU_NORMAL_ITEM) {
$menu_items[$module][$router_path] = $item['title'];
}
}
}
}
That will probably need to be be tweaked for your requirements.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Credential match from Plist
I have a plist with Array title and item0,item1,item2 is dictionary to store title and password of my app.now i want to check for signin process
now i Want to check for pass and items should be matched when i press submit button to login.i Tried the below code but xcode crashes
-(void)authenticateCredentials
{
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
if ([[[plistArray objectAtIndex:i]objectForKey:@"pass"]isEqualToString:emailTextFeild.text] && [[[plistArray objectAtIndex:i]objectForKey:@"title"]isEqualToString:passwordTextFeild.text])
{
NSLog(@"Correct credentials");
return;
}
NSLog(@"INCorrect credentials");
}
}
and
-(NSArray*)readFromPlist
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *valueArray = [dict objectForKey:@"title"];
return valueArray;
}
the xcode gets crashs ..please check in -(void)authenticateCredentials where i am incorrect?
AND
Crash when I select the submit button,Its wont give any output correct or incorrect in nslog and Xcode crash then , with errorr
2012-12-14 12:10:45.142 NavTutorial[1661:f803] emailEntry: [email protected]
2012-12-14 12:10:45.145 NavTutorial[1661:f803] passwordEntry: hellohello
2012-12-14 12:10:45.153 NavTutorial[1661:f803] -[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x1568cd8
2012-12-14 12:10:45.155 NavTutorial[1661:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x1568cd8'
*** First throw call stack:
(0x14d7052 0x11c2d0a 0x14d8ced 0x143df00 0x143dce2 0x3981 0x14d8ec9 0x3735c2 0x37355a 0x418b76 0x41903f 0x417e22 0x39893f 0x398c56 0x37f384 0x372aa9 0x1bcdfa9 0x14ab1c5 0x1410022 0x140e90a 0x140ddb4 0x140dccb 0x1bcc879 0x1bcc93e 0x370a9b 0x211d 0x2095 0x1)
terminate called throwing an exception
and
two days ago this same code worked fine
and if i put Breakpoint for IF condition and later if fails just after if condition.
A:
Modify your authenticateCredentials as shown below and check if it is working. If it is showing an error message as Error! Not a dictionary, you need to check if your plist is having correct structure. Mostly your [objDict objectForKey:@"pass"] is returning a different data type.
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:@"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:@"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(@"Correct credentials");
return;
}
NSLog(@"INCorrect credentials");
} else {
NSLog(@"Error! Not a dictionary");
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why won't the JPanel change color and stay that way?
I'm working on a assignment for school but I got a problem :P.
I got this code:
public void mouseEntered(MouseEvent e) {
MyPanel b = (MyPanel)e.getSource();
System.out.println("ID: "+b.getId()+"");
b.setColor(Color.blue);
}
In the MyPanel object I got:
public void setColor(Color kleur) {
if(this.getBackground()==Color.white) {
this.setBackground(kleur);
repaint();
}
}
When I enter the panel with my mouse the color flashes that I entered. But I want it to stay the color so I can draw a trail in a Jform with 500 Jpanels(I've added them to a ArrayList but this part works just fine)
What am I doing wrong?
A:
Based on @ErickRobertson's comment on the question, I guess the problem is the following:
Your MyPanel replaces the JPanel#paintComponents() method. Is that possible? If so, you could do the following. In your MyPanel#setColor(Color) method, you don't set the background, but a field containing your new background color:
private Color backgroundColor = Color.white;
public void setColor(Color kleur) {
backgroundColor = kleur;
repaint();
}
Then, in your MyPanel#paintComponents(Graphics):
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// draw background
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
// draw your stuff here
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Assigning Carbon NMR
I have a molecule and I need to assign the carbon NMR to each of the carbons.
My molecule is
The peaks I have for the carbon NMR are shown below. I have also used the DEPT to work out if it's a $\ce{CH3}$, $\ce{CH2}$, $\ce{CH}$ or quaternary C.
17.7ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH3}$)
19.5ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH3}$)
25.5ppm $\ce{CH2}$
25.7ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH3}$)
32.1ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
36.7ppm $\ce{CH2}$
39.7ppm $\ce{CH2}$
66.0ppm $\ce{CH2}$
122.1ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
124.4ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
128.2ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
128.3ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
128.6ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
131.5ppm quaternary carbon
136.2ppm quaternary carbon
149.0ppm $\ce{CH3}$ or $\ce{CH}$ (I think this is $\ce{CH}$)
166.4ppm quaternary carbon
I think I can assign the quaternary carbon with the $\ce{C=O}$ in the ester as the 166.4ppm.
Out of the three methyl groups, would the lowest ppm of 17.7ppm be the one at the top of the molecule by itself and then would the other two at the bottom of the molecule on the alkene be 19.5ppm and 25.7ppm? I don't know which one is which, I know it is to do with cis/trans but I'm not sure which way around it is.
I also know that on the benzene ring, only three $\ce{CH}$ peaks show up as the two ortho and the two meta carbons are equivalent.
A:
If this is a real sample, and not a provided coursework spectrum, then the best recommendation is to run a HSQC and/or HMBC. This will provide complete data to allow this assignment fully, and in much the same time as it takes to run a DEPT135. I don't understand the urge to run DEPTS any more - I haven't run one for years. A phase edited HSQC will give you all of the information that a DEPT can provide, as well as connectivities between proton and carbons. Anyway, off my soapbox.
Below is a simulation of this molecule, which has reasonable alignment with your peaks.
A methyl centre trans to a alkyl chain will be downfield shifted to an equivalent methyl group trans to a proton. So 19 will be downfield shifted from 20, and be fairly similar in chemical shift to 16. Simulations have their limitations, and carbon shifts are solvent dependent to +/- a few ppm at least. To avoid any uncertainty, run HSQC and HMBC. These should be part of your normal procedure for assigning structures.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Restlet Client :: how to add filters?
I suffering of a lack of documentation on the use of Restlet at the client side.
I am getting a resource on server via a ClientResource:
new ClientResource(url).get();
But the server can return an ETag header. To handle this I want to save the ETag when returned and send it back to the server when using the same url.
Currently I am doing it like this:
ClientResource clientResource = new ClientResource(url);
addEtag(url, clientResource); // add the cached ETag to the query if any
clientResource.get();
saveEtag(url, clientResource); // cache the ETag if any
I would like to do this using the Restlet framework. I am searching for days wihtout understanding the missing link.
I can extend an application, overwrite the createOutboundRoot() method and return a filter:
public class RestLetClient extends Application {
private Client client;
// instantiation of the client and other things here
@Override
public Restlet createOutboundRoot() {
return new Filter(getContext(), client){
@Override
protected int beforeHandle(Request request, Response response) {
addEtag(request);
return super.doHandle(request, response);
}
@Override
protected void afterHandle(Request request, Response response) {
saveEtag(request, reponse);
return super.afterHandle(request, response);
}
};
}
}
BUT how can I use this filtering around the Restlet client from my business code?
EDIT
The best I could get to work until now is this:
Request request = new Request(Method.GET, uri);
//the filter created in original post
filter.handle(request).getEntity();
This works but it is not integrated in the framework. What I am achieving to do is at the client side what is only documented for the server side. On the server you would do:
public class ServerApplication extends Application {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach(GET_URL, GetResource.class);
return router;
}
}
and then start the server. The application will the be triggered on the reception of a GET request on the url.
What is the equivalent on the client side? How can I trigger a Client Application? If I have an Application running at the client side I can nicely add filters where they belong in a REST application
EDIT 2
When trying to run my client within an Application I get the error: The filter org.restlet.engine.application.RangeFilter@f372a7a was executed without a next Restlet attached to it.
Here is how I am getting the error. I have a class extending Application that is called from a JUnit test:
public class RestLetClient extends Application {
private final Client client;
Logger logger = LoggerFactory.getLogger(getClass());
public RestLetClient() {
this.client = new Client(Protocol.HTTP);
}
public Representation get(final String uri) throws Exception {
Request request = new Request(Method.GET, uri);
Response response = handle(request);
return response.getEntity();
}
@Override
public Restlet createOutboundRoot() {
return new Filter(getContext(), client) {
@Override
protected int beforeHandle(Request request, Response response) {
addEtagFilter(request);
return super.beforeHandle(request, response);
}
@Override
protected void afterHandle(Request request, Response response) {
saveEtagFilter(request, response);
super.afterHandle(request, response);
}
};
}
private void saveEtagFilter(Request request, Response response) {
logger.debug("saving etag");
}
private void addEtagFilter(Request request) {
logger.debug("adding etag");
}
}
and the unit with a single test method:
public class RestLetClientTest {
public static final String URL = "http://localhost:8123/resource";
private RestLetClient instance;
private Server server;
@Before
public void setUp() throws Exception {
server = new Server(Protocol.HTTP, 8123, new TestApplication());
server.start();
instance = new RestLetClient();
instance.start();
}
@After
public void tearDown() throws Exception {
instance.stop();
}
@Test
public void testGet() throws Exception {
Representation representation = instance.get(URL);
System.out.println(representation.getText());
}
private class TestApplication extends Application {
@Override
public Restlet createInboundRoot() {
return new Router().attach(RestLetClientTest.URL, GetResource.class);
}
}
private class GetResource extends ServerResource {
@Get
public Representation getResource() {
return new StringRepresentation("hello world");
}
}
}
What am I doing wrong?
A:
I had a much nicer answer from a colleague. I post it here for the documentation.
The solution is to use a ClientResource, a Filter and a Client.
The Filter becomes the next() of the ClientResource and the Client the next() of the Filter.
public class ETagFilter extends Filter {
@Override
protected int beforeHandle(Request request, Response response) {
addEtag(request);
return super.beforeHandle(request, response);
}
@Override
protected void afterHandle(Request request, Response response) {
saveEtag(request, reponse);
super.afterHandle(request, response);
}
}
public class RestLetClient extends Application {
public Representation get(final String uri) throws Exception {
Client client = new Client(Protocol.HTTP);
ETagFilter eTagFilter = new ETagFilter();
clientResource = new ClientResource(uri);
clientResource.setNext(eTagFilter);
eTagFilter.setNext(client);
return clientResource.get(halMediaType);
}
}
For info. In my OP I was trying to transform code meant for server side into client side. That approach was wrong. My colleague pointed that the approach is much more like the use Apache HttpClient for similar needs
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MVC Controls Toolkit DatePicker with Razor doesn't render Calendar
I have tried following the documentation and examples of MVC Controls Toolkit to create a DatePicker but I can't get it to work.
I wonder if anyone can point me to what I am doing wrong please? Or provide a code example?
I am using Razor for my implementation with MVC3ControlsToolkit.dll...
@Html.DateTimeFor(model => model.Date, DateTime.Now);
I've updated my code to the one below, I get an empty textbox but no calendar pops up if I click in the text box. The documentation is not clear to me although I read it a few times! Following the docs, I have created a reference to MVC3ControlsToolkit.dll, MVCControlToolkit.Controls.Core-2.2.0.js and MVCControlToolkit.Controls.Datetime-2.2.0.js.
I want to get a populated textbox with the date in DB (this works in the normal textbox, but not the calendar control yet!) and when I click in the textbox, I want the calendar control to show up. When I select a date from the calendar, the selected date will be written to the textbox and the calendar will close.
@{ var DT = @Html.DateTimeFor(model => model.Date, DateTime.Now, dateInCalendar: true); }
@DT.DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions
{
ChangeYear = true,
ChangeMonth = true,
})
A:
DateTimeFor return an object that you can use for both data and time.
@Html.DateTimeFor(model => model.Date, DateTime.Now).Date()
should work.
or
@{
var DTS=Html.DateTimeFor(model => model.Date, DateTime.Now);
}
Then place date and time wherever you like with @DTS.Date() and @DTS.Time()
if you want a date picker:
@{
var DT = @Html.DateTimeFor(model => model.Date, DateTime.Now, dateInCalendar: true);
}
and then:
@DT.DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions{
ChangeYear = true,
ChangeMonth = true,
});
Please refer to the examples in the documentation for more details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to access app configuration from a .dll?
I recently broke out a part of my winform app in a .dll. Some of the classes in that dll
wants fetch/store user settings.
The classes just used the VS generated Settings file so it just did
Properties.Settings.Default.SomeSetting = var;Properties.Settings.Default.Save() etc.
What are my options now that I moved that code out to a class library/.dll ?
A:
The hosting application should handle the interface to the config file, not the DLL. Either
Pass whatever settings need to be read/modified within the DLL as parameters, or
Pass in a name-value collection of settings that can be modified by the DLL, and save whatever changes are made by the DLL to the collection when control returns to the calling application.
This is similar in principle to removing a database interface from the business layer of a tiered application and encapsulating it into a data layer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to stop God from leaving stale Resque worker processes?
I'm trying to understand how to monitor the resque worker for travis-ci with god in such a way that stopping the resque watch via god won't leave a stale worker process.
In the following I'm talking about the worker process, not forked job child processes (i.e. the queue is empty all the time).
When I manually start the resque worker like this:
$ QUEUE=builds rake resque:work
I'll get a single process:
$ ps x | grep resque
7041 s001 S+ 0:05.04 resque-1.13.0: Waiting for builds
And this process will go away as soon as I stop the worker task.
But when I start the same thing with god (exact configuration is here, basically the same thing as the resque/god example) like this ...
$ RAILS_ENV=development god -c config/resque.god -D
I [2011-03-27 22:49:15] INFO: Loading config/resque.god
I [2011-03-27 22:49:15] INFO: Syslog enabled.
I [2011-03-27 22:49:15] INFO: Using pid file directory: /Volumes/Users/sven/.god/pids
I [2011-03-27 22:49:15] INFO: Started on drbunix:///tmp/god.17165.sock
I [2011-03-27 22:49:15] INFO: resque-0 move 'unmonitored' to 'init'
I [2011-03-27 22:49:15] INFO: resque-0 moved 'unmonitored' to 'init'
I [2011-03-27 22:49:15] INFO: resque-0 [trigger] process is not running (ProcessRunning)
I [2011-03-27 22:49:15] INFO: resque-0 move 'init' to 'start'
I [2011-03-27 22:49:15] INFO: resque-0 start: cd /Volumes/Users/sven/Development/projects/travis && rake resque:work
I [2011-03-27 22:49:15] INFO: resque-0 moved 'init' to 'start'
I [2011-03-27 22:49:15] INFO: resque-0 [trigger] process is running (ProcessRunning)
I [2011-03-27 22:49:15] INFO: resque-0 move 'start' to 'up'
I [2011-03-27 22:49:15] INFO: resque-0 moved 'start' to 'up'
I [2011-03-27 22:49:15] INFO: resque-0 [ok] memory within bounds [784kb] (MemoryUsage)
I [2011-03-27 22:49:15] INFO: resque-0 [ok] process is running (ProcessRunning)
I [2011-03-27 22:49:45] INFO: resque-0 [ok] memory within bounds [784kb, 784kb] (MemoryUsage)
I [2011-03-27 22:49:45] INFO: resque-0 [ok] process is running (ProcessRunning)
Then I'll get an extra process:
$ ps x | grep resque
7187 ?? Ss 0:00.02 sh -c cd /Volumes/Users/sven/Development/projects/travis && rake resque:work
7188 ?? S 0:05.11 resque-1.13.0: Waiting for builds
7183 s001 S+ 0:01.18 /Volumes/Users/sven/.rvm/rubies/ruby-1.8.7-p302/bin/ruby /Volumes/Users/sven/.rvm/gems/ruby-1.8.7-p302/bin/god -c config/resque.god -D
God only seems to log the pid of the first one:
$ cat ~/.god/pids/resque-0.pid
7187
When I then stop the resque watch via god:
$ god stop resque
Sending 'stop' command
The following watches were affected:
resque-0
God gives this log output:
I [2011-03-27 22:51:22] INFO: resque-0 stop: default lambda killer
I [2011-03-27 22:51:22] INFO: resque-0 sent SIGTERM
I [2011-03-27 22:51:23] INFO: resque-0 process stopped
I [2011-03-27 22:51:23] INFO: resque-0 move 'up' to 'unmonitored'
I [2011-03-27 22:51:23] INFO: resque-0 moved 'up' to 'unmonitored'
But it does not actually terminate both of the processes, leaving the actual worker process alive:
$ ps x | grep resque
6864 ?? S 0:05.15 resque-1.13.0: Waiting for builds
6858 s001 S+ 0:01.36 /Volumes/Users/sven/.rvm/rubies/ruby-1.8.7-p302/bin/ruby /Volumes/Users/sven/.rvm/gems/ruby-1.8.7-p302/bin/god -c config/resque.god -D
A:
You need to tell god to use pid file generated by rescue and set pid file
w.env = {'PIDFILE' => '/path/to/resque.pid'}
w.pid_file = '/path/to/resque.pid'
env will tell rescue to write pid file, and pid_file will tell god to use it
also as svenfuchs noted it should be enough to set only proper env:
w.env = { 'PIDFILE' => "/home/travis/.god/pids/#{w.name}.pid" }
where /home/travis/.god/pids is the default pids directory
|
{
"pile_set_name": "StackExchange"
}
|
Q:
archive todos from org agenda
I make a function that move from TODO state to DONE and archive it in the archives files, and I set org-mode-map to make this function by a keybinding, but in agenda it doesn't change the TODO state. I tried to find a org-agenda-mode-map or something similar but I can't find it. My function is:
(defun mark-done-and-archive ()
(interactive)
(org-todo 'done)
(org-archive-subtree))
(define-key org-mode-map "\C-c\C-x\C-s" 'mark-done-and-archive)
EDIT
So when in my TODOS.org file I hit C-c C-x C-s the todo automatically is marked as DONE and move from TODOS.org to archive.org but when I make this in org-agenda buffer the todo is moved from his file well, the only problem is that it isn't marked as done. As example:
Archive todos.org
* TODO one todo from todo.org
* TODO Another todo
So I open todos.org and complete the first todo so I hit C-c C-x C-s and the file todos.org now contains:
* TODO Another todo
and archive.org contains:
DONE one todo from todo.org
But when I show my org-agenda and * TODO Another todo it's show, I try to complete and move to my archive file, again with C-c C-x C-s but I obtain the following in archive.org:
* DONE one todo from todo.org
* TODO Another todo
and todos.org it's empty.
A:
org-mode maintains two sets of functions for most things. The 'normal' version (like org-todo) and the agenda version (org-agenda-todo). If you rewrite your function to use the agenda version, all will be well:
(defun agenda-mark-done-and-archive ()
(interactive)
(org-agenda-todo 'done)
(org-agenda-archive))
(define-key org-agenda-mode-map "\C-c\C-x\C-s" 'agenda-mark-done-and-archive)
Internally, org-agenda-archive works by calling org-archive-subtree. So if we use advice we can modify org-archive-subtree to first mark things as done and then do whatever it normally does:
(defun org-archive-done (&optional arg)
(org-todo 'done))
(advice-add 'org-archive-subtree :before 'org-archive-done)
This version changes the normal and agenda versions simultaneously.
Note that the help for org-archive-subtree says
The tree will be moved to that location, the subtree
heading be marked DONE, and the current time will be added.
So this should already be happening. If it isn't, there may be some other issue.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Function to run when drop down is clicked
I have a lookup field. I need to filter the values in that drop-down, so I thought of writing function when the drop down control is clicked.
Something like.
$("select[title='Subsystem']").click(alert(""));
But this doesn't work. How could I achieve this?
A:
Try using Change event
$("select[title='Subsystem']").change(function () { alert($(this).val()); });
Update: Click event
$("select[title='Subsystem']").click(function(v){ console.log(v.target.value); });
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Event bind to the dynamically created elements
I have one textbox#search_text. on keyup i create one div#sresult_container.and append to some div to div#sresult_container. i try to bind click and mouseover event to div#sresult_container when this container display on canvas. i try following code but that not work.How can i do?
$("#search_text").keyup(function(e) {
if (e.which != 40 && e.which != 38) {
$("#search").removeAttr('disabled');
$.post('http://www.allinone.com', {
Search: sVal
}, function(data) {
$sresult_container = $('<div id="sresult_container"></div>');
//somecode which create another divs and append to the $sresult_container
})
}
$('#sresult_container').bind({
click: function(e) {
//some code
},
mouseover: function(e) {
//some code
}
});
});
A:
you can do this task with "live" function.
$('#sresult_container').live('click', function() {
alert('hello from binded function call');
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Print API for Chrome Extensions
Is there a Chrome Extension API that I can use to interact with the printing options for a page? I've checked Chrome's extension API's, but I can't seem to find anything on interacting with printing options in any way.
Is interacting with printer options possible using Chrome Extensions?
A:
Basically, no, there is no such API currently.
There are, it seems, vague plans for such an API in Chrome Apps, but nothing concrete yet as of 2015-04-16.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Php form: register users
i`m just starting in php, and I was wondering how to make a sign up form. I'm not really sure on how to add the values to the database. I'm using phpMyAdmin for the databases.
I have the inputs here:
<div id="registerSpace">
<form id="formulaireInscription2" name="formSignup" method="post" action="signUp.php">
<div class="registerUsername"><input type="text" placeholder="Username" name="txtUserName" /><span class="textInputs"></span></div>
<div class="registerNom"><input type="text" placeholder="First name" name="txtNom" /><span class="textInputs">First name</span></div>
<div class="registerPrenom"><input type="text" placeholder="Last name" name="txtPrenom" /><span class="textInputs">Family name</span></div>
<div class="registerPassword"><input type="password" placeholder="Password" name="txtPassword" /><span class="textInputs">Password</span></div>
<div class="dropLogonContentOptions"><input type="submit" value="Sign Up" name="send" />
</form>
</div>
I put all my code in signUp.php.
In phpMyAdmin, my database's called jleggett_colourful, and my table (where the user, password, first name blabla) is: t_usagers.
In there, I have u_id(auto increment, numbers only), u_nom(last name), u_prenom(first name), u_courriel(mail, also username!) and u_password.
What would be the best way to add it to the database? I have this code here:
<?php
session_start();
include 'inc/define.inc.php';
include 'inc/fct.inc.php';
if (isset($_POST["txtUserName"]) && isset($_POST["txtNom"]) && isset($_POST["txtPrenom"]) && isset($_POST["txtPassword"]))
{
// Ouvre une connexion au serveur MySQL
$connection = mysql_connect(NOM_SERVEUR, USER_NOM, USER_PASSWORD) or die("Impossible de se connecter : " . mysql_error());
if (!$connection) {
fin_perso('Problème de connexion au serveur : '. ' ---' . NOM_SERVEUR. '- - -' . USER_NOM. '- - -' . USER_PASSWORD. '- - - ' . mysql_error(), 'erreur_bd_');
}
// S�lectionne une base de données MySQL
if (!mysql_select_db(NOM_BD))
{
fin_perso('Problème de connexion à la base de données : ' . mysql_error(), 'erreur_bd');
}
$sql = "INSERT INTO t_usager (u_nom, u_prenom, u_password) VALUES ('fdfs', 'qwerty', '456789')";
else
echo "Please, enter all informations"
?>
I'm a bit lost here, but it should look like this! The code to connect to the database is correct, I just don't know how to add it with the values from my form. Thx! (I have entered default values, just for testing in $sql).
A:
You will change the following:
$sql = "INSERT INTO t_usager (u_nom, u_prenom, u_password) VALUES ('fdfs', 'qwerty', '456789')";
to use the values in the $_POST array (i.e. $_POST['txtUsername']). And then after you build the string for your query, you will need to call mysql_query ( $sql ); in order to actually run the query.
I believe that you are also missing a pair of {} within your code because the line with $sql on it is currently not valid (with the else right after since there is no nearby if it can relate to).
Code Example:
$nom = mysql_real_escape_string ( $_POST [ 'txtNom' ] );
$preNom = mysql_real_escape_string ( $_POST [ 'txtPrenom' ] );
$pass = mysql_real_escape_string ( $_POST [ 'txtPassword' ] );
$sql = "INSERT INTO t_usager (u_nom, u_prenom, u_password) VALUES ('$nom', '$preNom', '$pass')";
A:
Judda's answer surely works, but the risk of SQL injection is so high it transcends the "risk" realm, becoming more of a certainty.
I suggest you get a good basic manual (O'reilly's "Learning PHP, MySQL and Javascript is pretty easy and straightforward for beginners) and learn the basic security rules to observe when dealing with databases.
Spoiler, escaping is not enough; you will need prepared statements.
If you don't want to buy a book, then please for the love of god read this before going any further.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using evaluated variable values instead of the actual type
var foo;
console.log(typeof foo); //"undefined"
if(typeof foo === 'undefined')
console.log(1);
if(!foo)
console.log(2);
In my example above, the console will log both "1" and "2", since undefined evaluates as false. The same thing will happen for null, NaN, "" (empty string) etc.
Is it more common to use the typeof operator and compare the string value, rather than using the evaluated boolean value? Is there any difference besides readability? Any pros and cons?
A:
There is no silver bullet and it completely depends on your aims.
If you need to know that variable is "falsy" - you use if (!var), if you need to know precisely if it's null, 0, empty string or whatever - you use if (var === null)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I maintain state across multiple web servers?
Can I have multiple web servers hooked up to a SQL Server cluster and still maintain a user's session?
I've thought of various approaches. The one suggested by the Microsoft site is to use response.redirect to the "correct" server. While I can understand the reasoning for this, it seems kind of short sighted.
If the load balancer is sending you to the server currently under the least strain, surely as a developer you should honor that?
Are there any best practices to follow in this instance? If so, I would appreciate knowing what they are and any insights into the pros/cons of using them.
A:
Some options:
The load balancer can be configured to have sticky sessions. Make sure your app session timeout is less than the load balancers or you'll get bounced around with unpredictable results.
You can use a designated state server to handle session. Then it won't matter where they get bounced by the LB.
You can use SQL server to manage session.
Check this on serverfault.
https://serverfault.com/questions/19717/load-balanced-iis-servers-with-asp-net-inproc-session
|
{
"pile_set_name": "StackExchange"
}
|
Q:
analyzing a 2D array by columns
I have the following 2D array and I want to compare all the columns with each other.
int [][] myarray={{1,2,3},{1,2,3},{1,2,3}};
So what I want to see is if column 1 (all 1's) is equal to the values in column 2 (all 2's).
Ps. the array size is not just limited to this.
A:
It's not quite clear from your question whether you want to compare all columns to each other, or just a single column to another single column (for example column 1 to column 2). Assuming you meant the latter, you could do this.
public boolean columnsIdentical(int[][] array, int colIndex1, int colIndex2) {
for (int row = 0; row < array.length; row++ ) {
if (array[row][colIndex1] != array[row][colIndex2]) {
return false;
}
}
return true;
}
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.