_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 21
37k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d327
|
train
|
Your superclass PointF is not serialisable. That means that the following applies:
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
See: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
You will need to look at readObject and writeObject:
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
See also here: Java Serialization with non serializable parts for more tips and tricks.
A: I finally found the solution. Thanx @Greg and the other comment that has now been deleted. The solution is that instead of extending these objects we can make stub objects. As i was calling super from constructor the x and y fields were inherited from base class that is not serializable. so they were not serialized and there values were not sent.
so i mofidfied my class as per your suggestions
public class MyPointF implements Serializable {
/**
*
*/
private static final long serialVersionUID = -455530706921004893L;
public float x;
public float y;
public MyPointF(float x, float y) {
this.x = x;
this.y = y;
}
}
|
unknown
| |
d329
|
train
|
This has nothing to do with React Native, one of your resource files references an nonexisting value (dialogCornerRadius). Locate the reference (Android Studio to the rescue) and fix it.
|
unknown
| |
d333
|
train
|
The typical purpose for this style is in use for object construction.
Person* pPerson = &(new Person())->setAge(34).setId(55).setName("Jack");
instead of
Person* pPerson = new Person( 34, 55, "Jack" );
Using the second more traditional style one might forget if the first value passed to the constructor was the age or the id? This may also lead to multiple constructors based on the validity of some properties.
Using the first style one might forget to set some of the object properties and and may lead bugs where objects are not 'fully' constructed. (A class property is added at a later point but not all the construction locations got updated to call the required setter.)
As code evolves I really like the fact that I can use the compiler to help me find all the places where an object is created when changing the signature of a constructor. So for that reason I prefer using regular C++ constructors over this style.
This pattern might work well in applications that maintain their datamodel over time according to rules similar to those used in many database applications:
*
*You can add a field/attribute to a table/class that is NULL by default. (So upgrading existing data requires just a new NULL column in the database.)
*Code that is not changes should still work the same with this NULL field added.
A: Not all the setters, but some of them could return reference to object to be useful.
kind of
a.SetValues(object)(2)(3)(5)("Hello")(1.4);
I used this once long time ago to build SQL expression builder which handles all the Escapes problems and other things.
SqlBuilder builder;
builder.select( column1 )( column2 )( column3 ).
where( "=" )( column1, value1 )
( column2, value2 ).
where( ">" )( column3, 100 ).
from( table1 )( "table2" )( "table3" );
I wasn't able to reproduce sources in 10 minutes. So implementation is behind the curtains.
A: If your motivation is related to chaining (e.g. Brian Ensink's suggestion), I would offer two comments:
1.
If you find yourself frequently settings many things at once, that may mean you should produce a struct or class which holds all of these settings so that they can all be passed at once. The next step might be to use this struct or class in the object itself...but since you're using getters and setters the decision of how to represent it internally will be transparent to the users of the class anyways, so this decision will relate more to how complex the class is than anything.
2.
One alternative to a setter is creating a new object, changing it, and returning it. This is both inefficient and inappropriate in most types, especially mutable types. However, it's an option that people sometimes forget, despite it's use in the string class of many languages.
A: This technique is used in the Named parameter Idiom.
A: IMO setters are a code smell that usually indicate one of two things:
Making A Mountian Out Of A Molehill
If you have a class like this:
class Gizmo
{
public:
void setA(int a) { a_ = a; }
int getA() const { return a_; }
void setB(const std::string & b) { v_ = b; }
std::string getB() const { return b_; }
private:
std::string b_;
int a_;
};
... and the values really are just that simple, then why not just make the data members public?:
class Gizmo
{
public:
std::string b_;
int a_;
};
...Much simpler and, if the data is that simple you lose nothing.
Another possibility is that you could be
Making A Molehill Out Of A Mountian
Lots of times the data is not that simple: maybe you have to change multiple values, do some computation, notify some other object; who knows what. But if the data is non-trivial enough that you really do need setters & getters, then it is non-trivial enough to need error handling as well. So in those cases your getters & setters should be returning some kind of error code or doing something else to indicate something bad has happened.
If you are chaining calls together like this:
A.doA().doB().doC();
... and doA() fails, do you really want to be calling doB() and doC() anyway? I doubt it.
A: It's a usable enough pattern if there's a lot of things that need to be set on an object.
class Foo
{
int x, y, z;
public:
Foo &SetX(int x_) { x = x_; return *this; }
Foo &SetY(int y_) { y = y_; return *this; }
Foo &SetZ(int z_) { z = z_; return *this; }
};
int main()
{
Foo foo;
foo.SetX(1).SetY(2).SetZ(3);
}
This pattern replaces a constructor that takes three ints:
int main()
{
Foo foo(1, 2, 3); // Less self-explanatory than the above version.
}
It's useful if you have a number of values that don't always need to be set.
For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite.
Of course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not...
A: You can return a reference to this if you want to chain setter function calls together like this:
obj.SetCount(10).SetName("Bob").SetColor(0x223344).SetWidth(35);
Personally I think that code is harder to read than the alternative:
obj.SetCount(10);
obj.SetName("Bob");
obj.SetColor(0x223344);
obj.SetWidth(35);
A: I would not think so. Typically, you think of 'setter' object as doing just that.
Besides, if you just set the object, dont you have a pointer to it anyway?
|
unknown
| |
d335
|
train
|
You can try to light-weight load in main thread by
DispatchQueue.global().async {
UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList)
}
And instead of let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() use self.wishList directly in the last line
|
unknown
| |
d341
|
train
|
This version of your script should return the entire contents of the page:
var page = require('webpage').create();
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementsByTagName('html')[0].outerHTML;
});
console.log(ua);
}
phantom.exit();
});
A: There are multiple ways to retrieve the page content as a string:
*
*page.content gives the complete source including the markup (<html>) and doctype (<!DOCTYPE html>),
*document.documentElement.outerHTML (via page.evaluate) gives the complete source including the markup (<html>), but without doctype,
*document.documentElement.textContent (via page.evaluate) gives the cumulative text content of the complete document including inline CSS & JavaScript, but without markup,
*document.documentElement.innerText (via page.evaluate) gives the cumulative text content of the complete document excluding inline CSS & JavaScript and without markup.
document.documentElement can be exchanged by an element or query of your choice.
A: To extract the text content of the page, you can try thisreturn document.body.textContent; but I'm not sure the result will be usable.
A: Having encountered this question while trying to solve a similar problem, I ended up adapting a solution from this question like so:
var fs = require('fs');
var file_h = fs.open('header.html', 'r');
var line = file_h.readLine();
var header = "";
while(!file_h.atEnd()) {
line = file_h.readLine();
header += line;
}
console.log(header);
file_h.close();
phantom.exit();
This gave me a string with the read-in HTML file that was sufficient for my purposes, and hopefully may help others who came across this.
The question seemed ambiguous (was it the entire content of the file required, or just the "text" aka Strings?) so this is one possible solution.
|
unknown
| |
d343
|
train
|
You could try:
System.out.printf("Input an integer: ");
int a = in.nextInt();
int k = 0;
String str_a = "";
System.out.print(a);
while(a > 1)
{
if(a % 2 == 0)
a = a / 2;
else
a = 3 * a + 1;
str_a += ", " + String.valueOf(a);
k++;
}
System.out.println("k = " + k);
System.out.println("a = " + str_a);
|
unknown
| |
d347
|
train
|
If the registration is succesful you can simply push the email and password variables to firebase. See code below.
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
... Registration successful
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
##NEWCODE HERE##
emailRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/email")
passRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/password")
emailRef.set(email)
passRef.set(password)
logUserIn(email, password);
} else {
... Something went wrong at registration
}
}
});
}
|
unknown
| |
d351
|
train
|
I've done the first half of this before, so we'll start there (convenient, no?). Without knowing to much about your needs I'd recommend the following as a base (you can adjust the column widths as needed):
CREATE TABLE tree (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INT UNSIGNED NOT NULL DEFAULT 0,
type VARCHAR(20) NOT NULL,
name VARCHAR(32) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY (parent_id, type, name),
KEY (parent_id)
);
Why did I do it this way? Well, let's go through each field. id is a globally unique value that we can use to identify this element and all the elements that directly depend on it. parent_id lets us go back up through the tree until we reach parent_id == 0, which is the top of the tree. type would be your "car" or "vent" descriptions. name would let you qualify type, so things like "Camry" and "Driver Left" (for "vent" obviously).
The data would be stored with values like these:
INSERT INTO tree (parent_id, type, name) VALUES
(0, 'car', 'Camry'),
(1, 'hvac', 'HVAC'),
(2, 'vent', 'Driver Front Footwell'),
(2, 'vent', 'Passenger Front Footwell'),
(2, 'vent', 'Driver Rear Footwell'),
(2, 'vent', 'Passenger Rear Footwell'),
(1, 'glass', 'Glass'),
(7, 'window', 'Windshield'),
(7, 'window', 'Rear Window'),
(7, 'window', 'Driver Front Window'),
(7, 'window', 'Passenger Front Window'),
(7, 'window', 'Driver Rear Window'),
(7, 'window', 'Passenger Rear Window'),
(1, 'mirrors', 'Mirrors'),
(14, 'mirror', 'Rearview Mirror'),
(14, 'mirror', 'Driver Mirror'),
(14, 'mirror', 'Passenger Mirror');
I could keep going, but I think you get the idea. Just to be sure though... All those values would result in a tree that looked like this:
(1, 0, 'car', 'Camry')
| (2, 1, 'hvac', 'HVAC')
| +- (3, 2, 'vent', 'Driver Front Footwell')
| +- (4, 2, 'vent', 'Passenger Front Footwell')
| +- (5, 2, 'vent', 'Driver Rear Footwell')
| +- (6, 2, 'vent', 'Passenger Rear Footwell')
+- (7, 1, 'glass', 'Glass')
| +- (8, 7, 'window', 'Windshield')
| +- (9, 7, 'window', 'Rear Window')
| +- (10, 7, 'window', 'Driver Front Window')
| +- (11, 7, 'window', 'Passenger Front Window')
| +- (12, 7, 'window', 'Driver Rear Window')
| +- (13, 7, 'window', 'Passenger Rear Window')
+- (14, 1, 'mirrors', 'Mirrors')
+- (15, 14, 'mirror', 'Rearview Mirror')
+- (16, 14, 'mirror', 'Driver Mirror')
+- (17, 14, 'mirror', 'Passenger Mirror')
Now then, the hard part: copying the tree. Because of the parent_id references we can't do something like an INSERT INTO ... SELECT; we're reduced to having to use a recursive function. I know, we're entering The Dirty place. I'm going to pseudo-code this since you didn't note which language you're working with.
FUNCTION copyTreeByID (INTEGER id, INTEGER max_depth = 10, INTEGER parent_id = 0)
row = MYSQL_QUERY_ROW ("SELECT * FROM tree WHERE id=?", id)
IF NOT row
THEN
RETURN NULL
END IF
IF ! MYSQL_QUERY ("INSERT INTO trees (parent_id, type, name) VALUES (?, ?, ?)", parent_id, row["type"], row["name"])
THEN
RETURN NULL
END IF
parent_id = MYSQL_LAST_INSERT_ID ()
IF max_depth LESSTHAN 0
THEN
RETURN
END IF
rows = MYSQL_QUERY_ROWS ("SELECT id FROM trees WHERE parent_id=?", id)
FOR rows AS row
copyTreeByID (row["id"], max_depth - 1, parent_id)
END FOR
RETURN parent_id
END FUNCTION
FUNCTION copyTreeByTypeName (STRING type, STRING name)
row = MYSQL_QUERY_ROW ("SELECT id FROM tree WHERE parent_id=0 AND type=? AND name=?", type, name)
IF NOT ARRAY_LENGTH (row)
THEN
RETURN
END IF
RETURN copyTreeByID (row["id"])
END FUNCTION
copyTreeByTypeName looks up the tree ID for the matching type and name and passes it to copyTreeByID. This is mostly a utility function to help you copy stuff by type/name.
copyTreeByID is the real beast. Fear it because it is recursive and evil. Why is it recursive? Because your trees are not predictable and can be any depth. But it's okay, we've got a variable to track depth and limit it (max_depth). So let's walk through it.
Start by grabbing all the data for the element. If we didn't get any data, just return. Re-insert the data with the element's type and name, and the passed parent_id. If the query fails, return. Set the parent_id to the last insert ID so we can pass it along later. Check for max_depth being less than zero, which indicates we've reached max depth; if we have return. Grab all the elements from the tree that have a parent of id. Then for each of those elements recurse into copyTreeByID passing the element's id, max_depth minus 1, and the new parent_id. At the end return parent_id so you can access the new copy of the elements.
Make sense? (I read it back and it made sense, not that that means anything).
|
unknown
| |
d353
|
train
|
autoit may work. i'd use python PIL. i can specify font, convert it to a layer and overlay on top of preexisting image.
EDIT
actually imagemagick can be easier than PIL http://www.imagemagick.org/Usage/text/
A: Should not be much of a problem if you have Python and the Python Imaging Library (PIL) installed:
from PIL import Image, ImageFont, ImageDraw
BACKGROUND = '/path/to/background.png'
OUTPUT = '/path/to/mypicture_{0:04d}.png'
START = 0
STOP = 9999
# Create a font object from a True-Type font file and specify the font size.
fontobj = ImageFont.truetype('/path/to/font/arial.ttf', 24)
for i in range(START, STOP + 1):
img = Image.open(BACKGROUND)
draw = ImageDraw.Draw(img)
# Write a text over the background image.
# Parameters: location(x, y), text, textcolor(R, G, B), fontobject
draw.text((0, 0), '{0:04d}'.format(i), (255, 0, 0), font=fontobj)
img.save(OUTPUT.format(i))
print 'Script done!'
Please consult the PIL manual for other ways of creating font objects for other font formats
|
unknown
| |
d359
|
train
|
The simplest way would be to create a function with the code you want to execute after the execution of the request, and pass this function in parameter of the getfile function :
getFile : function( fileName, success ) {
var me = this;
me.db.transaction( function( tx ) {
tx.executeSql( "SELECT * FROM content WHERE fileName = '" + fileName + "'", [ ], me.onSuccess, me.onError );
},
success
);
// somehow return results as empty array or array with object
// I know results need to be transformed
});
var r = getFile(
name,
function() {
var r = getFile( name );
if ( r.length > 0 ) {
// use it
}
else {
// make AJAX call and store it
}
}
);
Otherwise, the best way to perform is to use Promises to resolve asynchronous issues but you'll have to use a library like JQuery.
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
|
unknown
| |
d361
|
train
|
If you want to use your url params in your state everytime, you can use the resolve function:
.state('edit', {
url: '/editItem/:id/:userId',
templateUrl: 'app/items/edit.html',
controller: 'editController',
controllerAs: 'vm',
resolve: {
testObject: function($stateParams) {
return {
id: $stateParams.id,
userId: $stateParams.userId
}
}
}
})
Now, you can pass testObject as a dependency to your editController and every time this route is resolved, the values will be available within your controller as testObject.id and testObject.userId
If you want to pass an object from one state to the next, use $state.go programatically:
$state.go('myState', {myParam: {some: 'thing'}})
$stateProvider.state('myState', {
url: '/myState',
params: {myParam: null}, ...
The only other option is to cache, trough Localstorage or cookies
|
unknown
| |
d363
|
train
|
Try this:
object.visible = false; //Invisible
object.visible = true; //Visible
A: simply use the object traverse method to hide the mesh in three.js.
In my code hide the object based on its name
object.traverse ( function (child) {
if (child instanceof THREE.Mesh) {
child.visible = true;
}
});
Here is the working sample for Object show/hide option
http://jsfiddle.net/ddbTy/287/
I think it should be helpful,..
|
unknown
| |
d365
|
train
|
how come I can still add content to the file such as shown here Android saving Bitmap to SD card.
That code creates a new file after deleting the old one.
So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there?
Call delete() on a File object that points to the file. Then, do not use that same File object to write to the file again, thereby creating a new file, as the code that you link to does.
|
unknown
| |
d375
|
train
|
It looks like you init your manifest on the incorrect version of AOSP. See Downloading the Source for a good explanation of what you need to do to setup AOSP.
The main part from there that you want though, is:
repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1
Which would init your repository on AOSP version 4.0.1_r1. If you want to init on the l-preview branch, it would be:
repo init -u https://android.googlesource.com/platform/manifest -b l-preview
Just keep in mind this isn't actually android l's source code, its a GPL update. I am not sure if they have moved it over to using java version 1.7 yet, as I have not personally tried.
|
unknown
| |
d379
|
train
|
You can encode these as you would encode a binary number, by assigning increasing powers of two for each column. You want to multiply each row by c(1,2,4) and then take the sum.
# The multiplier, powers of two
x <- 2^(seq(ncol(df))-1)
x
## [1] 1 2 4
# The values
apply(df, 1, function(row) sum(row*x))
## row1 row2 row3
## 4 1 2
To add this as a new column:
df$new <- apply(df, 1, function(row) sum(row*x))
df
## X1 X2 X3 new
## row1 0 0 1 4
## row2 1 0 0 1
## row3 0 1 0 2
A: Try:
> df
X1 X2 X3
row1 0 0 1
row2 1 0 0
row3 0 1 0
>
>
> mm = melt(df)
No id variables; using all as measure variables
>
> mm$new = paste(mm$variable,mm$value,sep='_')
>
> mm
variable value new
1 X1 0 X1_0
2 X1 1 X1_1
3 X1 0 X1_0
4 X2 0 X2_0
5 X2 0 X2_0
6 X2 1 X2_1
7 X3 1 X3_1
8 X3 0 X3_0
9 X3 0 X3_0
mm$new is the column you want.
A: Maybe this is what you want:
> df$X1 = ifelse(df$X1==0,'green','yellow')
> df$X2 = ifelse(df$X2==0,'red','blue')
> df$X3 = ifelse(df$X3==0,'black','white')
>
> df
X1 X2 X3
row1 green red white
row2 yellow red black
row3 green blue black
>
> unlist(df)
X11 X12 X13 X21 X22 X23 X31 X32 X33
"green" "yellow" "green" "red" "red" "blue" "white" "black" "black"
|
unknown
| |
d385
|
train
|
You declared the generic type bound in the wrong place.
It should be declared within the declaration of the generic type parameter:
public final <T extends MyObject> T getObject(Class<T> myObjectClass)
{
//...
}
|
unknown
| |
d387
|
train
|
I think inheritance is a good approach to this problem.
I can think of two down sides:
*
*It is possible to create additional columns to the inheritance children. If you control DDL, you can probably prevent that.
*You still have to create and modify indexes on all inheritance children individually.
If you are using PostgreSQL v11 or later, you could prevent both problems by using partitioning. The individual tables would then be partitions of the “template” table. This way, you can create indexes centrally by creating a partitioned index on the template table. The disadvantage (that may make this solution impossible) is that you need a partitioning key column in the table.
|
unknown
| |
d389
|
train
|
Your logic to get the new position is correct, but in your Update() function, you have to update the position of the camera using transform.position, assuming this script is a component you have added to the Camera in the scene.
// Update is called once per frame
void Update()
{
Vector3 newpos = Playerposition.position + cameraoffset;
transform.position = newpos;
}
If this script isn't on the camera, you'll need a reference to the camera by taking it as an input in the Unity inspector (declaring public Camera cam; at the top of your class) and then set in in the inspector by dragging the camera object onto that input. Then you can do cam.transform.position = newpos; in Update().
|
unknown
| |
d401
|
train
|
Your parameter is only set to 5
$('#form').validate({
rules: {
image: {
....
filesize: 5, ...
That is 5 BYTES, so of course you would be getting the error message for any file that is 98 kB or 3.8 MB. Since these are both larger than 5 bytes, they fail your custom rule, which only allows files smaller than 5 bytes.
Try 5242880 if you want to allow files under 5 MB.
filesize: 5242880 // <- 5 MB
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} bytes');
$(function($) {
"use strict";
$('#form').validate({
rules: {
image: {
//required: true,
extension: "jpg,jpeg,png",
filesize: 5242880 // <- 5 MB
}
},
});
});
<form id="form" method="post" action="">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
A: Usually in these types, file sizes are specified in bytes. So you have to multiply it by 1024 multipliers accordingly.
For example if you want to check if the file size is less than 5MB, you should use
image: {
extension: "jpg,jpeg,png",
filesize: 5*1024*1024,
}
|
unknown
| |
d409
|
train
|
If you are already using numpy you can set the dtype field to the type that you want (documentation). You'll get a little more flexibility there for typing, but in general you aren't going to get a lot of control over variable precision in Python. You might also have some luck if you want to go through the structural overhead of using the static types from Cython, though if you are new to programming that may not be the best route.
Beyond that, you haven't given us a lot to work with regarding your actual problem and why you feel that the variable precision is the best spot for optimization.
A: Pure CPython (sans numpy, etc.) floats are implemented as C doubles.
http://www.ibm.com/developerworks/opensource/library/os-python1/
Yes, the types are associated with values, not variables. You can check for something being a Python float with isinstance(something, float).
You could perhaps try objgraph to see what's using your memory.
http://mg.pov.lt/objgraph/
There's also a possibility that you are leaking memory, or merely need a garbage collection. And it could be that your machine just doesn't have much memory - sometimes it's cheaper to throw a little extra RAM, or even a little more swap space, at a constrained memory problem.
It's possible that using a low precision, alternative numeric representation would help - perhaps http://pypi.python.org/pypi/Simple%20Python%20Fixed-Point%20Module/0.6 ?.
|
unknown
| |
d411
|
train
|
setState is asynchronous.
I think you should handle the renderQuestion in a useEffect
const [questionIndex, setQuestionIndex] = useState(0)
function renderQuestion() {
console.log(`questionIndex from render question function is : ${questionIndex}`)
setWordToTranslate(Data[questionIndex].word);
setAnswer(Data[questionIndex].translation)
}
useEffect(() => {
renderQuestion()
}, [questionIndex])
function verifyAnswer(value) {
if (value === answer) {
console.log("answer is correct!");
if (questionIndex < questionsLength) {
setQuestionIndex(questionIndex + 1)
}
}
}
function handleInputChange(event) {
const {value} = event.target;
setUserInput(value);
verifyAnswer(value);
}
|
unknown
| |
d413
|
train
|
Probably the way you are using won't work. Because, you are sending a list but you are probably iterating through a queryset in template. Also, the way you are using distinct won't work. Because you are using 'Rounding','Configuration' togather, hence it will generate something like this:
<QuerySet [('Use Percentage Only', 'Up'), ('Use Percentage Only', 'Down'), ('Use Percentage Only', 'Half'), ...>
So you can try like this(without distinct):
grade = list(gradeScalesSetting.objects.all()) # < DB hit once
rounding = []
configuration = []
for i in grade:
if i.Rounding not in rounding:
rounding.append(i.Rounding)
if i.Configuration not in configuration:
configuration.append(i.Configuration)
return render(request, 'Homepage/gradescale.html',{"rounding":rounding, "configuration":configuration})
// in template
<select>
{% for r in rounding %}
<option value={{r}}>{{r}}</option>
{% endfor %}
</select>
But with distinct you might have to hit the DB twice:
rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct()
configuration = gradeScalesSetting.objects.all().values_list('Configuration', flat=True).distinct()
|
unknown
| |
d421
|
train
|
Add the bullets to the ship's parent (or directly to the scene), just not the ship or the turret because that will make the position of the bullet relative to either one.
A: Think of it this way: the ship is facing in a specific direction when it fires the bullet.
Once it fires the bullet, you wouldn't expect it to have any control over the bullet? If it turned around, the bullet should keep moving in the same direction (not stay directly in front of the ship).
This is a hint that the bullet should probably not have the ship as a parent node; it is an entity existing alongside the ship and not as part of it.
Once the bullet is fired, it should be in the same 'system' as the ship, so as @LearnCocos2D suggested it should share a parent with the ship.
|
unknown
| |
d423
|
train
|
Yet one more option is to use the hierarcyid data type
Example
Declare @YourTable Table ([ID] int,[Caption] varchar(50),[Parent] int) Insert Into @YourTable Values
(1,'A',NULL)
,(2,'B',NULL)
,(3,'a',1)
,(4,'b',2)
,(5,'bb',4)
,(6,'C',NULL)
,(7,'aa',3)
,(8,'c',6)
;with cteP as (
Select ID
,Parent
,Caption
,HierID = convert(hierarchyid,concat('/',ID,'/'))
From @YourTable
Where Parent is null
Union All
Select ID = r.ID
,Parent = r.Parent
,Caption = r.Caption
,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.ID,'/'))
From @YourTable r
Join cteP p on r.Parent = p.ID)
Select Lvl = HierID.GetLevel()
,ID
,Parent
,Caption
From cteP A
Order By A.HierID
Returns
Lvl ID Parent Caption
1 1 NULL A
2 3 1 a
3 7 3 aa
1 2 NULL B
2 4 2 b
3 5 4 bb
1 6 NULL C
2 8 6 c
A: Such sort requires somehow traversing the hierarchy to compute the path of each node.
You can do this with a recursive query:
with cte as (
select id, caption, parent, caption addr
from mytable
where parent is null
union all
select t.id, t.caption, t.parent, c.addr + '/' + t.caption
from cte c
inner join mytable t on t.parent = c.id
)
select
id,
row_number() over(order by addr) sort,
caption,
parent
from c
order by addr
A: You can construct the path to each row and then use that for sorting. The construction uses a recursive CTE:
with cte as (
select id, caption, parent, convert(varchar(max), format(id, '0000')) as path, 1 as lev
from t
where parent is null
union all
select t.id, t.caption, t.parent, convert(varchar(max), concat(path, '->', format(t.id, '0000'))), lev + 1
from cte join
t
on cte.id = t.parent
)
select id, caption, parent
from cte
order by path;
Here is a db<>fiddle.
A: No need for recursion, just use some clever sorting!
SELECT
ID,
ROW_NUMBER() over(order by Caption) as Sort,
Caption,
Parent
FROM Address
ORDER BY Caption, Parent
SQL Fiddle: http://sqlfiddle.com/#!18/bbbbe/9
|
unknown
| |
d425
|
train
|
What are you trying to do with the Title specifically? If you want a custom property on a label control you will need to create a custom control that inherits from the Label control. If you just want to set the text then use the Text property. If you want a tooltip then set the ToolTip property.
|
unknown
| |
d431
|
train
|
C# keywords supporting LINQ are still C#. Consider where as a conditional like if; you perform logical operations in the same way. In this case, a logical-OR, you use ||
(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(
txtFilter.Text.ToLowerInvariant())
|| creditCard.CardNumber.().Contains(txtFilter.Text)
orderby creditCard.BillToName
select creditCard)
A: You can use the .Where() function to accomplish this.
var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());
A: You should use the boolean operator that works in your language. Pipe | works in C#
Here's msdn on the single |
Here's msdn on the double pipe ||
The deal with the double pipe is that it short-circuits (does not run the right expression if the left expression is true). Many people just use double pipe only because they never learned single pipe.
Double pipe's short circuiting behavior creates branching code, which could be very bad if a side effect was expected from running the expression on the right.
The reason I prefer single pipes in linq queries is that - if the query is someday used in linq to sql, the underlying translation of both of c#'s OR operators is to sql's OR, which operates like the single pipe.
|
unknown
| |
d433
|
train
|
FWIW...late answer...however, it may help someone: if you have designated (through Info.plist's CFBundleExecutable key's value) the script to be your app's executable, by the time you attempt to sign said script, you should make sure everything else has already been signed.
Note: this is my experience using codesign through a bash script (so, not using XCode). Apple's docs say that you should sign your app bundle "from inside out"; this was my interpretation and it seems to work just fine for us.
A: Something similar to the following shell script in the Build Phases > Run Script section of your project settings should work...
/usr/bin/codesign --force --sign "iPhone Developer" --preserve-metadata=identifier,entitlements --timestamp=none $BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app/Frameworks/$framework
|
unknown
| |
d437
|
train
|
Lovespring,
You will need a copy of the kernel source or kernel headers for the kernel you are attempting to compile against. The kernel source is generally not installed with the system by default.
Typically, you can pull down a copy of the kernel source through whatever package/repository manager your have.
A: You may not need an installed kernel, but you will definitely need a copy of the source to be able to compile your module.
A:
Does the kernel module need a linux kernel to finish the compilation ?
Can I compile a kernel module without kernel ?
Yes, you can have single Makefile for your module source code. It still needs to find the kernel headers and some basic build tools.
you do not need to have the kernel sources, and you do not need to recompile the kernel.
Page #94 of this chapter may help:
http://www.linuxfordevices.com/files/misc/newnes_embedded_linux_ch7.pdf
|
unknown
| |
d441
|
train
|
You cannot write file directly from a browser to local computers.
That would be a massive security concern.
*You also cannot use fs on client-side browser
Instead you get inputs from a browser, and send it to your server (NodeJs), and use fs.writeFile() on server-side, which is allowed.
What you could do is:
*
*Create a link and prompt to download.
*Send to server and response with a download.
*Use native environment like Electron to able NodeJs locally to write into local computer.
What I assume you want to do is 1
Is that case you could simply do:
function writeAndDownload(str, filename){
let yourContent = str
//Convert your string into ObjectURL
let bom = new Uint8Array([0xef, 0xbb, 0xbf]);
let blob = new Blob([bom, yourContent], { type: "text/plain" });
let url = (window.URL || window.webkitURL).createObjectURL(blob);
//Create a link and assign the ObjectURL
let link = document.createElement("a");
link.style.display = "none";
link.setAttribute("href", url);
link.setAttribute("download", filename);
//Automatically prompt to download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
writeAndDownload("Text you want to save", "savedData")
|
unknown
| |
d443
|
train
|
You can't do it with a style or template, since a binding is not a FrameworkElement. But your idea of a class inheriting Binding should work fine, I've done the same before for a similar problem
|
unknown
| |
d447
|
train
|
A guy in my team found the solution. When referencing the stylesheets I've forgotten the rel="stylesheet" after each of them.
so this
<link type="text/css" href="assets/styles/main.css">
should be this
<link type="text/css" href="assets/styles/main.css" rel="stylesheet">
|
unknown
| |
d449
|
train
|
You cannot do this directly in the manner you are talking about. There are filesystems that sort of do this. For example LessFS can do this. I also believe that the underlying structure of btrfs supports this, so if someone put the hooks in, it would be accessible at user level.
But, there is no way to do this with any of the ext filesystems, and I believe that it happens implicitly in LessFS.
There is a really ugly way of doing it in btrfs. If you make a snapshot, then truncate the snapshot file to 100M, you have effectively achieved your goal.
I believe this would also work with btrfs and a sufficiently recent version of cp you could just copy the file with cp then truncate one copy. The version of cp would have to have the --reflink option, and if you want to be extra sure about this, give the --reflink=always option.
A: Adding to @Omnifarious's answer:
What you're describing is not a hard link. A hard links is essentially a reference to an inode, by a path name. (A soft link is a reference to a path name, by a path name.) There is no mechanism to say, "I want this inode, but slightly different, only the first k blocks". A copy-on-write filesystem could do this for you under the covers. If you were using such a filesystem then you would simply say
cp fileA fileB && truncate -s 200M fileB
Of course, this also works on a non-copy-on-write filesystem, but it takes up an extra 200 MB instead of just the filesystem overhead.
Now, that said, you could still implement something like this easily on Linux with FUSE. You could implement a filesystem that mirrors some target directory but simply artificially sets a maximum length to files (at say 200 MB).
FUSE
FUSE Hello World
A: Maybe you can check ChunkFS. I think this is what you need (I didn't try it).
|
unknown
| |
d451
|
train
|
You can make use of a dynamic uri in your route block.
See http://camel.apache.org/how-do-i-use-dynamic-uri-in-to.html
Note that this can be done in both from() and to().
Example:
[From (previous application endpoint)]
-> [To (perform rest with dynamic values from the exchange)]
-> [To (process the returned json)]
A: If you're making a rest call you can use the CXFRS component. At the very bottom of the page you'll see an example of a processor that's setting up a message as a rest call. With regards to your question, you can use
inMessage.setHeader(Exchange.HTTP_PATH, "/resources/{var1}/{var2}/details?orderNumber=XXXXX");
to set up any path parameters that you might need.
A: Please Try to use camel servlet.
< from uri="servlet:///orders/resources/{$var1}/{$var2}/details?orderNumber=XXXXX" />
in web.xml,
< url-pattern>/ * < /url-pattern>
Reference:
http://camel.apache.org/servlet.html
A: Below is the example where you can find a Rest call with Apache Camel.
package camelinaction;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.apache.camel.spring.boot.FatJarRouter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class OrderRoute extends FatJarRouter {
@Bean(name = "jsonProvider")
public JacksonJsonProvider jsonProvider() {
return new JacksonJsonProvider();
}
@Override
public void configure() throws Exception {
// use CXF-RS to setup the REST web service using the resource class
// and use the simple binding style which is recommended to use
from("cxfrs:http://localhost:8080?resourceClasses=camelinaction.RestOrderService&bindingStyle=SimpleConsumer&providers=#jsonProvider")
// call the route based on the operation invoked on the REST web service
.toD("direct:${header.operationName}");
// routes that implement the REST services
from("direct:createOrder")
.bean("orderService", "createOrder");
from("direct:getOrder")
.bean("orderService", "getOrder(${header.id})");
from("direct:updateOrder")
.bean("orderService", "updateOrder");
from("direct:cancelOrder")
.bean("orderService", "cancelOrder(${header.id})");
}
}
Source code link :
https://github.com/camelinaction/camelinaction2/tree/master/chapter10/camel-cxf-rest-spring-boot.
I highly encourage to refer camelinaction2 as it covers many advance topics and it is written by @Claus Ibsen.
|
unknown
| |
d453
|
train
|
Try DataRow's IsNull method to check null values :
Dim isPersonIDNull As Boolean = .Rows(0).IsNull("personId")
Or use IsDBNull method :
Dim isPersonIDNull As Boolean = IsDBNull(.Rows(int).Item("personId"))
Or manually Check if the value equals DBNull :
Dim isPersonIDNull As Boolean = .Rows(int).Item("personId").Equals(DBNull.Value)
A: If DBNull.Value.Equal(.Rows(int).Item("personId")) Then
...
DBNull
A: You can also use the Convert.DbNull constant.
A: You have to check if the value is null before you assign it to PersonID
like:
if .Rows(int).Item("personId") = DBNull.Value Then
' Assign some Dummy Value
PersonID = ""
else
PersonID = .Rows(int).Item("personId")
end if
I would recommend to extract that piece of code into a helper method which gets either the value or a default for a given column.
A: This situation can occur if table with no rows, that time ds.Table(0).Rows(int).Item("personId") will return null reference exception
so you have to use two conditions
Dim PersonID As String =""
if(ds.tables.count>0) Then
if(ds.tables(0).Rows.Count>0) Then
if(NOT DBNull.Value.Equal((ds.tables(0).Rows(int).Item("PersonID"))) Then
PersonID = ds.tables(0).Rows(int).Item("PersonID")
I think It will solve your issue..just minor syntax variation may be present
|
unknown
| |
d455
|
train
|
You've tried onMouseDown?
<button
onMouseDown={() => setdata((previous) => !previous)}
type="button"
style={{ cursor: 'pointer' }}
>
Start
</button>
source: https://stackoverflow.com/a/37273344/19503616
A: It's possible that the issue might be with the type of the button or with the way the event handler is being attached to the button. Try changing the type of the button from "button" to "submit". Also, make sure that the onClick event handler is correctly attached to the button component. Here's how it should look:
<button type="submit" onClick={() => setdata((previous) => !previous)} style={{ cursor: 'pointer' }}>Start</button>
If the above does not work, try debugging the issue by using console.log statements within the event handler to check if it's being called.
|
unknown
| |
d465
|
train
|
This is because you have reduced the number of significant digits when you changed the datatype. If you have any rows with a value of 100,000 or greater it won't fit inside the new size. If you want to increase the number of decimal places (scale) you will also need to increase the precision by 1.
alter table xxx alter COLUMN xxx decimal (10,5) not null
Please note, this will increase the storage requirements of each row by 4 bytes. The storage requirement will increase from 5 bytes to 9 bytes.
https://msdn.microsoft.com/en-us/library/ms187746.aspx
|
unknown
| |
d467
|
train
|
Try this:
string[] arrdate = currentLine.Split(' ');
var dateItems = arrdate.Where(item => item.Contains("/")).ToArray()
A: foreach (string s in arrdate)
{
if (s.contains("/"))
{
//do something with s like add it to an array or if you only look for one string assign it and break out of the loop.
}
}
A: if you want to get only one item then try this
// split on the basis of white space
string[] arrdate = currentLine.Split(' ');
// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();
// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}
A: // split on the basis of white space
string[] arrdate = currentLine.Split(' ');
// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();
// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}
|
unknown
| |
d469
|
train
|
You have a little code that looks like pseudoxode - try this:
if (isNaN(rows)) alert("Error: Not a Number");
|
unknown
| |
d473
|
train
|
//root.setStyle("-fx-background-image: url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQxsasGQIwQNwjek3F1nSwlfx60g6XpOggnxw5dyQrtCL_0x8IW')");
This worked out. But not all url's it likes.
A: In case you are using FXML, you have to add stylesheets to your GridPane in the Controller class. For example, gridPane is the reference variable of your GridPane and app.css is a name of your stylesheets:
gridPane.getStylesheets().addAll(getClass().getResource("/css/app.css").toExternalForm())
Then write something like this in your stylesheets:
#gridPane { -fx-background-image:url("file:C:/path/to/your/project/folder/src/main/resources/image.jpg"); }
In addition, you can add stylesheets app.css to GridPane in the SceneBuilder.
The aforementioned procedure worked for me.
|
unknown
| |
d475
|
train
|
You were nearly there!:
You just need to supply the package and class of the app you want.
// Try
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setComponent(new ComponentName("com.htc.Camera", "com.htc.Camera.Camera"));
startActivity(intent);
// catch not found (only works on HTC phones)
ComponentName
I also just saw you can do it a second way:
PackageManager packageManager = getPackageManager();
startActivity(packageManager.getLaunchIntentForPackage("com.skype.android"));
See: SOQ Ref
|
unknown
| |
d477
|
train
|
There isn't direct metaspace information in a HPROF file.
Your might have a class loader leak or duplicate classes.
Try reading Permgen vs Metaspace in Java or
The Unknown Generation: Perm
|
unknown
| |
d481
|
train
|
NoSuchElementException exception is throwed by in.next(), in list.add(new Task(in.next(),in.next(), in.hasNextBoolean())),.
and for in.next(), if you don't use any Pattern in Scanner to match the next token. it will use default Pattern private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*") to match whole line. it will cause in.next() will read whole line.
so list.add(new Task(in.next(),in.next(), in.hasNextBoolean())) will throw NoSuchElementException, you have read twice but you only check once.
|
unknown
| |
d485
|
train
|
Dumb me, i was trying to figure out what is wrong with the code this whole time when its just a simple problem.. i have two models with the same filename (backup project) and i blindly edits model file that is inside the backup project..
Perhaps for future readers seeking an answer, don't forget to check your folder path for your model file, you might make the same mistake as i did.
|
unknown
| |
d487
|
train
|
From this thread:
The IBM.WMQ is IBM's version of Neil Kolban's original work of
converting the Java classes for MQ to classes for the .NET framework.
The IBM.WMQAX is IBM's COM component for accessing MQ (ActiveX)
If you're coding in .NET, use IBM.WMQ since it's managed code. If
you're coding in VB6 or VC++ then use the ActiveX com component.
You could use the COM component from .NET using COM Interop, but that
really would only make sense, IF, the classes for .NET were NOT
available. Seeing that they are, use IBM.WMQ.
A: You need to use IBM.WMQ namespace for developing .NET applications to interact with IBM MQ Queue Manager. The other one, IBM.WMQAX namespace is for ActiveX applications.
A: This thread, linked in the answer by @stuartd contains some valuable information. While the part in his quote seems partially incorrect, additional comments in the thread do a better job clarifying. While I never used VB script or ActiveX, and thus don't quite follow the problem that the IBM.WMQAX namespace was looking to solve, I can ascertain from the discussion that the namespace should be avoided when writing a new .NET application from scratch.
|
unknown
| |
d493
|
train
|
Use a Bounded Wildcard in your interface:
public interface Population<T extends Chromosome>{
void addChromosomes(List<T> chromosomes);
List<T> getChromosomes();
}
public class TSPPopulation implements Population<TSPChromosome>
{
private List<TSPChromosome> chromosomes;
@Override
public void addChromosomes(List<TSPChromosome> chromosomes) {
...
}
@Override
public List<TSPChromosome> getChromosomes() {
...
}
}
A: The simplest solution is extending a list (then use addAll(...) to add a list of Chromosoms to the list):
class Population<T extends Chromosome> extends ArrayList<T> {
}
But if you want the same structure I would make Population into a generic list class. That way both add... and get... methods can be handled in the generic base class. If you do want to override any other feature you just extend Population (class TSPPopulation extends Population<TSPChromosome>.
Usage:
public static void main(String... args) {
Population<TSPChromosome> tspPopulation = new Population<TSPChromosome>();
...
}
Implementation:
class Population<T extends Chromosome> {
private List<T> chromosomes = new ArrayList<T>();
public void addChromosomes(List<T> chromosomes) {
this.chromosomes.addAll(chromosomes);
}
public List<T> getChromosomes() {
return new ArrayList<T>(this.chromosomes);
}
}
A: It would be much safer if you made the Population generic itself:
public interface Population<T extends Chromosome> {
void addChromosomes(List<T> chromosomes);
List<T> getChromosomes();
}
public class TspPopulation implements Population<TspChromosome>{
@Override
public void addChromosomes(List<TspChromosome> chromosomes){
//
}
@Override
public List<TspChromosome> getChromosomes(){
//
}
}
That way you would not need any casting in client code.
A: I know GAs, and I would question whether your Population implementation actually needs to know which kind of Chromosome you put in. Do you really have different Population implementations depending on the Chromosome subclass? Or what you really want is to make sure you have the same subclass of Chromosome in a Population? In this last case, you can define the Population interface as others suggested, and the make a generic implementation (or skip the interface altogether):
public class PopulationImpl implements Population<T extends Chromosome> {
private List<T> chromosomes;
@Override
public void addChromosomes(List<T> chromosomes) {
this.chromosomes.addAll(chromosomes);
}
@Override
public List<T> getChromosomes() {
return new ArrayList<T>(chromosomes);
}
}
Be careful not to put too many generics, or you will end up with generics hell, or tons of casts which will make generics more annoying than useful.
A: Yes, for instance:
public interface Population<T extends Chromosome>
{
void addChromosomes(List<T> chromosomes);
List<T> getChromosomes();
// More code here ...
}
public class TSPPopulation implements Population<TSPChromosome>
{
private List<TSPChromosome> chromosomes;
@Override
public void addChromosomes(List<TSPChromosome> chromosomes) {
this.chromosomes.addAll(chromosomes);
}
@Override
public List<TSPChromosome> getChromosomes() {
return new ArrayList<TSPChromosome>(chromosomes);
}
}
|
unknown
| |
d497
|
train
|
One simple approach to keep as close to your code as possible is to start off with an empty list called colors before entering your loop, and appending to that all the valid colors as you take inputs. Then, when you are done, you simply use the join method to take that list and make a string with the ':' separators.
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
else:
colors.append(color)
colors = ':'.join(colors)
print ("colors ", colors)
Demo:
please enter Color of your choice(To exit press No): red
please enter Color of your choice(To exit press No): blue
please enter Color of your choice(To exit press No): green
please enter Color of your choice(To exit press No): orange
please enter Color of your choice(To exit press No): No
colors red:blue:green:orange
A: You can concatenate a ':' after every input color
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
color += color
color += ':'
print ("colors ", color)
A: you're looking for str.join(), to be used like so: ":".join(colors). Read more at https://docs.python.org/2/library/stdtypes.html#str.join
A: Using a list is neat:
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color in ('No'):
break
colors.append(color)
print("colors ", ':'.join(colors))
|
unknown
| |
d499
|
train
|
Could you see what happens (not sure here...) when you add a text-field xyz to the form and use a notes-url like notes://localhost/__A92574C800517FC7.nsf/company?OpenForm&xyz=something ?
|
unknown
| |
d501
|
train
|
When you divide $valueAsCents = 54780 / 100 then it becomes a float which is not always accurate in digital form because of the way they are stored. In my tests I got
547.7999999999999545252649113535881042480468750000
When multiplied by 100 this is would be
54779.9999999999927240423858165740966796870000
When PHP casts to int, it always rounds down.
When converting from float to integer, the number will be rounded towards zero.
This is why the int value is 54779
Additionally, the PHP manual for float type also includes a hint that floating point numbers may not do what you expect.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
|
unknown
| |
d503
|
train
|
You need to use as below
MenuItem menuTest2 = new MenuItem(); // Main Manu 2
menuTest2.Text = " SMS ";
menuTest2.NavigateUrl = "javascript:void(0)";
//menuTest2.Value = "something";
Menu1.Items.Add(menuTest2);
The problem as I think was that the page get redirected to the same page when clicked. And as I guess the menu is created on page load event.
Using menuTest2.NavigateUrl = "javascript:void(0)"; will stop the menu to postback when it is clicked.
|
unknown
| |
d505
|
train
|
How about using YCbCr?
Y is intensity, Cb is the blue component relative to the green component and Cr is the red component relative to the green component.
So I think YCbCr can differentiate between multiple pixels with same grayscale value.
|
unknown
| |
d509
|
train
|
I think the error says it quite well. You have a syntax error.
Perhaps this is what you wanted?
exec('sed -i \'1i MAILTO=""\' /var/spool/cron/'.$clientName);
|
unknown
| |
d511
|
train
|
Refer this great write up: http://blog.webbb.be/command-not-found-node-npm/
This can happen when npm is installing to a location that is not the standard and is not in your path.
To check where npm is installing, run: npm root -g
It SHOULD say /usr/local/lib/node_modules, If it doesn't then follow this:
Set it to the correct PATH:
*
*run: npm config set prefix /usr/local
*Then reinstall your npm package(s) with -g:
npm install -g cordova etc
If this doesn't work then try adding the global path of cordova(where it got installed) to your $PATH variable.
|
unknown
| |
d513
|
train
|
If you know that the list is the value associated to the 'result' key, simply call dct['result'].
>>> dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct
{'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct['result']
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']
Converting the values to a list is unneeded, inefficient and might return the wrong value if your dict has more than 1 (key, value) pair.
A: Your dictionary have only one value and that itself is a list of elements. So just call the result key and you will get the list value.
If you want the list from your code add the index [0] like,
dList = list(dct.values())[0]
Hope this helps! Cheers!
|
unknown
| |
d515
|
train
|
You can use useState hook from react. check the docs here: https://reactjs.org/docs/hooks-state.html
|
unknown
| |
d517
|
train
|
No, it's currently not possible to do dynamic configuration updates.
There's a Jira ticket for that exact issue here, and the accompanying KIP (Kafka Improvement Proposal).
|
unknown
| |
d519
|
train
|
find . -size +20000
The above one should work.
A: I guess you want to find files bigger than 1 Mb, then do
$ find . -size +1M
A: On Ubuntu, this works:
find . -type f -size +10k
The above would find all files in the current directory and below, being at least 10k.
A: This command tell you "the size" too :-)
find . -size +1000k -exec du -h {} \;
|
unknown
| |
d523
|
train
|
The Entity Framework uses only the information in the attribute to convert the method call to SQL. The implementation is not used in this case.
A: The EdmFunction attribute calls the specified method in SQL. The implementation you have in C# will be ignored. So in your case STR method is called at SQL end.
You can have your method as:
[EdmFunction("SqlServer", "STR")]
public static string ConvertToString(double? number)
{
throw new NotSupportedException("Direct calls not supported");
}
and still it would work.
See: EDM and Store functions exposed in LINQ
How it works
When a method with the EdmFunction attribute is detected within a LINQ
query expression, its treatment is identical to that of a function
within an Entity-SQL query. Overload resolution is performed with
respect to the EDM types (not CLR types) of the function arguments.
Ambiguous overloads, missing functions or lack of overloads result in
an exception. In addition, the return type of the method must be
validated. If the CLR return type does not have an implicit cast to
the appropriate EDM type, the translation will fail.
As a side note, you can also use SqlFunctions.StringConvert like:
var student = (from s in Students
where SqlFunctions.StringConvert((double) s.LanguageId)).Trim() == "2"
select s).FirstOrDefault();
|
unknown
| |
d537
|
train
|
Why not bundle a prebuilt Realm file as part of your application instead? To do this you'll need to:
*
*Create the prebuilt Realm file, either using Realm Browser or a simple Mac app of your own creation.
*Add the prebuilt Realm file to your app target in your Xcode project, ensuring that it appears in the Copy Bundle Resources build phase.
*Add code similar to that found in the above link to your app to have it open the prebuilt Realm file as read-only. Alternatively, you could copy the file out of your app bundle into the user's documents or cache directory and open it read-write.
|
unknown
| |
d539
|
train
|
Hibernate ORM 5.3 implements the JPA 2.2 standard.
Supported types from the Java 8 Date and Time API
The JPA 2.2 specification says that the following Java 8 types are supported:
*
*java.time.LocalDate
*java.time.LocalTime
*java.time.LocalDateTime
*java.time.OffsetTime
*java.time.OffsetDateTime
Hibernate ORM supports all these types, and even more:
*
*java.time.ZonedDateTime
*java.time.Duration
Entity mapping
Assuming you have the following entity:
@Entity(name = "DateTimeEntity")
public static class DateTimeEntity {
@Id
private Integer id;
@Column(name = "duration_value")
private Duration duration = Duration.of( 20, ChronoUnit.DAYS );
@Column(name = "instant_value")
private Instant instant = Instant.now();
@Column(name = "local_date")
private LocalDate localDate = LocalDate.now();
@Column(name = "local_date_time")
private LocalDateTime localDateTime = LocalDateTime.now();
@Column(name = "local_time")
private LocalTime localTime = LocalTime.now();
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime = OffsetDateTime.now();
@Column(name = "offset_time")
private OffsetTime offsetTime = OffsetTime.now();
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime = ZonedDateTime.now();
//Getters and setters omitted for brevity
}
The DateTimeEntity will have an associated database table that looks as follows:
CREATE TABLE DateTimeEntity (
id INTEGER NOT NULL,
duration_value BIGINT,
instant_value TIMESTAMP,
local_date DATE,
local_date_time TIMESTAMP,
local_time TIME,
offset_date_time TIMESTAMP,
offset_time TIME,
zoned_date_time TIMESTAMP,
PRIMARY KEY (id)
)
Source: Mapping Java 8 Date/Time entity attributes with Hibernate
A: Since version 2.2, JPA offers support for mapping Java 8 Date/Time API, like LocalDateTime, LocalTime, LocalDateTimeTime, OffsetDateTime or OffsetTime.
Also, even with JPA 2.1, Hibernate 5.2 supports all Java 8 Date/Time API by default.
In Hibernate 5.1 and 5.0, you have to add the hibernate-java8 Maven dependency.
So, let's assume we have the following Notification entity:
@Entity(name = "Notification")
@Table(name = "notification")
public class Notification {
@Id
private Long id;
@Column(name = "created_on")
private OffsetDateTime createdOn;
@Column(name = "notify_on")
private OffsetTime clockAlarm;
//Getters and setters omitted for brevity
}
Notice that the createdOn attribute is a OffsetDateTime Java object and the clockAlarm is of the OffsetTime type.
When persisting the Notification:
ZoneOffset zoneOffset = ZoneOffset.systemDefault().getRules()
.getOffset(LocalDateTime.now());
Notification notification = new Notification()
.setId(1L)
.setCreatedOn(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset)
).setClockAlarm(
OffsetTime.of(7, 30, 0, 0, zoneOffset)
);
entityManager.persist(notification);
Hibernate generates the proper SQL INSERT statement:
INSERT INTO notification (
notify_on,
created_on,
id
)
VALUES (
'07:30:00',
'2020-05-01 12:30:00.0',
1
)
When fetching the Notification entity, we can see that the OffsetDateTime and OffsetTime
are properly fetched from the database:
Notification notification = entityManager.find(
Notification.class, 1L
);
assertEquals(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset),
notification.getCreatedOn()
);
assertEquals(
OffsetTime.of(7, 30, 0, 0, zoneOffset),
notification.getClockAlarm()
);
|
unknown
| |
d541
|
train
|
You are getting key-value pair data.
access like this
let data = [
{"_id":{"$oid":"5def1f22b15556e4e9bdb345"},
"Time":{"$numberDouble":"1616180000000"},
"Image_Path":"1575946831220.jpg","permission":"Read:Write"},
{"_id":{"$oid":"5def1f22b15556e4e9bdb346"},
"Time":{"$numberDouble":"727672000000000000"},
"Image_Path":"8398393839313893.jpg","permission":"Read:Write"},
{"_id":{"$oid":"5def1f22b15556e4e9bdb347"},
"Time":{"$numberDouble":"84983500000000"},
"Image_Path":"82492849284984.jpg","permission":"Read:Write"}
]
let json = Object.values(data);
in reactjs
return (
<div>
{json.map(a =>
<div key={a.id}>
<h4>image path --{a.Image_Path}</h4>
<h6>Permission-- {a.permission}</h6>
</div>
)}
</div>
);
|
unknown
| |
d545
|
train
|
Check Nick's post about tagging blog posts. It covers all main tagging issues.
A: There is a modified django-tagging, probably it might work.
|
unknown
| |
d547
|
train
|
You'd need to add a listener to each row so that when the price or quantity are updated, you can get the new quantity and price and update the total column.
In jQuery, something like:
$('.row').on('change', function() {
var quantity = $('.quantity', this).val(), // get the new quatity
price = $('.price', this).val(), // get the new price
total = price*quantity;
$('.total', this).val(total); //set the row total
var totals = $.map($('.row .total'), function(tot) {
return tot.val(); // get each row total into an array
}).reduce(function(p,c){return p+c},0); // sum them
$('#total').val(totals); // set the complete total
});
This assumes that each order form row container has the class row, each quantity has the class quantity, each row total has the class total and the order form total has the id total.
|
unknown
| |
d549
|
train
|
To elaborate: destroying a QList will destroy the elements of the list. If the elements are pointers, the pointers themselves are destroyed, not the pointees. You can use qDeleteAll to delete the pointees.
(That will use operator delete, which is the right choice if and only if you're using operator new; malloc will always require free and operator new[] will always require operator delete[]).
That having been said, returning a QList by value won't destroy it, as its refcount won't drop to 0. Getting a crash there means it's very likely that you have some memory corruption. Use valgrind or similar tools to debug that.
|
unknown
| |
d553
|
train
|
You will need a xul browser object to load the content into.
Load the "view-source:" version of your page into a the browser object, in the same way as the "View Page Source" menu does. See function viewSource() in chrome://global/content/viewSource.js. That function can load from cache, or not.
Once the content is loaded, the original source is given by:
var source = browser.contentDocument.getElementById('viewsource').textContent;
Serialize a DOM Document
This method will not get the original source, but may be useful to some readers.
You can serialize the document object to a string. See Serializing DOM trees to strings in the MDC. You may need to use the alternate method of instantiation in your extension.
That article talks about XML documents, but it also works on any HTML DOMDocument.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(document);
This even works in a web page or the firebug console.
A: really looks like there is no way to get "all the sourcecode". You may use
document.documentElement.innerHTML
to get the innerHTML of the top element (usually html). If you have a php error message like
<h3>fatal error</h3>
segfault
<html>
<head>
<title>bla</title>
<script type="text/javascript">
alert(document.documentElement.innerHTML);
</script>
</head>
<body>
</body>
</html>
the innerHTML would be
<head>
<title>bla</title></head><body><h3>fatal error</h3>
segfault
<script type="text/javascript">
alert(document.documentElement.innerHTML);
</script></body>
but the error message would still retain
edit: documentElement is described here:
https://developer.mozilla.org/en/DOM/document.documentElement
A: You can get URL with var URL = document.location.href and navigate to "view-source:"+URL.
Now you can fetch the whole source code (viewsource is the id of the body):
var code = document.getElementById('viewsource').innerHTML;
Problem is that the source code is formatted. So you have to run strip_tags() and htmlspecialchars_decode() to fix it.
For example, line 1 should be the doctype and line 2 should look like:
<<span class="start-tag">HTML</span>>
So after strip_tags() it becomes:
<HTML>
And after htmlspecialchars_decode() we finally get expected result:
<HTML>
The code doesn't pass to DOM parser so you can view invalid HTML too.
A: Maybe you can get it via DOM, using
var source =document.getElementsByTagName("html");
and fetch the source using DOMParser
https://developer.mozilla.org/En/DOMParser
A: The first part of Sagi's answer, but use document.getElementById('viewsource').textContent instead.
A: More in line with Lachlan's answer, but there is a discussion of the internals here that gets quite in depth, going into the Cpp code.
http://www.mail-archive.com/[email protected]/msg05391.html
and then follow the replies at the bottom.
|
unknown
| |
d557
|
train
|
Of course you can send patches to anyone (git diff >file). However, branches contain commits (really, they're just a name for one commit and its ancestors come along for the ride), so it's meaningless to talk about sharing a branch without having committed anything.
|
unknown
| |
d561
|
train
|
You can use xargs with -P option to run any command in parallel:
seq 1 200 | xargs -n1 -P10 curl "http://localhost:5000/example"
This will run curl command 200 times with max 10 jobs in parallel.
A: Using xargs -P option, you can run any command in parallel:
xargs -I % -P 8 curl -X POST --header "http://localhost:5000/example" \
< <(printf '%s\n' {1..400})
This will run give curl command 400 times with max 8 jobs in parallel.
A: Adding to @saeed's answer, I created a generic function that utilises function arguments to fire commands for a total of N times in M jobs at a parallel
function conc(){
cmd=("${@:3}")
seq 1 "$1" | xargs -n1 -P"$2" "${cmd[@]}"
}
$ conc N M cmd
$ conc 10 2 curl --location --request GET 'http://google.com/'
This will fire 10 curl commands at a max parallelism of two each.
Adding this function to the bash_profile.rc makes it easier. Gist
A: Add “wait” at the end, and background them.
for ((request=1;request<=20;request++))
do
for ((x=1;x<=20;x++))
do
time curl -X POST --header "http://localhost:5000/example" &
done
done
wait
They will all output to the same stdout, but you can redirect the result of the time (and stdout and stderr) to a named file:
time curl -X POST --header "http://localhost:5000/example" > output.${x}.${request}.out 2>1 &
A: Wanted to share my example how I utilised parallel xargs with curl.
The pros from using xargs that u can specify how many threads will be used to parallelise curl rather than using curl with "&" that will schedule all let's say 10000 curls simultaneously.
Hope it will be helpful to smdy:
#!/bin/sh
url=/any-url
currentDate=$(date +%Y-%m-%d)
payload='{"field1":"value1", "field2":{},"timestamp":"'$currentDate'"}'
threadCount=10
cat $1 | \
xargs -P $threadCount -I {} curl -sw 'url= %{url_effective}, http_status_code = %{http_code},time_total = %{time_total} seconds \n' -H "Content-Type: application/json" -H "Accept: application/json" -X POST $url --max-time 60 -d $payload
.csv file has 1 value per row that will be inserted in json payload
A: Update 2020:
Curl can now fetch several websites in parallel:
curl --parallel --parallel-immediate --parallel-max 3 --config websites.txt
websites.txt file:
url = "website1.com"
url = "website2.com"
url = "website3.com"
A: This is an addition to @saeed's answer.
I faced an issue where it made unnecessary requests to the following hosts
0.0.0.1, 0.0.0.2 .... 0.0.0.N
The reason was the command xargs was passing arguments to the curl command. In order to prevent the passing of arguments, we can specify which character to replace the argument by using the -I flag.
So we will use it as,
... xargs -I '$' command ...
Now, xargs will replace the argument wherever the $ literal is found. And if it is not found the argument is not passed. So using this the final command will be.
seq 1 200 | xargs -I $ -n1 -P10 curl "http://localhost:5000/example"
Note: If you are using $ in your command try to replace it with some other character that is not being used.
A: Based on the solution provided by @isopropylcyanide and the comment by @Dario Seidl, I find this to be the best response as it handles both curl and httpie.
# conc N M cmd - fire (N) commands at a max parallelism of (M) each
function conc(){
cmd=("${@:3}")
seq 1 "$1" | xargs -I'$XARGI' -P"$2" "${cmd[@]}"
}
For example:
conc 10 3 curl -L -X POST https://httpbin.org/post -H 'Authorization: Basic dXNlcjpwYXNz' -H 'Content-Type: application/json' -d '{"url":"http://google.com/","foo":"bar"}'
conc 10 3 http --ignore-stdin -F -a user:pass httpbin.org/post url=http://google.com/ foo=bar
|
unknown
| |
d563
|
train
|
Is it possible that you accidentally cleared the "Shows Navigation Bar" setting in the Navigation Controller itself?
A: Have you tried deleting your current Navigation Controller in Storyboard and re-embedding your controller in it (or dragging a new Navigation Controller out and setting its default controller by control-dragging to your VC?)
|
unknown
| |
d565
|
train
|
Using a sub-query, this can be achieved as following:
q = (select([Item.identifier_id, func.count(Item.id).label("cnt")]).
group_by(Item.identifier_id).having(func.count(Item.id)>1)).alias("subq")
qry = (session.query(Item).join(q, Item.identifier_id==q.c.identifier_id))
print qry # prints SQL statement generated
items = qry.all() # result
A: Here is the version I am finally using:
from sqlalchemy.sql.functions import count
from sqlalchemy.orm import subqueryload
# …
repeats = (
select(
(Item.identifier,
count(Item.identifier)))
.group_by(Item.identifier)
.having(count(Item.identifier) > 1)
.alias())
for identifier in (
sess.query(Identifier)
.join(repeats, repeats.c.identifier==Identifier.value)
.options(subqueryload(Identifier.items))
):
for item in identifier.items:
pass
(Identifier is now mapped against a select and not backed by a database table, which makes import a bit faster too)
|
unknown
| |
d569
|
train
|
Yes. In-app purchase given by Microsoft is enough for selling apps in windows store. You don't need to worry about third party payment gateway etc.
refer to this link https://msdn.microsoft.com/en-in/library/windows/apps/jj206949(v=vs.105).aspx
examples given on this page are useful.
|
unknown
| |
d571
|
train
|
The following example disables the resizing of a tkinter GUI using the resizable method.
import tkinter as tk
class App(tk.Frame):
def __init__(self,master=None,**kw):
tk.Frame.__init__(self,master=master,**kw)
tk.Canvas(self,width=100,height=100).grid()
if __name__ == '__main__':
root = tk.Tk()
App(root).grid()
root.resizable(width=False,height=False)
root.mainloop()
A: Even though you have an answer, here's a shortened code, without classes (if you want):
from tkinter import Tk
root = Tk()
root.geometry("500x500")
root.resizable(False, False)
root.mainloop()
A: try this. It should help.
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width='you can decide', height='you can decide')
canvas.pack()
canvas.mainloop()
|
unknown
| |
d573
|
train
|
Why don't you use an npm package for screen recording?
Also your while loop doesn't represent seconds but discrete steps. If you want a time based recording you need some implementation which respects time based steps with step delta to allow adjustment for different rendering speeds. (This is similar to game loops, the only difference is that your action is screen captures and not moving game characters.)
A good screen recording package should do that, as well as providing an API for export. Save your time and effort and use a package for that.
Good point to start: https://www.npmjs.com/search?q=screen+recording
|
unknown
| |
d575
|
train
|
Why do you want to make it synchronous?
If you want to do something after members, just do it in callback function.
var callback=function(res){
retrived=retrieved.concat(res);
//continue do other things
};
client.smembers("offer", function (err, replies) {
if(!err){
callback(replies);
}
})
If you want to do something after a loop,you can try _.after of underscore.js,for example:
var times=10;
var arrayOfReplies=[]; //store all replies
var callback=function(){
//do something with arrayOfReplies
}
var afterAll = _.after(times,callback); //afterAll's callback is a function which will be run after be called 10 times
for(var i=0;i<10;i++){
client.smembers("offer", function (err, replies) {
if(!err){
arrayOfReplies=arrayOfReplies.concat(replies);
afterAll();
}
})
}
see more:http://underscorejs.org/#after
|
unknown
| |
d577
|
train
|
Don't use a regex for this. Instead, use parse_url() and parse_str().
$params = array();
$url= "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food";
$url_query = parse_url($url, PHP_URL_QUERY);
parse_str($url_query, $params);
echo $params['q']; // Outputs food
Demo
A: A perfect tutorial for what you're trying to accomplish:
$parts = parse_url('http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food');
parse_str($parts['query'], $query);
echo $query['q'];
|
unknown
| |
d583
|
train
|
ExecuteReader doesn't actually perform the query. The first call to .Read() will throw the error.
If you want to only catch the SqlException you can do the following:
Try
TestReader = TestSqlCommand.ExecuteReader()
TestReader.Read()
Catch ex As SqlException
Console.WriteLine("SQL error.")
Catch ex As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally")
End Try
A: For me this fixes the SSMS
exec sp_executesql N'select 1 where N''a'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'
exec sp_executesql N'select 1 where N''1'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'
I totally disagree with Rene Reader.
On my system it executes on ExecuteReader.
ExecuteReader would be a real bad name if it did not actually execute.
Did you consider that it is not catching and exception because it is not throwing an exception.
I know you see an error in SQL Profiler but if I introduce a syntax error it is caught.
This is C# but is is not throwing an exception for me.
And if I change it to:
"select 1 where N'a' = @p1";
Then it returns a row.
If I introduce a syntax error:
"select 1 whereX 1 = @p1";
Then it does throw an exception and it throws it on the ExecuteReader line.
If you want 1 to be a literal you should use:
"select 1 where '1' = @p1";
SQLcmd.CommandType = CommandType.Text;
SQLcmd.CommandText = "select 1 where N'1' = @p1";
SqlParameter TestSqlParameter = new SqlParameter();
TestSqlParameter.ParameterName = "@p1";
TestSqlParameter.SqlDbType = SqlDbType.NChar;
TestSqlParameter.Value = "a";
SQLcmd.Parameters.Add(TestSqlParameter);
try
{
rdr = SQLcmd.ExecuteReader();
Int32 waste;
if (rdr.HasRows)
{
while (rdr.Read())
{
waste = rdr.GetInt32(0);
}
}
}
catch (Exception Ex)
{
Debug.WriteLine(Ex.Message);
}
A: I solved this problem if the sql string passed used EXEC sp_executesql by ensuring I read every result and result set... like so:
....
using (var conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
using (var cmd = new SqlCommand(sql, conn))
{
cmd.CommandTimeout = 0;
using (var rdr = cmd.ExecuteReader())
{
// TODO: Do stuff with the rdr here.
FlushReader(rdr);
}
}
}
catch (Exception ex)
{
_logger.Fatal("Exception: {0}\r\nSQL:\r\n{1}", ex.Message, sql);
throw;
}
finally
{
conn.Close();
}
}
...
/// <summary>
/// Continue trying to read in case the server threw an exception.
/// </summary>
private static void FlushReader(IDataReader rdr)
{
while (rdr.Read())
{
}
while (rdr.NextResult())
{
while (rdr.Read())
{
}
}
}
Without calling the FlushReader method the application continues without throwing an exception of any kind. Even if I use a SQL THROW statement. Running the same sql in SQL management studio will show the error.
Hope this helps.
|
unknown
| |
d585
|
train
|
Just loop the number generation until it generated a new number:
int[] randomNum = new int[20];
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int number;
do
{
number = RandomNumber.Next(1, 80);
} while(randomNum.Contains(number));
randomNum[i] = number;
}
foreach (int j in randomNum)
{
Console.WriteLine("First Number:{0}", j);
Thread.Sleep(200);
}
A: According to your last comment, I would say:
for (int i = 0; i < 20; i++)
{
int num;
do
{
num = RandomNumber.Next(1, 80);
} while (randomNum.Contains(num));
randomNum[i] = num;
}
A: Why you used array for this? If you want to print random numbers, you can write this.
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int randomNum = RandomNumber.Next(1, 80);
Console.WriteLine("Number:{0}", randomNum);
Thread.Sleep(200);
}
A: you don't need in randomNum. Just do it so:
for (int i = 0; i < 20; i++)
{
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}
If you wanna avoid dublication, do so:
List<int> intList = new List();
for (int i = 0; i < 20; i++)
{
int r = RandomNumber.Next(1, 80);
foreach(int s in intList) if(s!=r){
intList.Add(s);
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}else i--;
}
|
unknown
| |
d587
|
train
|
The documentation page explains quite well how to setup d3 in your localhost.
You have to:
*
*include d3.js in your page using:
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
*start a python server if you want to access local files using:
python -m SimpleHTTPServer 8888 &
A: Thanks a lot for your suggestion.
But actually, The problem was that i did not put my javascript code in
$(document).ready(function(){//here})
It works great now :) ..
Thank you Christopher and FernOfTheAndes for all the help
|
unknown
| |
d589
|
train
|
You can map with sum, and get the sum of the result:
sum(map(sum, t))
# 6
Or if you prefer it with a for loop:
res = 0
for i in t:
res += sum(i)
print(res)
# 6
A: You can use simple iteration (works in python3.8, I assume it works on older versions as well).
t = ((1, 1), (1, 1), (1, 1))
sum_tuples = 0
for a,b in t:
sum_tuples += a # First element
sum_tuples += b # Second Element
print(sum_tuples) # prints 6
A: You could use itertools.chain
>>> import itertools
>>> t = ((1, 1), (1, 1), (1, 1))
>>> sum(itertools.chain.from_iterable(t))
6
A: You can loop tuple to sum all. This code is long but it can sum tuple in tuple.
t = ((1, 1), (1, 1), (1, 1))
# Tuple in tuple:
t = ((1, 1, (1, 1, (1, 1))))
def getsum(var, current = 0):
result = current
if type(var) == tuple:
for i in range(len(var)):
x = var[i]
result = getsum(x, result)
else:
result += var
return result
print(getsum(t))
|
unknown
| |
d591
|
train
|
Here is the code for an example 3d graph:
public void plot3d() {
JGnuplot jg = new JGnuplot();
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
zlabel = "z";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y = { 2, 4, 6, 8, 10 }, z = { 3, 6, 9, 12, 15 }, z2 = { 2, 8, 18, 32, 50 };
DataTableSet dts = plot.addNewDataTableSet("3D Plot");
dts.addNewDataTable("z=x+y", x, y, z);
dts.addNewDataTable("z=x*y", x, y, z2);
jg.execute(plot, jg.plot3d);
}
It produces the following figure:
Here are more examples: 2D Plot, Bar Plot, 3D Plot, Density Plot, Image Plot...
|
unknown
| |
d595
|
train
|
Solution is to use pdflatex and Sumatra PDF, since this viewer auto-reloads the file.
|
unknown
| |
d597
|
train
|
This is the Docs from https://msdn.microsoft.com/en-us/library/windows/desktop/gg537710(v=vs.85).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
IShellDispatch.BrowseForFolder( _
ByVal Hwnd As Integer, _
ByVal sTitle As BSTR, _
ByVal iOptions As Integer, _
[ ByVal vRootFolder As Variant ] _
) As FOLDER
and these are the flags see BIF_BROWSEINCLUDEURLS and BIF_SHAREABLE
ulFlags
Type: UINT
Flags that specify the options for the dialog box. This member can be 0 or a combination of the following values. Version numbers refer to the minimum version of Shell32.dll required for SHBrowseForFolder to recognize flags added in later releases. See Shell and Common Controls Versions for more information.
BIF_RETURNONLYFSDIRS (0x00000001)
0x00000001. Only return file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
Note The OK button remains enabled for "\\server" items, as well as "\\server\share" and directory items. However, if the user selects a "\\server" item, passing the PIDL returned by SHBrowseForFolder to SHGetPathFromIDList fails.
BIF_DONTGOBELOWDOMAIN (0x00000002)
0x00000002. Do not include network folders below the domain level in the dialog box's tree view control.
BIF_STATUSTEXT (0x00000004)
0x00000004. Include a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box. This flag is not supported when BIF_NEWDIALOGSTYLE is specified.
BIF_RETURNFSANCESTORS (0x00000008)
0x00000008. Only return file system ancestors. An ancestor is a subfolder that is beneath the root folder in the namespace hierarchy. If the user selects an ancestor of the root folder that is not part of the file system, the OK button is grayed.
BIF_EDITBOX (0x00000010)
0x00000010. Version 4.71. Include an edit control in the browse dialog box that allows the user to type the name of an item.
BIF_VALIDATE (0x00000020)
0x00000020. Version 4.71. If the user types an invalid name into the edit box, the browse dialog box calls the application's BrowseCallbackProc with the BFFM_VALIDATEFAILED message. This flag is ignored if BIF_EDITBOX is not specified.
BIF_NEWDIALOGSTYLE (0x00000040)
0x00000040. Version 5.0. Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized. The dialog box has several new capabilities, including: drag-and-drop capability within the dialog box, reordering, shortcut menus, new folders, delete, and other shortcut menu commands.
Note If COM is initialized through CoInitializeEx with the COINIT_MULTITHREADED flag set, SHBrowseForFolder fails if BIF_NEWDIALOGSTYLE is passed.
BIF_BROWSEINCLUDEURLS (0x00000080)
0x00000080. Version 5.0. The browse dialog box can display URLs. The BIF_USENEWUI and BIF_BROWSEINCLUDEFILES flags must also be set. If any of these three flags are not set, the browser dialog box rejects URLs. Even when these flags are set, the browse dialog box displays URLs only if the folder that contains the selected item supports URLs. When the folder's IShellFolder::GetAttributesOf method is called to request the selected item's attributes, the folder must set the SFGAO_FOLDER attribute flag. Otherwise, the browse dialog box will not display the URL.
BIF_USENEWUI
Version 5.0. Use the new user interface, including an edit box. This flag is equivalent to BIF_EDITBOX | BIF_NEWDIALOGSTYLE.
Note If COM is initialized through CoInitializeEx with the COINIT_MULTITHREADED flag set, SHBrowseForFolder fails if BIF_USENEWUI is passed.
BIF_UAHINT (0x00000100)
0x00000100. Version 6.0. When combined with BIF_NEWDIALOGSTYLE, adds a usage hint to the dialog box, in place of the edit box. BIF_EDITBOX overrides this flag.
BIF_NONEWFOLDERBUTTON (0x00000200)
0x00000200. Version 6.0. Do not include the New Folder button in the browse dialog box.
BIF_NOTRANSLATETARGETS (0x00000400)
0x00000400. Version 6.0. When the selected item is a shortcut, return the PIDL of the shortcut itself rather than its target.
BIF_BROWSEFORCOMPUTER (0x00001000)
0x00001000. Only return computers. If the user selects anything other than a computer, the OK button is grayed.
BIF_BROWSEFORPRINTER (0x00002000)
0x00002000. Only allow the selection of printers. If the user selects anything other than a printer, the OK button is grayed.
In Windows XP and later systems, the best practice is to use a Windows XP-style dialog, setting the root of the dialog to the Printers and Faxes folder (CSIDL_PRINTERS).
BIF_BROWSEINCLUDEFILES (0x00004000)
0x00004000. Version 4.71. The browse dialog box displays files as well as folders.
BIF_SHAREABLE (0x00008000)
0x00008000. Version 5.0. The browse dialog box can display sharable resources on remote systems. This is intended for applications that want to expose remote shares on a local system. The BIF_NEWDIALOGSTYLE flag must also be set.
BIF_BROWSEFILEJUNCTIONS (0x00010000)
0x00010000. Windows 7 and later. Allow folder junctions such as a library or a compressed file with a .zip file name extension to be browsed.
|
unknown
| |
d599
|
train
|
This should work for you:
notes_service.js
app.factory ('NoteService', function($http) {
return {
getAll: function() {
return $http.get('/notes.json').then(function(response) {
return response.data;
});
}
}
});
navCtrl.js
NotesService.getAll().then(function(res){
$scope.cleanArrayOfNotes = res.data;
});
Or, if you want to return the result rather than the promise, you can:
notes_service.js
app.factory ('NoteService', function($http) {
var notes = [];
var promise = $http.get('/notes.json').then(function(response) {
angular.copy(response.data, notes);
return notes;
});
return {
getAll: function() {
return notes;
},
promise: promise
}
});
navCtrl.js
// get array of notes
scope.cleanArrayOfNotes = NotesService.getAll();
// or use promise
NoteService.promise.then(function(response) {
scope.cleanArrayOfNotes = response.data;
});
|
unknown
| |
d601
|
train
|
For others who might find this thread, check out Mailpile. I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well.
A: You could try Quotient. It's a somewhat unusual webmail system, and it definitely won't fit into the same process as CherryPy - but it is in Python ;).
A: You can build one, using email for generating and parsing mail, imaplib for reading (and managing) incoming mail from your mail server, and smtplib for sending mail to the world.
A: Looking up webmail on pypi gives Posterity.
There is very probably some way to build a webmail with very little work using Zope3 components, or some other CMS.
I guess if you are writing a webapp, you are probably using one of the popular frameworks. We would need to know which one to give a more specific answer.
|
unknown
| |
d605
|
train
|
Try this:
context.Files.Where(x => x.Name == "test").ToList()
.ForEach( f => context.Files.Remove(f));
context.SaveChanges();
The RemoveAll may not compiled to SQL and not executed in SQL Server.
|
unknown
| |
d609
|
train
|
Ok so could make this work by redrawing the canvas in the function.
I don't really understand why the line got updated after the canvas.draw() call in the first function and why I have to redraw in the second function.
def changeLineThickness(self):
plt.setp(line, linewidth=1)
canvas.draw()
Maybe there is a faster way to do this rather than redrawing the whole canvas.
|
unknown
| |
d611
|
train
|
You can do next thing:
*
*php artisan make:command CustomServeCommand
*Then delete all from file and use this code:
<?php
namespace App\Console\Commands;
use Illuminate\Foundation\Console\ServeCommand;
use Symfony\Component\Console\Input\InputOption;
class CustomServeCommand extends ServeCommand
{
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '0.0.0.0'],//default 127.0.0.1
['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],
];
}
}
*php artisan serve
Link to the core file.
Basically, you will extend default class and adapt method to fit your own needs. This way you can set host and port per requirements.
|
unknown
| |
d613
|
train
|
Both MySQL and HTML files can work. Your choice should depend on how simple the data is, and how much you are storing.
Some considerations:
*
*Speed. The HTML files and include() approach is going to be faster. The file system is the fastest, simplest form of data persistence.
*Horizontal scalability. If you adopt the file system approach, you are more or less tied to the disk on that machine. With a separate database engine, you have the future option of running the database on separate cluster servers on the network.
*Meta Data. Do you need to store things like time of creation, which user created the HTML, how many times it has been viewed by other users? If so, you probably only have one realistic choice - a "proper" database. This can be MySQL or perhaps one of the NoSQL solutions.
*Data Consumption. Do you show the table in its entirety to other users? Or do you show selected parts of it? Possibly even different parts to different users? This impacts how you store data - the entire table as ONE entity, or each row as an entity, or each individual cell.
*TEXT or LONGTEXT? Of course only applicable if you're going with SQL. The only way to answer this is to know how many bytes you are expecting to store per "HTML fragment". Note that your character encoding also impacts the number of bytes stored. Refer to: TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes
Also note that in MySQL, each TEXT/LONGTEXT may also result in an I/O to the disk.
As for the concern:
The HTML must be preserved in its entirety.
As long as you don't escape the HTML at any point, you should be fine. At first glance, this violates a security best practice, but if you think about it, "not escaping HTML" is exactly what you want to do. The practice of escaping HTML output only helps to eliminate HTML syntax being parsed as HTML tags (potential malicious), but in your case, you don't want HTML syntax eliminated at all - you intentionally want <td> to be parsed into an actual HTML table cell. So do not escape anything and the example you gave should never occur.
Just note: although you do not HTML-escape the output, you still should filter your inputs. In essence, this means: before writing to your DB, check that the user input is indeed HTML. To enhance your application's security, it may also be wise to define rules for what can be stored in those table cells - perhaps no <iframe> or <a> allowed, no style attributes allowed etc. Also, watch out for SQL injection - use PDO and prepared statements if you're going PHP + MySQL.
A: Live by this rule: PHP is for formatting; MySQL is for data.
PHP is for building HTML. MySQL is useful as a persistent store for data from which PHP can build HTML.
I have built several systems with Apache+PHP+MySQL. Each page is PHP-generated HTML. I do not store <html tags> in MySQL, only data.
Some of my pages perform one SELECT; many pages perform a dozen or more. The performance is just fine. I use PHP subroutines to build <table>s. I construct style variations based on the data.
Let's use blue for this might be in some database table; PHP code would add the <div> tags around it.
A: Someone is going to come up with the php to do this correctly, but here's an idea.
*
*Learning a database is a separate exercise that should not be mixed with learning anything else. Leave MySQL out of this. If you want to go back and redo the project with it as a learning exercise, after you've spent some time learning the basics, go ahead.
*What you are going to want to do is to generate your table as a separate .php fragment, and then save it to the disk under a unique name that you can use to find it again later (maybe it is a date/time, maybe a number that keeps increasing, maybe a different way). After it is saved, you can then include it into your page as well as the other pages you want to include it. Getting that unique name may be a challenge, but that is a different question (and if you look around, probably already has an answer somewhere).
*If you know .php enough, the rest should be self explanatory. If you don't, then now is an excellent time to learn. If you have further questions, you can search stack overflow or google for the answers. Chances are, the answers are out there.
*Since I do know databases, there could be an interesting discussion that the other posters are trying to have with you about how to store the data. However, that discussion will only be really useful to you once you understand what we are trying to talk about. Besides, I bet it has already been asked at least once.
So try out that plan and come back and post how you did it for future readers. Happy coding.
A: What you want to do is absolutely not Three-tier architecture like said Rick James, you are mixing data and presentation.
But like in everything, it is up what you want to do and your strategy.
*
*Let say, if you are looking to build an application with specific mould of page with a specific space for an image with a specific data at this place and you want to maintain this same architecture for years, you should separate data and presentation. Most of the time, big companies, big applications are looking for this approch. Even if I know some big companies application, we have stored some HTML code in database.
*Now, if you want to be free to change every page design quickly, you can have HTML tag in your database.
For example, Wordpress has a lot of HTML tag in its table for years and it is still maintained and used by a lot of people. Saving HTML in database? According to your needs/strategy, it does not schock me.
*And for your information, in Wordpress a HTML post is saved as LONGTEXT.
*In this approach, like Wordpress, you will not have a strong database model, it will be messy and not really relationnal.
^^
A: I don't know how many tables are you planning to store, but if you don't need to make complicated operations like sorting or filtering you could just store them in files in a folder structure, that will consume less resources than MySQL and the entire file is preserved.
If you need many tables then don't store the HTML table, store a json with the info like this:
[
[
{
"content": "Let's use blue for this.",
"color": "blue"
},
{
"content": "Let's use red for this.",
"color": "red"
}
],
[
{
"content": "Another row.",
"color": "blue"
},
{
"content": "Another row.",
"color": "red"
}
]
]
And then rebuild it when you call it. Will use less space and will be faster to transfer.
If your tables are in a fixed format, then make a table with the fields you need.
A: I would recommend thinking of your table as a kind of object. SQL tables are meant to store relational data. As such, why not represent the table in that fashion? Below is a really basic example of how you could store a table of People data in SQL.
<table>
<thead>
<th>People ID</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>Doe</td>
</tr>
</tbody>
And then your SQL Table would store the encrypted string as follows (using JS):
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
var my_table = $('#table').html();
// Store this
var encrypted_string = utf8_to_b64(my_table);
// Decode as so
var table = b64_to_utf8(encrypted_string);
B64 encoding retrieved from here: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
|
unknown
| |
d615
|
train
|
There are multiple issues here:
*
*You cannot break a string in multiple lines the way you did.
*You're missing a ')' in the end of your swal call
*You're missing the title parameter, which is mandatory for swal
*The HTML must receive a boolean indicating that your message contains HTML code
I'm not very sure if you can create a form inside the SweetAlert, at least there are not examples in their page.
swal({background:'#ACF1F4', html:true, title:"<form method='post' id='loginform'>Username: <input id='username' name='username' style='width: 100%' ><br><br>Password:<input type='password' id='password' name='password'><br> <br></form>",
confirmButtonText: 'Submit',showCancelButton: true})
|
unknown
| |
d617
|
train
|
I would think this would work.
=TEXT(MIN(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd")
and
=TEXT(MAX(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd")
Your timestamps are coming from a system other than GoogleSheets. They need to be "forced" into numbers before they can be MIN()'d and MAX()'d. That's what 1* LEFT(... , 10) does.
Then they need to get turned back into text before they're concatenated in a text string like your plan. That's what TEXT(... ,"yyyy-mm-dd") does.
|
unknown
| |
d619
|
train
|
you can do as below
var objList = Context.sp_Temp().ToList();
var photoList = objList.Where(o=>o._int_previous == 1).ToList();
Or
you can cast the object to Class which build the object list as below
var photoList =
(from pht in objList
let x=>(sp_TempResult)pht
where x._int_previous == 1 select pht).ToList();
|
unknown
| |
d623
|
train
|
You must parse the referer. For exemple a google search query will contains: http://www.google.be/search?q=oostende+taxi&ie=UTF-8&oe=UTF-8&hl=en&client=safari
It's a real life query, yes I'm in Oostebde right now :)
See the query string. You can determine pretty easily what I was looking for.
Not all search engines are seo friendly, must major players are.
How to get the referer ? It depends on the script language you use.
A: You should use a tool like Google analytics.
A: Besides the Google Analytics, Google Webmaster Tools is also very useful. It can report a detail analysis of the search queries' impressions, clicks, CTR, position etc.
|
unknown
| |
d625
|
train
|
I think I got what you're trying to accomplish. First, you can't define a hook inside a function. What you can do is trigger the effect callback after at least one of its dependencies change.
useEffect(() => {
// run code whenever deps change
}, [deps])
Though for this particular problem (from what I understood from your description), I'd go something like this:
export default function Academics() {
let [currentOption, setCurrentOption] = useState()
function handleSelectOption(i) {
return () => setCurrentOption(i)
}
function clearSelectedOption() {
return setCurrentOption()
}
return (options.map((option, i) =>
<button
onClick={handleSelectOption(i)}
className={i === currentOption ? 'option option--highlight' : 'option'}
onBlur={clearSelectedOption}
></button>
))
}
|
unknown
| |
d635
|
train
|
The problem solved it self - I do not know why, but now everything is working properly, in the meantime Skype and some Windwos updates have been installed but I am not shure how this might affect the git system...
A: I have also encountered such problems. The solution is to start the Windows Update Service:
|
unknown
| |
d637
|
train
|
This should work:
var types = this.GetType().GetTypeInfo().Assembly.GetTypes()
.Where(t => t.GetTypeInfo().GetCustomAttribute<MyAttribute>() != null);
|
unknown
| |
d639
|
train
|
You can display 3 levels in 3 modules from the same menu, of course the second level's content will be determined by the first level selection; this will apply also to the third level.
However, please note that mod_menu used to have inadequate cache support, so by all means DO DISABLE the cache on the modules, else they won't work or will work funny (not showing the current page highlighted... changing the second menu "20" when you click on the first menu "3" ...)
A: Try the Splitmenu configuration of RocketTheme's RokNavMenu
Here's a discussion on how to accomplish that.
|
unknown
| |
d641
|
train
|
error in setting value using find function I'm a fairly inexperienced coder and have a small piece of code that is just falling over each time I run it (although I would swear it worked once and has since stopped!)
I am trying to find a value from a cell (which has a formulas to determine which value I need to find) in a range of cells elsewhere in the spreadsheet.
Originally my code was set as follows (when I think it worked) and I am getting an error message saying "Compile error: object required"
I tried to add the word Set in the appropriate place to stop that but then I get a runtime error 91 message saying object variable or with block variable not set.
My sub is in a class module set as option explicit and the code is as follows;
Dim StartRow As Integer
Dim EndRow As Integer
Set StartRow = Sheets("CHARTS").Range("T2:T9").Find(What:=Sheets("CHARTS").Range("O14").Value, LookIn:=xlValues, Lookat:=xlWhole).row
Set EndRow = Sheets("CHARTS").Range("T2:T9").Find(What:=Sheets("CHARTS").Range("O13").Value, LookIn:=xlValues, Lookat:=xlWhole).row
Any help gratefully received, I just can't see where I've gone wrong...!!
|
unknown
| |
d643
|
train
|
Very simple you have forgotten to place parantheses after myFunction.
your code should be:
<script>
function myFunction(){
document.getElementById('but').value = "changed";
}
</script>
A: This way it work. Function needs parenthesis
function myFunction() {
document.getElementById('but').value = "changed";
}
<html>
<body>
<input type="text" id="input" onkeypress="myFunction()">
<input type="button" value="Hallo" id="but">
</body>
</html>
an alternative way is
myFunction = function () {
document.getElementById('but').value = "changed";
}
|
unknown
| |
d651
|
train
|
You can try to launch the same activity but changing the content view (into onCreate) for each situation. Something like:
if (isLocked()) {
setContentView(R.layout.locker_activity);
} else {
setContentView(R.layout.settings_activity);
}
A: You can use just one activity as launcher and use Fragments to load what you want. Something like this:
public class LauncherActivity extends FragmentActivity {
super.onCreate(savedInstanceState);
Fragment fragment;
if (isLocked()) {
fragment = new LockerFragment();
}
else {
fragment = new SettingsFragmentFragment();
}
getFragmentManager().beginTransaction().add(R.id.container_id,fragment).commit();
}
|
unknown
| |
d653
|
train
|
This is pretty straightforward using rolling joins with data.table:
require(data.table) ## >= 1.9.2
setkey(setDT(d1), x) ## convert to data.table, set key for the column to join on
setkey(setDT(d2), x) ## same as above
d2[d1, roll=-Inf]
# x z y
# 1: 4 200 10
# 2: 6 200 20
# 3: 7 300 30
A: Input data:
d1 <- data.frame(x=c(4,6,7), y=c(10,20,30))
d2 <- data.frame(x=c(3,6,9), z=c(100,200,300))
You basically wish to extend d1 by a new column. So let's copy it.
d3 <- d1
Next I assume that d2$x is sorted nondecreasingly and thatmax(d1$x) <= max(d2$x).
d3$z <- sapply(d1$x, function(x) d2$z[which(x <= d2$x)[1]])
Which reads: for each x in d1$x, get the smallest value from d2$x which is not smaller than x.
Under these assumptions, the above may also be written as (& should be a bit faster):
d3$z <- sapply(d1$x, function(x) d2$z[which.max(x <= d2$x)])
In result we get:
d3
## x y z
## 1 4 10 200
## 2 6 20 200
## 3 7 30 300
EDIT1: Inspired by @MatthewLundberg's cut-based solution, here's another one using findInterval:
d3$z <- d2$z[findInterval(d1$x, d2$x+1)+1]
EDIT2: (Benchmark)
Exemplary data:
set.seed(123)
d1 <- data.frame(x=sort(sample(1:10000, 1000)), y=sort(sample(1:10000, 1000)))
d2 <- data.frame(x=sort(c(sample(1:10000, 999), 10000)), z=sort(sample(1:10000, 1000)))
Results:
microbenchmark::microbenchmark(
{d3 <- d1; d3$z <- d2$z[findInterval(d1$x, d2$x+1)+1] },
{d3 <- d1; d3$z <- sapply(d1$x, function(x) d2$z[which(x <= d2$x)[1]]) },
{d3 <- d1; d3$z <- sapply(d1$x, function(x) d2$z[which.max(x <= d2$x)]) },
{d1$x2 <- d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]; merge(d1, d2, by.x='x2', by.y='x')},
{d1a <- d1; setkey(setDT(d1a), x); d2a <- d2; setkey(setDT(d2a), x); d2a[d1a, roll=-Inf] }
)
## Unit: microseconds
## expr min lq median uq max neval
## findInterval 221.102 1357.558 1394.246 1429.767 17810.55 100
## which 66311.738 70619.518 85170.175 87674.762 220613.09 100
## which.max 69832.069 73225.755 83347.842 89549.326 118266.20 100
## cut 8095.411 8347.841 8498.486 8798.226 25531.58 100
## data.table 1668.998 1774.442 1878.028 1954.583 17974.10 100
A: cut can be used to find the appropriate matches in d2$x for the values in d1$x.
The computation to find the matches with cut is as follows:
as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))
## [1] 2 2 3
These are the values:
d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]
[1] 6 6 9
These can be added to d1 and the merge performed:
d1$x2 <- d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]
merge(d1, d2, by.x='x2', by.y='x')
## x2 x y z
## 1 6 4 10 200
## 2 6 6 20 200
## 3 9 7 30 300
The added column may then be removed, if desired.
A: Try: sapply(d1$x,function(y) d2$z[d2$x > y][which.min(abs(y - d2$x[d2$x > y]))])
|
unknown
| |
d669
|
train
|
You will have to maintain inner state with currently played video, and as soon as video is over, you will have to set next video in state which will re render the component again and start with next video. Below code should work.
import React from "react";
import ReactDOM from "react-dom";
import YouTube from '@u-wave/react-youtube';
import "./styles.css";
let videoIdList=["AOMpxsiUg2Q","XM-HJT8_esM","AOMpxsiUg2Q"];
class App extends React.Component {
constructor(props){
super(props);
this.state = {};
this.i = 0;
}
componentDidMount() {
this.setState({videoId: videoIdList[this.i]});
}
render() {
const opts = {
height: '390',
width: '640',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 1
}
};
return (
<YouTube
video={this.state.videoId}
opts={opts}
onReady={this._onReady}
onEnd={this._onEnd}
/>
);
}
_onEnd = () => {
this.setState({videoId: videoIdList[++this.i]});
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can check working code here -
https://codesandbox.io/s/7yk0vrzr36
|
unknown
| |
d671
|
train
|
A slight problem with the way you are setting things up is that the height of the element itself and the height of the background image (before you have sized it) are the same, and its drawing the gray for 6px from the top (the default direction for a linear-gradient) and the rest is transparent.
This snippet slightly simplifies what is going on.
It 'draws'a background image in the gray color, setting its width to 88% and its height to 6px and its position to bottom left. It sets it to not repeat on either axis.
body {
background: red;
}
.skeleton-6euk0cm7tfi:empty {
height: 100px;
background-color: #ffffff;
border-radius: 0px 0px 0px 0px;
background-image: linear-gradient( #676b6f, #676b6f);
background-repeat: no-repeat;
background-size: 88px 6px;
background-position: left bottom;
}
<
<div class="skeleton-6euk0cm7tfi"></div>
|
unknown
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.