According to the Twitter Bootstrap documentation: http://getbootstrap.com/css/#helper-classes-center
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4 center-block">
<button id="singlebutton" name="singlebutton" class="btn btn-primary center-block">
Next Step!
</button>
</div>
</div>
All the class center-block
does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from so will not center itself as anticipated.
See an example of the code above here: https://jsfiddle.net/Seany84/2j9pxt1z/
Should have checked, Once I included the jQuery UI Library it worked fine and was animating...
As far as I understand, you create a Movie class:
class Movie
{
private:
std::string _title;
std::string _director;
int _year;
int _rating;
std::vector<std::string> actors;
};
and having such class, you create a vector instance:
std::vector<Movie*> movies;
so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:
std::vector<shared_ptr<Movie>> movies;
libs and Assets folder in Android Studio:
Create libs folder inside app folder and Asset folder inside main in the project directory by exploring project directory.
Now come back to Android Studio and switch the combo box from Android to Project. enjoy...
Aside from the LINQ answers already given, I have a "SmartEnumerable" class which allows you to get the index and the "first/last"-ness. It's a bit ugly in terms of syntax, but you may find it useful.
We can probably improve the type inference using a static method in a nongeneric type, and implicit typing will help too.
Add These two lines in your text
android:ellipsize="end"
android:singleLine="true"
Usually String.Format("format", object) is preferable to object.ToString("format"). Therefore,
String.Format("{0:00000}", 15);
is preferable to,
Key = i.ToString("000000");
Well quite same question and there is also an answer =)
http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1
@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...
I can not test it currently so please test it =)
Also found some more:
http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/
Or you check the navigator with some javascript and generate / add a css file with javascript
This is the sample code for gitpull and gitpush using gitpython module.
import os.path
from git import *
import git, os, shutil
# create local Repo/Folder
UPLOAD_FOLDER = "LocalPath/Folder"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
print(UPLOAD_FOLDER)
new_path = os.path.join(UPLOADFOLDER)
DIR_NAME = new_path
REMOTE_URL = "GitURL" # if you already connected with server you dont need to give
any credential
# REMOTE_URL looks "[email protected]:path of Repo"
# code for clone
class git_operation_clone():
try:
def __init__(self):
self.DIR_NAME = DIR_NAME
self.REMOTE_URL = REMOTE_URL
def git_clone(self):
if os.path.isdir(DIR_NAME):
shutil.rmtree(DIR_NAME)
os.mkdir(DIR_NAME)
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
except Exception as e:
print(str(e))
# code for push
class git_operation_push():
def git_push_file(self):
try:
repo = Repo(DIR_NAME)
commit_message = 'work in progress'
# repo.index.add(u=True)
repo.git.add('--all')
repo.index.commit(commit_message)
origin = repo.remote('origin')
origin.push('master')
repo.git.add(update=True)
print("repo push succesfully")
except Exception as e:
print(str(e))
if __name__ == '__main__':
a = git_operation_push()
git_operation_push.git_push_file('')
git_operation_clone()
git_operation_clone.git_clone('')
Your problem is you have the b
in the open
flag.
The flag rt
(read, text) is the default, so, using the context manager, simply do this:
with open('sample.csv') as ifile:
read = csv.reader(ifile)
for row in read:
print (row)
The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.
The above is the same as:
with open('sample.csv', 'r') as ifile:
...
or
with open('sample.csv', 'rt') as ifile:
...
You can try:
unless defined?(var)
#ruby code goes here
end
=> true
Because it returns a boolean.
You can use 'True' or 'False' strings for simulate bolean type data.
Select *
From <table>
Where <columna> = 'True'
I think this way maybe slow than just put 1 because it's resolved with Convert_implicit function.
it works
Add this inside your head tag
<link rel="shortcut icon" href="http://example.com/myicon.png" />
It's not valid html (I don't think) but it seems to work if you create a custom attribute for the script tag in your webpage:
<script id="myScript" myCustomAttribute="some value" ....>
Then access the custom attribute in the javascript:
var myVar = document.getElementById( "myScript" ).getAttribute( "myCustomAttribute" );
Not sure if this is better or worse than parsing the script source string.
I don't exactly know how the stop stuff works. But I've got a gradient text example. Maybe this will help you out!
_you can also add more colors to the gradient if you want or just select other colors from the color generator
.rainbow2 {_x000D_
background-image: -webkit-linear-gradient(left, #E0F8F7, #585858, #fff); /* For Chrome and Safari */_x000D_
background-image: -moz-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Fx (3.6 to 15) */_x000D_
background-image: -ms-linear-gradient(left, #E0F8F7, #585858, #fff); /* For pre-releases of IE 10*/_x000D_
background-image: -o-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Opera (11.1 to 12.0) */_x000D_
background-image: linear-gradient(to right, #E0F8F7, #585858, #fff); /* Standard syntax; must be last */_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.rainbow {_x000D_
_x000D_
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>_x000D_
<br />_x000D_
<span class="rainbow2">No rainbow text</span>
_x000D_
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
Try to use this :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
{
txtBx.text += chBoxListTables.Items[i].ToString() + " \n";
}
}
For those that like to over-use LINQ.
(from f in new DirectoryInfo("C:/Temp").GetFiles()
where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(90))
select f
).ToList()
.ForEach(f => f.Delete());
replaceAll(String regex, String replacement)
Above method will help to get the answer.
String check = "Hello World";
check = check.replaceAll("o","");
Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.
Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto
link that lets them do that.
// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';
// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);
// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;
// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);
// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';
Note: the above assumes you are outputting to a text/html
document. If your output media type is text/json
then simply use $retval['url'] = $mailToUri;
because output encoding is handled by json_encode()
.
You should see:
"args": {
"token": "w%a&!e#\"^2(^@azW"
},
And of course this is the JSON representation of $token
above.
In Python 3.5 and newer use the new recursive **/
functionality:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)
When recursive
is set, **
followed by a path separator matches 0 or more subdirectories.
In earlier Python versions, glob.glob()
cannot list files in subdirectories recursively.
In that case I'd use os.walk()
combined with fnmatch.filter()
instead:
import os
import fnmatch
path = 'C:/Users/sam/Desktop/file1'
configfiles = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in fnmatch.filter(files, '*.txt')]
This'll walk your directories recursively and return all absolute pathnames to matching .txt
files. In this specific case the fnmatch.filter()
may be overkill, you could also use a .endswith()
test:
import os
path = 'C:/Users/sam/Desktop/file1'
configfiles = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in files if f.endswith('.txt')]
OTRS, Cerberus
random.sample
is another that can be used
import random
n = 1 # specify the no. of numbers
num = random.sample(range(10), n)
num[0] # is the required number
you can check ZBarSDK to reads QR Code and ECN/ISBN codes it's simple to integrate try the following code.
- (void)scanBarcodeWithZBarScanner
{
// ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
//Get the return value from controller
[reader setReturnBlock:^(BOOL value) {
}
and in didFinishPickingMediaWithInfo we get bar code value.
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
barcodeValue = symbol.data;
// EXAMPLE: do something useful with the barcode image
barcodeImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[_barcodeIV setImage:barcodeImage];
//set the values for to TextFields
[self setBarcodeValue:YES];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
[reader dismissViewControllerAnimated:YES completion:nil];
}
If somehow you want a simple, yet different solution, you can use the {**dict}
syntax:
from collections import OrderedDict
ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
regular = {**ordered}
To check if the javascript in nonexistant.js
returned no error you have to add a variable inside http://fail.org/nonexistant.js
like var isExecuted = true;
and then check if it exists when the script tag is loaded.
However if you only want to check that the nonexistant.js
returned without a 404 (meaning it exists), you can try with a isLoaded
variable ...
var isExecuted = false;
var isLoaded = false;
script_tag.onload = script_tag.onreadystatechange = function() {
if(!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") {
// script successfully loaded
isLoaded = true;
if(isExecuted) // no error
}
}
This will cover both cases.
If you've got 2FA enabled on your Github account, your regular password won't work for this purpose, but you can generate a Personal Access Token and use that in its place instead.
Visit the Settings
-> Developer Settings
-> Personal Access Tokens
page in GitHub (https://github.com/settings/tokens/new), and generate a new Token with all Repo permissions:
The page will then display the new token value. Save this value and use it in place of your password when pushing to your repository on GitHub:
> git push origin develop
Username for 'https://github.com': <your username>
Password for 'https://<your username>@github.com': <your personal access token>
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
If you have more than one view in the layout file android.R.layout.simple_list_item_1
then you'll have to pass the third argument android.R.id.text1
to specify the view that should be filled with the array elements (values). But if you have just one view in your layout file, there is no need to specify the third argument.
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
Places is a list and not a dictionary. This line below should therefore not work:
print data['places']['latitude']
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
print data['places'][0]['post code']
A good implementation of binary search tree, taken from here:
'''
A binary search Tree
'''
from __future__ import print_function
class Node:
def __init__(self, label, parent):
self.label = label
self.left = None
self.right = None
#Added in order to delete a node easier
self.parent = parent
def getLabel(self):
return self.label
def setLabel(self, label):
self.label = label
def getLeft(self):
return self.left
def setLeft(self, left):
self.left = left
def getRight(self):
return self.right
def setRight(self, right):
self.right = right
def getParent(self):
return self.parent
def setParent(self, parent):
self.parent = parent
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, label):
# Create a new Node
new_node = Node(label, None)
# If Tree is empty
if self.empty():
self.root = new_node
else:
#If Tree is not empty
curr_node = self.root
#While we don't get to a leaf
while curr_node is not None:
#We keep reference of the parent node
parent_node = curr_node
#If node label is less than current node
if new_node.getLabel() < curr_node.getLabel():
#We go left
curr_node = curr_node.getLeft()
else:
#Else we go right
curr_node = curr_node.getRight()
#We insert the new node in a leaf
if new_node.getLabel() < parent_node.getLabel():
parent_node.setLeft(new_node)
else:
parent_node.setRight(new_node)
#Set parent to the new node
new_node.setParent(parent_node)
def delete(self, label):
if (not self.empty()):
#Look for the node with that label
node = self.getNode(label)
#If the node exists
if(node is not None):
#If it has no children
if(node.getLeft() is None and node.getRight() is None):
self.__reassignNodes(node, None)
node = None
#Has only right children
elif(node.getLeft() is None and node.getRight() is not None):
self.__reassignNodes(node, node.getRight())
#Has only left children
elif(node.getLeft() is not None and node.getRight() is None):
self.__reassignNodes(node, node.getLeft())
#Has two children
else:
#Gets the max value of the left branch
tmpNode = self.getMax(node.getLeft())
#Deletes the tmpNode
self.delete(tmpNode.getLabel())
#Assigns the value to the node to delete and keesp tree structure
node.setLabel(tmpNode.getLabel())
def getNode(self, label):
curr_node = None
#If the tree is not empty
if(not self.empty()):
#Get tree root
curr_node = self.getRoot()
#While we don't find the node we look for
#I am using lazy evaluation here to avoid NoneType Attribute error
while curr_node is not None and curr_node.getLabel() is not label:
#If node label is less than current node
if label < curr_node.getLabel():
#We go left
curr_node = curr_node.getLeft()
else:
#Else we go right
curr_node = curr_node.getRight()
return curr_node
def getMax(self, root = None):
if(root is not None):
curr_node = root
else:
#We go deep on the right branch
curr_node = self.getRoot()
if(not self.empty()):
while(curr_node.getRight() is not None):
curr_node = curr_node.getRight()
return curr_node
def getMin(self, root = None):
if(root is not None):
curr_node = root
else:
#We go deep on the left branch
curr_node = self.getRoot()
if(not self.empty()):
curr_node = self.getRoot()
while(curr_node.getLeft() is not None):
curr_node = curr_node.getLeft()
return curr_node
def empty(self):
if self.root is None:
return True
return False
def __InOrderTraversal(self, curr_node):
nodeList = []
if curr_node is not None:
nodeList.insert(0, curr_node)
nodeList = nodeList + self.__InOrderTraversal(curr_node.getLeft())
nodeList = nodeList + self.__InOrderTraversal(curr_node.getRight())
return nodeList
def getRoot(self):
return self.root
def __isRightChildren(self, node):
if(node == node.getParent().getRight()):
return True
return False
def __reassignNodes(self, node, newChildren):
if(newChildren is not None):
newChildren.setParent(node.getParent())
if(node.getParent() is not None):
#If it is the Right Children
if(self.__isRightChildren(node)):
node.getParent().setRight(newChildren)
else:
#Else it is the left children
node.getParent().setLeft(newChildren)
#This function traversal the tree. By default it returns an
#In order traversal list. You can pass a function to traversal
#The tree as needed by client code
def traversalTree(self, traversalFunction = None, root = None):
if(traversalFunction is None):
#Returns a list of nodes in preOrder by default
return self.__InOrderTraversal(self.root)
else:
#Returns a list of nodes in the order that the users wants to
return traversalFunction(self.root)
#Returns an string of all the nodes labels in the list
#In Order Traversal
def __str__(self):
list = self.__InOrderTraversal(self.root)
str = ""
for x in list:
str = str + " " + x.getLabel().__str__()
return str
def InPreOrder(curr_node):
nodeList = []
if curr_node is not None:
nodeList = nodeList + InPreOrder(curr_node.getLeft())
nodeList.insert(0, curr_node.getLabel())
nodeList = nodeList + InPreOrder(curr_node.getRight())
return nodeList
def testBinarySearchTree():
r'''
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
'''
r'''
Example After Deletion
7
/ \
1 4
'''
t = BinarySearchTree()
t.insert(8)
t.insert(3)
t.insert(6)
t.insert(1)
t.insert(10)
t.insert(14)
t.insert(13)
t.insert(4)
t.insert(7)
#Prints all the elements of the list in order traversal
print(t.__str__())
if(t.getNode(6) is not None):
print("The label 6 exists")
else:
print("The label 6 doesn't exist")
if(t.getNode(-1) is not None):
print("The label -1 exists")
else:
print("The label -1 doesn't exist")
if(not t.empty()):
print(("Max Value: ", t.getMax().getLabel()))
print(("Min Value: ", t.getMin().getLabel()))
t.delete(13)
t.delete(10)
t.delete(8)
t.delete(3)
t.delete(6)
t.delete(14)
#Gets all the elements of the tree In pre order
#And it prints them
list = t.traversalTree(InPreOrder, t.root)
for x in list:
print(x)
if __name__ == "__main__":
testBinarySearchTree()
try {
// THIS for POST+JSON
options.contentType = 'application/json';
options.type = 'POST';
options.data = JSON.stringify(options.data);
// OR THIS for GET+URL-encoded
//options.data = $.param(_.clone(options.data));
console.log('.fetch options = ', options);
collection.fetch(options);
} catch (excp) {
alert(excp);
}
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
open command prompt
python pip install <package-name>
This should complete the process
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
Apple has added a new method for IOS 7 to simplify life a bit.
[mapView showAnnotations:yourAnnotationArray animated:YES];
You can easily pull from an array stored in the map view:
yourAnnotationArray = mapView.annotations;
and quickly adjust the camera too!
mapView.camera.altitude *= 1.4;
this won't work unless the user has iOS 7+ or OS X 10.9+ installed. check out custom animation here
You can use emojis
Done? | Name
:---:| ---
??| Nope
?| Yep
Just for the newcomers: the recent versions of C# allows the use of ?
operator to check nulls assignments
parentSplit = xNode.ParentNode.Attributes["split"]?.Value;
I was getting this error while using JQuery 1.10 and JQuery UI 1.8. I was able to resolve this error by updating to the latest JQuery UI 1.11.4.
sudo yum install fontconfig freetype libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6
<form name="add" method="post">
<p>Age:</p>
<select name="age">
<option value="1_sre">23</option>
<option value="2_sam">24</option>
<option value="5_john">25</option>
</select>
<input type="submit" name="submit"/>
</form>
You will have the selected value in $_POST['age']
, e.g. 1_sre
. Then you will be able to split the value and get the 'stud_name'
.
$stud = explode("_",$_POST['age']);
$stud_id = $stud[0];
$stud_name = $stud[1];
Just for the sake of completeness for C following the others explanations, not sure for C++.
x
int *p;
int const *p;
int * const p;
int const * const p;
int **pp;
int ** const pp;
int * const *pp;
int const **pp;
int * const * const pp;
int const ** const pp;
int const * const *pp;
int const * const * const pp;
// Example 1
int x;
x = 10;
int *p = NULL;
p = &x;
int **pp = NULL;
pp = &p;
printf("%d\n", **pp);
// Example 2
int x;
x = 10;
int *p = NULL;
p = &x;
int ** const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);
// Example 3
int x;
x = 10;
int * const p = &x; // Definition must happen during declaration
int * const *pp = NULL;
pp = &p;
printf("%d\n", **pp);
// Example 4
int const x = 10; // Definition must happen during declaration
int const * p = NULL;
p = &x;
int const **pp = NULL;
pp = &p;
printf("%d\n", **pp);
// Example 5
int x;
x = 10;
int * const p = &x; // Definition must happen during declaration
int * const * const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);
// Example 6
int const x = 10; // Definition must happen during declaration
int const *p = NULL;
p = &x;
int const ** const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);
// Example 7
int const x = 10; // Definition must happen during declaration
int const * const p = &x; // Definition must happen during declaration
int const * const *pp = NULL;
pp = &p;
printf("%d\n", **pp);
// Example 8
int const x = 10; // Definition must happen during declaration
int const * const p = &x; // Definition must happen during declaration
int const * const * const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);
Just keep going, but may the humanity excommunicate you.
int x = 10;
int *p = &x;
int **pp = &p;
int ***ppp = &pp;
int ****pppp = &ppp;
printf("%d \n", ****pppp);
I had a similar issue where I wanted a banner across the top of the screen that had one image on the left and a repeating image on the right to the edge of the screen. I ended up resolving it like so:
CSS:
.banner_left {
position: absolute;
top: 0px;
left: 0px;
width: 131px;
height: 150px;
background-image: url("left_image.jpg");
background-repeat: no-repeat;
}
.banner_right {
position: absolute;
top: 0px;
left: 131px;
right: 0px;
height: 150px;
background-image: url("right_repeating_image.jpg");
background-repeat: repeat-x;
background-position: top left;
}
The key was the right tag. I'm basically specifying that I want it to repeat from 131px in from the left to 0px from the right.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>
^[0-9]{1,2}[:.,-]?po$
Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.
Did you try list(x)??
y = '+123-456-7890'
c =list(y)
c
['+', '1', '2', '3', '-', '4', '5', '6', '-', '7', '8', '9', '0']
In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:
[formControlName]="'familyName'"
similar to below:
formControlName="familyName"
document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";
Will set the value for a year.
Attach an event handler to the submit event of the form. Make sure it cancels the default action.
Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.
Here is how you would do it in YUI 3:
<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function (Y) {
Y.one('form').on('submit', function (e) {
// Whatever else you want to do goes here
e.preventDefault();
});
});
</script>
Make sure that the server will pick up the slack if the JavaScript fails for any reason.
I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array
To access the attributes of an object is pretty easy:
alert(data.second);
But, if this does not completely answer your question, please clarify it and post back.
Thanks !
The function datepicker
is case sensitive and all lowercase. The following however works fine for me:
$(document).ready(function() {
$('.date-pick').datepicker( {
onSelect: function(date) {
alert(date);
},
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1
});
});
I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.
Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl
implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.
Change callSoapWebService
method first line to following.
SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();
I hope it will be helpful to others.
[object Object]
This means somewhere the object is being converted to a string.
Converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product + '');
Not converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product);
The .navbar-static-top
you are using forces your navbar
to become full-width. Remove that class and you will get a resizable navbar
. Then, you can wrap it in a span#
of the size you want.
<div class="container">
<div class="row">
<div class="span6 offset3">
<div class="navbar">
...
</div>
</div>
</div>
Here's an outline/boilerplate for describing the behavior of mapStateToProps
:
(This is a vastly simplified implementation of what a Redux container does.)
class MyComponentContainer extends Component {
mapStateToProps(state) {
// this function is specific to this particular container
return state.foo.bar;
}
render() {
// This is how you get the current state from Redux,
// and would be identical, no mater what mapStateToProps does
const { state } = this.context.store.getState();
const props = this.mapStateToProps(state);
return <MyComponent {...this.props} {...props} />;
}
}
and next
function buildReduxContainer(ChildComponentClass, mapStateToProps) {
return class Container extends Component {
render() {
const { state } = this.context.store.getState();
const props = mapStateToProps(state);
return <ChildComponentClass {...this.props} {...props} />;
}
}
}
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
If none of the above usual ways help you, look at the call trace underneath this error message ("fatal: This operation . . ."
) and locate the script and line which is raising the actual error. Once you locate that error() call, disable it and see if the operation you are trying completes even with some warnings/messages - ignore them for now. If so, finally after completing it might mention the part of the operation that was not completed successfully. Now, address this part separately as applicable.
Relating above logic to my case, I was getting this error message "fatal: This operation . . ."
when I was trying to get the Android-x86 code with repo sync . . .
. and the call trace showed raise GitError("cannot initialize work tree")
as the error() call causing the above error message ("fatal: . . ."
). So, after commenting that GitError()
in .repo/repo/project.py
, repo sync . . .
continued and finally indicated error for three projects that were not properly synced. I just deleted their *.git
folders from their relevant paths in the Android-x86 source tree locally and ran repo sync . . .
again and tasted success!
As you already hinted in your question, your code creates all promises synchronously. Instead they should only be created at the time the preceding one resolves.
Secondly, each promise that is created with new Promise
needs to be resolved with a call to resolve
(or reject
). This should be done when the timer expires. That will trigger any then
callback you would have on that promise. And such a then
callback (or await
) is a necessity in order to implement the chain.
With those ingredients, there are several ways to perform this asynchronous chaining:
With a for
loop that starts with an immediately resolving promise
With Array#reduce
that starts with an immediately resolving promise
With a function that passes itself as resolution callback
With ECMAScript2017's async
/ await
syntax
With ECMAScript2020's for await...of
syntax
See a snippet and comments for each of these options below.
for
You can use a for
loop, but you must make sure it doesn't execute new Promise
synchronously. Instead you create an initial immediately resolving promise, and then chain new promises as the previous ones resolve:
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
));
}
_x000D_
reduce
This is just a more functional approach to the previous strategy. You create an array with the same length as the chain you want to execute, and start out with an immediately resolving promise:
[...Array(10)].reduce( (p, _, i) =>
p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
))
, Promise.resolve() );
_x000D_
This is probably more useful when you actually have an array with data to be used in the promises.
Here we create a function and call it immediately. It creates the first promise synchronously. When it resolves, the function is called again:
(function loop(i) {
if (i < 10) new Promise((resolve, reject) => {
setTimeout( () => {
console.log(i);
resolve();
}, Math.random() * 1000);
}).then(loop.bind(null, i+1));
})(0);
_x000D_
This creates a function named loop
, and at the very end of the code you can see it gets called immediately with argument 0. This is the counter, and the i argument. The function will create a new promise if that counter is still below 10, otherwise the chaining stops.
The call to resolve()
will trigger the then
callback which will call the function again. loop.bind(null, i+1)
is just a different way of saying _ => loop(i+1)
.
async
/await
Modern JS engines support this syntax:
(async function loop() {
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
console.log(i);
}
})();
_x000D_
It may look strange, as it seems like the new Promise()
calls are executed synchronously, but in reality the async
function returns when it executes the first await
. Every time an awaited promise resolves, the function's running context is restored, and proceeds after the await
, until it encounters the next one, and so it continues until the loop finishes.
As it may be a common thing to return a promise based on a timeout, you could create a separate function for generating such a promise. This is called promisifying a function, in this case setTimeout
. It may improve the readability of the code:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
(async function loop() {
for (let i = 0; i < 10; i++) {
await delay(Math.random() * 1000);
console.log(i);
}
})();
_x000D_
for await...of
With EcmaScript 2020, the for await...of
found its way to modern JavaScript engines. Although it does not really reduce code in this case, it allows to isolate the definition of the random interval chain from the actual iteration of it:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function * randomDelays(count ,max) {
for (let i = 0; i < count; i++) yield delay(Math.random() * max).then(() => i);
}
(async function loop() {
for await (let i of randomDelays(10, 1000)) console.log(i);
})();
_x000D_
<ul>
<li style="color: #888;"><span style="color: #000">test</span></li>
</ul>
the big problem with this method is the extra markup. (the span tag)
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
For basic autocompletion, have a look at the files in %ProgramFiles%\Notepad++\plugins\APIs
. It's basically just an XML file with keywords in. If you want calltips ("function parameters hint"), check out these instructions.
I've never found any more documentation, but cpp.xml
has a calltip for fopen
, while php.xml
is quite complete.
As the comment stated, this is in C# not Java but the idea is the same. I've researched this issue extensively and ultimately the issue is, FindElement always returns an exception when the element doesn't exist. There isn't an overloaded option that allows you to get null or anything else. Here is why I prefer this solution over others.
It's actually a very simple and elegant once the method is created. By using FindElementSafe instead of FindElement, I don't "see" the ugly try/catch block and I can use a simple Exists method. That would look something like this:
IWebElement myLink = driver.FindElementSafe(By.Id("myId"));
if (myLink.Exists)
{
myLink.Click();
}
Here is how you extend IWebElement & IWebDriver
IWebDriver.FindElementSafe
/// <summary>
/// Same as FindElement only returns null when not found instead of an exception.
/// </summary>
/// <param name="driver">current browser instance</param>
/// <param name="by">The search string for finding element</param>
/// <returns>Returns element or null if not found</returns>
public static IWebElement FindElementSafe(this IWebDriver driver, By by)
{
try
{
return driver.FindElement(by);
}
catch (NoSuchElementException)
{
return null;
}
}
IWebElement.Exists
/// <summary>
/// Requires finding element by FindElementSafe(By).
/// Returns T/F depending on if element is defined or null.
/// </summary>
/// <param name="element">Current element</param>
/// <returns>Returns T/F depending on if element is defined or null.</returns>
public static bool Exists(this IWebElement element)
{
if (element == null)
{ return false; }
return true;
}
You could use polymorphism to modify the IWebDriver class instance of FindElement but that's a bad idea from a maintenance standpoint.
I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".
Regarding error: log4j:ERROR Element type "rollingPolicy" must be declared
log4j.dtd
defining rollingPolicy
.apache-log4j-extras-1.1.jar
I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:
home = System.getenv('HOME')
It helps to keep in mind that anything that works in pure Java will work in Gradle too.
There is also a set of predefined Android strings such as "Ok", "Cancel" and many others - so you don't have to declare all. They're available simply by:
getString(android.R.string.ok)
(In this case, "Ok" string). BTW there are also other Android resources available like for example icons images etc.
I had a similar issue with Visual Studio 2005, and my solution consisted of five projects in the following dependency (first built at top):
Video_Codec depends on nothing
Generic_Graphics depends on Video_Codec
SpecificAPI_Graphics depends on Generic_Graphics
Engine depends on Specific_Graphics
Application depends on Engine.
I was finding that the Video_Codec project wanted a full build even after a full clean then rebuild of the solution.
I fixed this by ensuring the pdb
output file of both the C/C++ and linker matched the location used by the other working projects. I also switched RTTI on.
First you should change the password using terminal. (username is postgres)
postgres=# \password postgres
Then you will be prompted to enter the password and confirm it.
Now you will be able to connect using pgadmin with the new password.
I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
Refer this link Get Keycode from key press and char value for any key code
$('input#inp').keyup(function(e){
$(this).val(String.fromCharCode(e.keyCode));
$('div#output').html('Keycode : ' + e.keyCode);
});
The thing here is - You have already another tomcat running on port 8080, you need to shut it down. You can do it in several ways. let me tell you 2 simplest ways
OR
You can as well look into PHP's get_browser();
http://php.net/manual/en/function.get-browser.php
Maybe you'll find it useful for more features.
You can use Files#readAllLines()
to get all lines of a text file into a List<String>
.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use String#split()
to split a String
in parts based on a regular expression.
for (String part : line.split("\\s+")) {
// ...
}
Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use Integer#valueOf()
to convert a String
into an Integer
.
Integer i = Integer.valueOf(part);
Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use List#add()
to add an element to a List
.
numbers.add(i);
Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines()
.
List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
.map(line -> line.split("\\s+")).flatMap(Arrays::stream)
.map(Integer::valueOf)
.collect(Collectors.toList());
Tutorial: Processing data with Java 8 streams
This problem comes when you are writing data in many files simultaneously and your Operating System has a fixed limit of Open files. In Linux, you can increase the limit of open files.
https://www.tecmint.com/increase-set-open-file-limits-in-linux/
Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.
Perhaps declare it above your first while
?
you need to iterate through the array's elements
float foo[] = {1, 2, 3, 10};
int i;
for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) {
printf("%lf\n",foo[i]);
}
or create a function that returns stacked sn printf
and then prints it with
printf("%s\n",function_that_makes_pretty_output(foo))
JNDI in layman's terms is basically an Interface for being able to get instances of internal/External resources such as
javax.sql.DataSource,
javax.jms.Connection-Factory,
javax.jms.QueueConnectionFactory,
javax.jms.TopicConnectionFactory,
javax.mail.Session, java.net.URL,
javax.resource.cci.ConnectionFactory,
or any other type defined by a JCA resource adapter. It provides a syntax in being able to create access whether they are internal or external. i.e (comp/env in this instance means where component/environment, there are lots of other syntax):
jndiContext.lookup("java:comp/env/persistence/customerDB");
Type $.fn.jquery
in your console and tell us what numbers it says. You probably have a second version running somewhere.
TL;DR: - grab the datatable from the dataset and read from the rows property.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn col = new DataColumn("Id", typeof(int));
dt.Columns.Add(col);
dt.Rows.Add(new object[] { 1 });
ds.Tables.Add(dt);
var row = ds.Tables[0].Rows[0];
//access the ID column.
var id = (int) row.ItemArray[0];
A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.
Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.
If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.
If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.
You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.
After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.
When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:
MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
//do some other work
The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!
There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.
The following works for a non-primary key mapping as well.
Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:
@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;
@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;
You are calling get with the wrong argument.
It should be:
Object value = field.get(object);
For others who wind up here like I did, you can use AJAX to do a PUT with parameters, but they are sent as the body, not as query strings.
In addition to answer by Dinesh Prajapati, Use
adb -d logcat <your package name>:<log level>
where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.
Now your command goes like:
adb -d logcat com.example.example:V > logfileName_WithPath.txt
You can use [ScriptIgnore]
:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public bool IsComplete
{
get { return Id > 0 && !string.IsNullOrEmpty(Name); }
}
}
Reference here
In this case the Id and then name will only be serialized
I assume that you want to read input from the console. If so, use Read-Host
.
iOS8+ (OBJECTIVE C)
#import <UserNotifications/UserNotifications.h>
[[UNUserNotificationCenter currentNotificationCenter]getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:{
break;
}
case UNAuthorizationStatusDenied:{
break;
}
case UNAuthorizationStatusAuthorized:{
break;
}
default:
break;
}
}];
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
This is universal code , no matter how your input is long but in same schema if there is : separator :)
var string = "firstName:name1, lastName:last1";
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
var b = i + 1, c = b/2, e = c.toString();
if(e.indexOf('.') != -1 ) {
empty[el] = arr[i+1];
}
});
console.log(empty)
I consider state to be for view only information and data that should persist beyond the view state is better stored as props. URL params are useful when you want to be able to link to a page or share the URL deep in to the app but otherwise clutter the address bar.
Take a look at Redux-Persist (if you're using redux) https://github.com/rt2zz/redux-persist
In my case, I had multiple spaces(fields were separated by one or more space) that I wanted to replace with a tab. The following did it:
:% s/\s\+/\t/g
You have by default the static
endpoint for static files. Also Flask
application has the following arguments:
static_url_path
: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder
folder.
static_folder
: the folder with static files that should be served at static_url_path
. Defaults to the 'static' folder in the root path of the application.
It means that the filename
argument will take a relative path to your file in static_folder
and convert it to a relative path combined with static_url_default
:
url_for('static', filename='path/to/file')
will convert the file path from static_folder/path/to/file
to the url path static_url_default/path/to/file
.
So if you want to get files from the static/bootstrap
folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Also look at url_for
documentation.
Update: req.param()
is now deprecated, so going forward do not use this answer.
Your answer is the preferred way to do it, however I thought I'd point out that you can also access url, post, and route parameters all with req.param(parameterName, defaultValue)
.
In your case:
var color = req.param('color');
From the express guide:
lookup is performed in the following order:
- req.params
- req.body
- req.query
Note the guide does state the following:
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
However in practice I've actually found req.param()
to be clear enough and makes certain types of refactoring easier.
Docker container exits if task inside is done, so if you want to keep it alive even if it does not have any job or already finished them, you can do docker run -di image
. After you do docker container ls
you will see it running.
1).For ASync :
var fs = require('fs');
fs.readFile(process.cwd()+"\\text.txt", function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
2).For Sync :
var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\\text.txt");
console.log(buffer.toString());
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
One other thing to check with your connection string - the model name. I was using two entity models, DB first. In the config I copied the entity connection for one, renamed it, and changed the connection string part. What I didn't change was the model name, so while the entity model generated correctly, when the context was initiated EF was looking in the wrong model for the entities.
Looks obvious written down, but there are four hours I won't get back.
It would be more helpful if you posed a more complete working (or in this case non-working) example.
I tried the following:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(1000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()
This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1]
.
Further, as per the hist
documentation (i.e. ax.hist?
from ipython
), I think the sum is fine too:
*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``. In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::
pdf, bins, patches = ax.hist(...)
print np.sum(pdf * np.diff(bins))
Giving this a try after the commands above:
np.sum(n * np.diff(bins))
I get a return value of 1.0
as expected. Remember that normed=True
doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n)
returned approx 7.2767
.
Or if you don't like branching, just negate the two parameters and add 180° to the answer.
(Adding 180° to the return value puts it nicely in the 0-360 range, but flips the angle. Negating both input parameters flips it back.)
try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.
or else you may use state based programming where an event occurs at a particular state of the browser..
select t.*
from (
select RequestID, max(CreatedDate) as MaxCreatedDate
from table1
group by RequestID
) tm
inner join table1 t on tm.RequestID = t.RequestID and tm.MaxCreatedDate = t.CreatedDate
<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
//$("form").submit(function(e){
$("#btn1").click(function(e){
e.preventDefault();
// alert('here');
$(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');
});
//}
});
</script>
</head>
<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>
<tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr>
<tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){
move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);
$fname = $_FILES['e5']['name'][$key];
$imgarryimp[]=$fname;
//echo $fname;
if(strlen($fname)>0)
{
$img = $fname;
}
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
}
exit;
// echo $values;exit;
//foreach($_POST['e1'] as $row)
//{
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
//}
//exit;
}
?>
</form>
<table>
<?php
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
Update
data
was re-introduced in RC.4
How do I pass data in Angular 2 components while using Routing?
DataTable
, DbDataReader
, or IEnumerable<SqlDataRecord>
objects can be used to populate a table-valued parameter per the MSDN article Table-Valued Parameters in SQL Server 2008 (ADO.NET).
The following example illustrates using either a DataTable
or an IEnumerable<SqlDataRecord>
:
SQL Code:
CREATE TABLE dbo.PageView
(
PageViewID BIGINT NOT NULL CONSTRAINT pkPageView PRIMARY KEY CLUSTERED,
PageViewCount BIGINT NOT NULL
);
CREATE TYPE dbo.PageViewTableType AS TABLE
(
PageViewID BIGINT NOT NULL
);
CREATE PROCEDURE dbo.procMergePageView
@Display dbo.PageViewTableType READONLY
AS
BEGIN
MERGE INTO dbo.PageView AS T
USING @Display AS S
ON T.PageViewID = S.PageViewID
WHEN MATCHED THEN UPDATE SET T.PageViewCount = T.PageViewCount + 1
WHEN NOT MATCHED THEN INSERT VALUES(S.PageViewID, 1);
END
C# Code:
private static void ExecuteProcedure(bool useDataTable,
string connectionString,
IEnumerable<long> ids)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "dbo.procMergePageView";
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter;
if (useDataTable) {
parameter = command.Parameters
.AddWithValue("@Display", CreateDataTable(ids));
}
else
{
parameter = command.Parameters
.AddWithValue("@Display", CreateSqlDataRecords(ids));
}
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "dbo.PageViewTableType";
command.ExecuteNonQuery();
}
}
}
private static DataTable CreateDataTable(IEnumerable<long> ids)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(long));
foreach (long id in ids)
{
table.Rows.Add(id);
}
return table;
}
private static IEnumerable<SqlDataRecord> CreateSqlDataRecords(IEnumerable<long> ids)
{
SqlMetaData[] metaData = new SqlMetaData[1];
metaData[0] = new SqlMetaData("ID", SqlDbType.BigInt);
SqlDataRecord record = new SqlDataRecord(metaData);
foreach (long id in ids)
{
record.SetInt64(0, id);
yield return record;
}
}
other than using this.form.submit()
you also submiting by id or name.
example i have form like this : <form action="" name="PostName" id="IdName">
By Name : <select onchange="PostName.submit()">
By Id : <select onchange="IdName.submit()">
You can use any
:
print any(df.column == 07311954)
True #true if it contains the number, false otherwise
If you rather want to see how many times '07311954' occurs in a column you can use:
df.column[df.column == 07311954].count()
Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable
using not empty operator on my dataModel
that extends javax.faces.model.ListDataModel
Code sample:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class EntityDataModel extends ListDataModel<Entity> implements
Collection<Entity>, SelectableDataModel<Entity>, Serializable {
public EntityDataModel(List<Entity> data) { super(data); }
@Override
public Entity getRowData(String rowKey) {
// In a real app, a more efficient way like a query by rowKey should be
// implemented to deal with huge data
List<Entity> entitys = (List<Entity>) getWrappedData();
for (Entity entity : entitys) {
if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
}
return null;
}
@Override
public Object getRowKey(Entity entity) {
return entity.getId();
}
@Override
public boolean isEmpty() {
List<Entity> entity = (List<Entity>) getWrappedData();
return (entity == null) || entity.isEmpty();
}
// ... other not implemented methods of Collection...
}
An array isn't immutable by nature; you can't make it constant.
The nearest you can get is:
var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }
Note the [...]
instead of []
: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
This is what helped me when I found myself in the same problem:
npm uninstall -g angular-cli @angular/cli
npm cache clean --force
npm install -g @angular/cli@latest
Templates:
Pass function name and argument.
<a href="{{ url_for('get_blog_post',id = blog.id)}}">{{blog.title}}</a>
View,function
@app.route('/blog/post/<string:id>',methods=['GET'])
def get_blog_post(id):
return id
If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's post).
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();
css example:
String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();
I had the same issue, so tried a few things. One of which seemed to work for me - removing the width and adding a float to the body tag.
May not work for all instances, but in the scenario I recently had, hiding overflow on content elements was a no go...
In Windows OS the following commands works for me.
mysql>Use <DatabaseName>
mysql>SOURCE C:/data/ScriptFile.sql;
No single quotes or double quotes around file name. Path would contain '/' instead of '\'.
You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).
It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)
You can do this using Ajax. I have a function that I use for something like this:
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.
Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.
<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">
Total: {{num1 + num2}}
and in js :
parseInt($scope.num1) + parseInt($scope.num2)
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
As the thread mentioned in the comment, get-command
in powershell can also work it out. For example, you can type get-command npm
and the output is as below:
Using function Find is cleaner way.
MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
....
}
Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.
You can read about what a unit is here: https://developers.google.com/youtube/v3/getting-started#quota
If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.
Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here: https://youtube-eng.googleblog.com/2012/09/the-youtube-api-on-stack-overflow_14.html
There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...
UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.
UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.
UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.
autoResetEvent.WaitOne()
is similar to
try
{
manualResetEvent.WaitOne();
}
finally
{
manualResetEvent.Reset();
}
as an atomic operation
The issue you are encountering is a documented feature of get_or_create
.
When using keyword arguments other than "defaults" the return value of get_or_create
is an instance. That's why it is showing you the parens in the return value.
you could use customer.source = Source.objects.get_or_create(name="Website")[0]
to get the correct value.
Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs
All the answers indicate the cause, but sometimes the bigger problem is identifying all the places that define an improper namespace. With tools like Resharper that automatically adjust the namespace using the folder structure, it is rather easy to encounter this issue.
You can get all the lines that create the issue by searching in project / solution using the following regex:
namespace .+\.TheNameUsedAsBothNamespaceAndType
I run cntlm
localy, configured with NTLMv2
password hashes to authenticate with the corporate proxy, and use
export MAVEN_OPTS="-DproxyHost=127.0.0.1 -DproxyPort=3128"
to use that proxy from maven
. Of course the proxy you use should support cntlm
/NTLMv2
.
Kotlin version with Gson
to read the response JSON:
val response = BufferedReader(
InputStreamReader(conn.inputStream, "UTF-8")
).use { it.readText() }
to parse response we can use Gson:
val model = Gson().fromJson(response, YourModelClass::class.java)
The use of @Qualifier will solve the issue.
Explained as below example :
public interface PersonType {} // MasterInterface
@Component(value="1.2")
public class Person implements PersonType { //Bean implementing the interface
@Qualifier("1.2")
public void setPerson(PersonType person) {
this.person = person;
}
}
@Component(value="1.5")
public class NewPerson implements PersonType {
@Qualifier("1.5")
public void setNewPerson(PersonType newPerson) {
this.newPerson = newPerson;
}
}
Now get the application context object in any component class :
Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id
you can the object of class of which qualifier id is passed.
This will also give you the project directory by navigating two levels up from the current executing directory (this won't return the project directory for every build, but this is the most common).
System.IO.Path.GetFullPath(@"..\..\")
Of course you would want to contain this inside some sort of validation/error handling logic.
This code can help you :
$(document).ready(function() {
$('#calendar').fullCalendar({
events:
[
{
id: 1,
title: 'First Event',
start: ...,
end: ...,
description: 'first description'
},
{
id: 2,
title: 'Second Event',
start: ...,
end: ...,
description: 'second description'
}
],
eventRender: function(event, element) {
element.find('.fc-title').append("<br/>" + event.description);
}
});
}
To scroll an element into view of a div, only if needed, you can use this scrollIfNeeded
function:
function scrollIfNeeded(element, container) {_x000D_
if (element.offsetTop < container.scrollTop) {_x000D_
container.scrollTop = element.offsetTop;_x000D_
} else {_x000D_
const offsetBottom = element.offsetTop + element.offsetHeight;_x000D_
const scrollBottom = container.scrollTop + container.offsetHeight;_x000D_
if (offsetBottom > scrollBottom) {_x000D_
container.scrollTop = offsetBottom - container.offsetHeight;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('btn').addEventListener('click', ev => {_x000D_
ev.preventDefault();_x000D_
scrollIfNeeded(document.getElementById('goose'), document.getElementById('container'));_x000D_
});
_x000D_
.scrollContainer {_x000D_
overflow-y: auto;_x000D_
max-height: 100px;_x000D_
position: relative;_x000D_
border: 1px solid red;_x000D_
width: 120px;_x000D_
}_x000D_
_x000D_
body {_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.box {_x000D_
margin: 5px;_x000D_
background-color: yellow;_x000D_
height: 25px;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
#goose {_x000D_
background-color: lime;_x000D_
}
_x000D_
<div id="container" class="scrollContainer">_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div id="goose" class="box">goose</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
</div>_x000D_
_x000D_
<button id="btn">scroll to goose</button>
_x000D_
Your format syntax is wrong actual syntax is
FORMAT ( value, format [, culture ] )
Please follow this link it helps you
I learned from this link, if you are using XP or greater that this will simply work by itself:
SET params = %~1
I could not get any of the other solutions here to work on Windows 7.
To iterate over them, I did this:
FOR %%A IN (%params%) DO (
ECHO %%A
)
Note: You will only get double quotes if you pass in arguments separated by a space typically.
@Transactional
uses in service layer which is called by using controller layer (@Controller
) and service layer call to the DAO layer (@Repository
) i.e data base related operation.
Here is a brief pointer on void
pointers: https://www.learncpp.com/cpp-tutorial/613-void-pointers/
6.13 — Void pointers
Because the void pointer does not know what type of object it is pointing to, it cannot be dereferenced directly! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
If a void pointer doesn't know what it's pointing to, how do we know what to cast it to? Ultimately, that is up to you to keep track of.
Void pointer miscellany
It is not possible to do pointer arithmetic on a void pointer. This is because pointer arithmetic requires the pointer to know what size object it is pointing to, so it can increment or decrement the pointer appropriately.
Assuming the machine's memory is byte-addressable and does not require aligned accesses, the most generic and atomic (closest to the machine level representation) way of interpreting a void*
is as a pointer-to-a-byte, uint8_t*
. Casting a void*
to a uint8_t*
would allow you to, for example, print out the first 1/2/4/8/however-many-you-desire bytes starting at that address, but you can't do much else.
uint8_t* byte_p = (uint8_t*)p;
for (uint8_t* i = byte_p; i < byte_p + 8; i++) {
printf("%x ",*i);
}
Change that import to
from matplotlib.pyplot import *
Note that this style of imports (from X import *
) is generally discouraged. I would recommend using the following instead:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
One clarification (and a point that confused me):
"remotes/origin/HEAD is the default branch" is not really correct.
remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.
Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.
Read up on the datetime module.
SilentGhost's answer has the details my answer leaves out and is reposted here:
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
You can just use padding. Like so:
http://jsfiddle.net/davidja/KG8Kv/
HTML
<table>
<tr>
<td>item1</td>
<td>item2</td>
<td>item2</td>
</tr>
</table>
CSS
td {padding:10px 25px 10px 25px;}
OR
tr td:first-child {padding-left:0px;}
td {padding:10px 0px 10px 50px;}
In Java 11, you have repeat
:
String s = " ";
s = s.repeat(1);
(Although at the time of writing still subject to change)
I finally found this solution from "Sven" and solved the problem. what I did was I included "bootstrap.min.js" with:
<script src="bootstrap.min.js"/>
instead of:
<script src="bootstrap.min.js"></script>
and it fixed the problem which looked really odd. can anyone explain why?
In Visual Studio .NET you can do Ctrl + K then C to comment, Crtl + K then U to uncomment a block.
I added
config.EnableCors(new EnableCorsAttribute(Properties.Settings.Default.Cors, "", ""))
as well as
app.UseCors(CorsOptions.AllowAll);
on the server. This results in two header entries. Just use the latter one and it works.
The ioctl
function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl
could be used to get the current font as well as set the font to a new one. A user application uses ioctl
to send a code to a printer telling it to return the current font or to set the font to a new one.
int ioctl(int fd, int request, ...)
fd
is file descriptor, the one returned by open
;request
is request code. e.g GETFONT
will get the current font from the printer, SETFONT
will set the font on the printer;void *
. Depending on the second argument, the third may or may not be present,
e.g. if the second argument is SETFONT
, the third argument can be the font name such as "Arial"
;int request
is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl
and then uses the request code in the device driver module to determine which action to perform.
A request code has 4 main parts
1. A Magic number - 8 bits
2. A sequence number - 8 bits
3. Argument type (typically 14 bits), if any.
4. Direction of data transfer (2 bits).
If the request code is SETFONT
to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial"
to the printer).
If the request code is GETFONT
, direction is from printer to the user application.
In order to generate a request code, Linux provides some predefined function-like macros.
1._IO(MAGIC, SEQ_NO)
both are 8 bits, 0 to 255, e.g. let us say we want to pause printer.
This does not require a data transfer. So we would generate the request code as below
#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM)
and now use ioctl
as
ret_val = ioctl(fd, PAUSE_PRIN);
The corresponding system call in the driver module will receive the code and pause the printer.
__IOW(MAGIC, SEQ_NO, TYPE)
MAGIC
and SEQ_NO
are the same as above, and TYPE
gives the type of the next argument, recall the third argument of ioctl
is void *
. W in __IOW
indicates that the data flow is from user application to driver module. As an example,
suppose we want to set the printer font to "Arial"
.#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
further,
char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font);
Now font
is a pointer, which means it is an address best represented as unsigned long
, hence the third part of _IOW
mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long
and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE)
and __IORW(MAGIC, SEQ_NO, TYPE)
where the data flow will be from kernel space to user space and both ways respectively.
Please let me know if this helps!
Open up the Windows task manager, kill the process named adb.exe, and re-launch your program.
Generally you cannot translate from a time zone like Asia/Kolkata to a GMT offset like +05:30 or +07:00. A time zone, as the name says, is a place on earth and comprises the historic, present and known future UTC offsets used by the people in that place (for now we can regard GMT and UTC as synonyms, strictly speaking they are not). For example, Asia/Kolkata has been at offset +05:30 since 1945. During periods between 1941 and 1945 it was at +06:30 and before that time at +05:53:20 (yes, with seconds precision). Many other time zones have summer time (daylight saving time, DST) and change their offset twice a year.
Given a point in time, we can make the translation for that particular point in time, though. I should like to provide the modern way of doing that.
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZoneOffset offsetIn1944 = LocalDateTime.of(1944, Month.JANUARY, 1, 0, 0)
.atZone(zone)
.getOffset();
System.out.println("Offset in 1944: " + offsetIn1944);
ZoneOffset offsetToday = OffsetDateTime.now(zone)
.getOffset();
System.out.println("Offset now: " + offsetToday);
Output when running just now was:
Offset in 1944: +06:30 Offset now: +05:30
For the default time zone set zone
to ZoneId.systemDefault()
.
To format the offset with the text GMT
use a formatter with OOOO
(four uppercase letter O) in the pattern:
DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("OOOO");
System.out.println(offsetFormatter.format(offsetToday));
GMT+05:30
I am recommending and in my code I am using java.time, the modern Java date and time API. The TimeZone
, Calendar
, Date
, SimpleDateFormat
and DateFormat
classes used in many of the other answers are poorly designed and now long outdated, so my suggestion is to avoid all of them.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).You can use this;
Form1 button1 click
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
this.Hide();
frm2.Show();
}
And add this to Form2
public string info = "";
Form2 button1 click
private void button1_Click(object sender, EventArgs e)
{
info = textBox1.Text;
this.Hide();
BeginInvoke(new MethodInvoker(() =>
{
Gogo();
}));
}
public void Gogo()
{
Form1 frm = new Form1();
frm.Show();
frm.Text = info;
}
You need to declare the Builder
inner class as static
.
Consult some documentation for both non-static inner classes and static inner classes.
Basically the non-static inner classes instances cannot exist without attached outer class instance.
If SelectionUnit="Cell"
try this:
string cellValue = GetSelectedCellValue();
Where:
public string GetSelectedCellValue()
{
DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
if (cellInfo == null) return null;
DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
if (column == null) return null;
FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
BindingOperations.SetBinding(element, TagProperty, column.Binding);
return element.Tag.ToString();
}
Seems like it shouldn't be that complicated, I know...
Edit: This doesn't seem to work on DataGridTemplateColumn
type columns. You could also try this if your rows are made up of a custom class and you've assigned a sort member path:
public string GetSelectedCellValue()
{
DataGridCellInfo cells = MyDataGrid.SelectedCells[0];
YourRowClass item = cells.Item as YourRowClass;
string columnName = cells.Column.SortMemberPath;
if (item == null || columnName == null) return null;
object result = item.GetType().GetProperty(columnName).GetValue(item, null);
if (result == null) return null;
return result.ToString();
}
Set a flag on hover:
var over = false;
$('#elem').hover(function() {
over = true;
},
function () {
over = false;
});
Then just check your flag.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
LIMIT 1
is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order
clause in an outer query).
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
You can use the version in Windows SDK but sometimes it might not be the same version of the .NET Framework your using, getting you the following error:
Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
In .NET 4.0 you'll need to search inside Microsoft SDK v8.0A, e.g.: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (in my case I only have the 32 bit version installed by Visual Studio 2012).
I had successfully used the following on Arch Linux (where the -a
flag is used for attachments) for several years:
mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html
This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s
subject. Presumably, this was done to improve security.
Instead of relying on hacking the subject line, I now use a bash subshell:
(
echo -e "Content-Type: text/html\n"
cat mail.html
) | mail -s "The Subject" -t [email protected]
And since we are really only using mailx
's subject flag, it seems there is no reason not to switch to sendmail
as suggested by @dogbane:
(
echo "To: [email protected]"
echo "Subject: The Subject"
echo "Content-Type: text/html"
echo
cat mail.html
) | sendmail -t
The use of bash subshells avoids having to create a temporary file.
Use MouseClick event instead of Click
This stored procedure will provide you with a hierarchical tree of relationship. Based on this article from Technet. It will also optionally provide you a query for reading or deleting all the related data.
IF OBJECT_ID('GetForeignKeyRelations','P') IS NOT NULL
DROP PROC GetForeignKeyRelations
GO
CREATE PROC GetForeignKeyRelations
@Schemaname Sysname = 'dbo'
,@Tablename Sysname
,@WhereClause NVARCHAR(2000) = ''
,@GenerateDeleteScripts bit = 0
,@GenerateSelectScripts bit = 0
AS
SET NOCOUNT ON
DECLARE @fkeytbl TABLE
(
ReferencingObjectid int NULL
,ReferencingSchemaname Sysname NULL
,ReferencingTablename Sysname NULL
,ReferencingColumnname Sysname NULL
,PrimarykeyObjectid int NULL
,PrimarykeySchemaname Sysname NULL
,PrimarykeyTablename Sysname NULL
,PrimarykeyColumnname Sysname NULL
,Hierarchy varchar(max) NULL
,level int NULL
,rnk varchar(max) NULL
,Processed bit default 0 NULL
);
WITH fkey (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk)
AS
(
SELECT
soc.object_id
,scc.name
,soc.name
,convert(sysname,null)
,convert(int,null)
,convert(sysname,null)
,convert(sysname,null)
,convert(sysname,null)
,CONVERT(VARCHAR(MAX), scc.name + '.' + soc.name ) as Hierarchy
,0 as level
,rnk=convert(varchar(max),soc.object_id)
FROM SYS.objects soc
JOIN sys.schemas scc
ON soc.schema_id = scc.schema_id
WHERE scc.name =@Schemaname
AND soc.name =@Tablename
UNION ALL
SELECT sop.object_id
,scp.name
,sop.name
,socp.name
,soc.object_id
,scc.name
,soc.name
,socc.name
,CONVERT(VARCHAR(MAX), f.Hierarchy + ' --> ' + scp.name + '.' + sop.name ) as Hierarchy
,f.level+1 as level
,rnk=f.rnk + '-' + convert(varchar(max),sop.object_id)
FROM SYS.foreign_key_columns sfc
JOIN Sys.Objects sop
ON sfc.parent_object_id = sop.object_id
JOIN SYS.columns socp
ON socp.object_id = sop.object_id
AND socp.column_id = sfc.parent_column_id
JOIN sys.schemas scp
ON sop.schema_id = scp.schema_id
JOIN SYS.objects soc
ON sfc.referenced_object_id = soc.object_id
JOIN SYS.columns socc
ON socc.object_id = soc.object_id
AND socc.column_id = sfc.referenced_column_id
JOIN sys.schemas scc
ON soc.schema_id = scc.schema_id
JOIN fkey f
ON f.ReferencingObjectid = sfc.referenced_object_id
WHERE ISNULL(f.PrimarykeyObjectid,0) <> f.ReferencingObjectid
)
INSERT INTO @fkeytbl
(ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk)
SELECT ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk
FROM fkey
SELECT F.Relationshiptree
FROM
(
SELECT DISTINCT Replicate('------',Level) + CASE LEVEL WHEN 0 THEN '' ELSE '>' END + ReferencingSchemaname + '.' + ReferencingTablename 'Relationshiptree'
,RNK
FROM @fkeytbl
) F
ORDER BY F.rnk ASC
-------------------------------------------------------------------------------------------------------------------------------
-- Generate the Delete / Select script
-------------------------------------------------------------------------------------------------------------------------------
DECLARE @Sql VARCHAR(MAX)
DECLARE @RnkSql VARCHAR(MAX)
DECLARE @Jointables TABLE
(
ID INT IDENTITY
,Object_id int
)
DECLARE @ProcessTablename SYSNAME
DECLARE @ProcessSchemaName SYSNAME
DECLARE @JoinConditionSQL VARCHAR(MAX)
DECLARE @Rnk VARCHAR(MAX)
DECLARE @OldTablename SYSNAME
IF @GenerateDeleteScripts = 1 or @GenerateSelectScripts = 1
BEGIN
WHILE EXISTS ( SELECT 1
FROM @fkeytbl
WHERE Processed = 0
AND level > 0 )
BEGIN
SELECT @ProcessTablename = ''
SELECT @Sql = ''
SELECT @JoinConditionSQL = ''
SELECT @OldTablename = ''
SELECT TOP 1 @ProcessTablename = ReferencingTablename
,@ProcessSchemaName = ReferencingSchemaname
,@Rnk = RNK
FROM @fkeytbl
WHERE Processed = 0
AND level > 0
ORDER BY level DESC
SELECT @RnkSql ='SELECT ' + REPLACE (@rnk,'-',' UNION ALL SELECT ')
DELETE FROM @Jointables
INSERT INTO @Jointables
EXEC(@RnkSql)
IF @GenerateDeleteScripts = 1
SELECT @Sql = 'DELETE [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10)
IF @GenerateSelectScripts = 1
SELECT @Sql = 'SELECT [' + @ProcessSchemaName + '].[' + @ProcessTablename + '].*' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10)
SELECT @JoinConditionSQL = @JoinConditionSQL
+ CASE
WHEN @OldTablename <> f.PrimarykeyTablename THEN 'JOIN [' + f.PrimarykeySchemaname + '].[' + f.PrimarykeyTablename + '] ' + CHAR(10) + ' ON '
ELSE ' AND '
END
+ ' [' + f.PrimarykeySchemaname + '].[' + f.PrimarykeyTablename + '].[' + f.PrimarykeyColumnname + '] = [' + f.ReferencingSchemaname + '].[' + f.ReferencingTablename + '].[' + f.ReferencingColumnname + ']' + CHAR(10)
, @OldTablename = CASE
WHEN @OldTablename <> f.PrimarykeyTablename THEN f.PrimarykeyTablename
ELSE @OldTablename
END
FROM @fkeytbl f
JOIN @Jointables j
ON f.Referencingobjectid = j.Object_id
WHERE charindex(f.rnk + '-',@Rnk + '-') <> 0
AND F.level > 0
ORDER BY J.ID DESC
SELECT @Sql = @Sql + @JoinConditionSQL
IF LTRIM(RTRIM(@WhereClause)) <> ''
SELECT @Sql = @Sql + ' WHERE (' + @WhereClause + ')'
PRINT @SQL
PRINT CHAR(10)
UPDATE @fkeytbl
SET Processed = 1
WHERE ReferencingTablename = @ProcessTablename
AND rnk = @Rnk
END
IF @GenerateDeleteScripts = 1
SELECT @Sql = 'DELETE FROM [' + @Schemaname + '].[' + @Tablename + ']'
IF @GenerateSelectScripts = 1
SELECT @Sql = 'SELECT * FROM [' + @Schemaname + '].[' + @Tablename + ']'
IF LTRIM(RTRIM(@WhereClause)) <> ''
SELECT @Sql = @Sql + ' WHERE ' + @WhereClause
PRINT @SQL
END
SET NOCOUNT OFF
go
Use jQuery.find() to find children more than one level deep.
The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.
$('#google_translate_element').find('*').unbind('click');
You need the '*'
in find()
:
Unlike in the rest of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.
Here you go, options have values, label and css classes that gets reflected on parent element upon selection.
$(document).on('click','.update_app_status', function (e) {
let $div = $(this).parent().parent();
let $btn = $div.find('.vBtnMain');
let $btn2 = $div.find('.vBtnArrow');
let cssClass = $(this).data('status_class');
let status_value = $(this).data('status_value');
let status_label = $(this).data('status_label');
$btn.html(status_label);
$btn.removeClass();
$btn2.removeClass();
$btn.addClass('btn btn-sm vBtnMain '+cssClass);
$btn2.addClass('btn btn-sm vBtnArrow dropdown-toggle dropdown-toggle-split '+cssClass);
$div.removeClass('show');
$div.find('.dropdown-menu').removeClass('show');
e.preventDefault();
return false;
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group">
<button type="button" class="btn btn-sm vBtnMain btn-warning">Awaiting Review</button>
<button type="button" class="btn btn-sm vBtnArrow btn-warning dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item update_app_status" data-status_class="btn-warning" data-status_value="1" data-status_label="Awaiting Review" href="#">Awaiting Review</a>
<a class="dropdown-item update_app_status" data-status_class="btn-info" data-status_value="2" data-status_label="Reviewed" href="#">Reviewed</a>
<a class="dropdown-item update_app_status" data-status_class="btn-dark" data-status_value="3" data-status_label="Contacting" href="#">Contacting</a>
<a class="dropdown-item update_app_status" data-status_class="btn-success" data-status_value="4" data-status_label="Hired" href="#">Hired</a>
<a class="dropdown-item update_app_status" data-status_class="btn-danger" data-status_value="5" data-status_label="Rejected" href="#">Rejected</a>
</div>
</div>
_x000D_
Try:
<table border="1">
<tr>
<td>
<table border="">
...
</table>
</td>
</tr>
</table>
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
First off, run
npm init
...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.
Then, once you have a package.json file, use
npm install <pkg> --save
or
npm install <pkg> --save-dev
...to install a dependency and automatically append it to your package.json
's dependencies
list.
(Note: You may need to manually tweak the version ranges for your dependencies.)
You can use font face like this:
@font-face {
font-family:"Name-Of-Font";
src: url("yourfont.ttf") format("truetype");
}
First you should to make the following commands:
Step 1:
php artisan migrate:rollback
Step 2:
php artisan migrate
Your table will be back in database .
You can do it like this:
alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'
Check out a working example here: http://jsfiddle.net/LtjzW/1/
I usually go with PNG, as it seems to have a few advantages over GIF. There used to be patent restrictions on GIF, but those have expired.
GIFs are suitable for sharp-edged line art (such as logos) with a limited number of colors. This takes advantage of the format's lossless compression, which favors flat areas of uniform color with well defined edges (in contrast to JPEG, which favors smooth gradients and softer images).
GIFs can be used for small animations and low-resolution film clips.
In view of the general limitation on the GIF image palette to 256 colors, it is not usually used as a format for digital photography. Digital photographers use image file formats capable of reproducing a greater range of colors, such as TIFF, RAW or the lossy JPEG, which is more suitable for compressing photographs.
The PNG format is a popular alternative to GIF images since it uses better compression techniques and does not have a limit of 256 colors, but PNGs do not support animations. The MNG and APNG formats, both derived from PNG, support animations, but are not widely used.
You can use jquery-validate.js . The following is the code snippet from jquery-validate.js.
// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
var pendingRequests = {},
ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
$.ajaxPrefilter(function( settings, _, xhr ) {
var port = settings.port;
if ( settings.mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = xhr;
}
});
} else {
// Proxy ajax
ajax = $.ajax;
$.ajax = function( settings ) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if ( mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = ajax.apply(this, arguments);
return pendingRequests[port];
}
return ajax.apply(this, arguments);
};
}
So that you just only need to set the parameter mode to abort when you are making ajax request.
Ref:https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js
Another variant of a solution, using assembly language, is an external procedure. This example for unsigned integer multiplication using g++ and fasm under Linux x64.
This procedure multiplies two unsigned integer arguments (32 bits) (according to specification for amd64 (section 3.2.3 Parameter Passing).
If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8, and %r9 is used
(edi and esi registers in my code)) and returns the result or 0 if an overflow has occured.
format ELF64
section '.text' executable
public u_mul
u_mul:
MOV eax, edi
mul esi
jnc u_mul_ret
xor eax, eax
u_mul_ret:
ret
Test:
extern "C" unsigned int u_mul(const unsigned int a, const unsigned int b);
int main() {
printf("%u\n", u_mul(4000000000,2)); // 0
printf("%u\n", u_mul(UINT_MAX/2,2)); // OK
return 0;
}
Link the program with the asm object file. In my case, in Qt Creator, add it to LIBS
in a .pro file.
When you create a new File
, you are supposed to provide the file name, not only the directory you want to put your file in.
Try with something like
File file = new File("D:/Data/" + item.getFileName());
The simple solution is to install Python 3. I think why you have this problem is because you are using Python 2. I did this and it worked.
When installing Python 3, make sure to select PIP. It installs it with Python.
1.Install angular-animate
2.Add the animation effect to the class ng-enter
for page entering animation and the class ng-leave
for page exiting animation
for reference: this page has a free resource on angular view transition https://e21code.herokuapp.com/angularjs-page-transition/
in Kotlin :
val jsonArrayString = "['A','B','C']"
val gson = Gson()
val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
val stringList : List<String> = gson.fromJson(
jsonArrayString,
listType)
Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.
See http://www.json.org/ for the specifications.
Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.
When you create a stored routine that has a BEGIN...END
block, statements within the block are terminated by semicolon (;)
. But the CREATE PROCEDURE
statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE
, or terminates one of the statements within the body of the procedure.
The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE
statement.
If you have another list that contains all the items you would like to add you can do arList.addAll(otherList)
. Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll()
method, with something like
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));
or, if you don't want to create that unnecessary array:
arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
Otherwise you will have to have some sort of loop that adds the values to the list individually.
Here's my working approach using zsh. Tested on OSX:
# Calculation dates
## A random old date
START_DATE="2015-11-15"
## Today's date
TODAY=$(date +%Y-%m-%d)
# Import zsh date mod
zmodload zsh/datetime
# Calculate number of days
DIFF=$(( ( $(strftime -r %Y-%m-%d $TODAY) - $(strftime -r %Y-%m-%d $START_DATE) ) / 86400 ))
echo "Your value: " $DIFF
Result:
Your value: 1577
Basically, we use strftime
reverse (-r
) feature to transform our date string back to a timestamp, then we make our calculation.
Take a look at the java.text.MessageFormat
class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.
Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);
Make sure that your sas.png
is marked as Build Action: Content
and Copy To Output Directory: Copy Always
in its Visual Studio Properties
...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext
is string
path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image
would be automatically loaded at runtime.
In C/C++, pointers and arrays are (almost) equivalent.
int *a; a[0];
will return *a
, and a[1];
will return *(a + 1)
But array can't change the pointer it points to while pointer can.
new int[n]
will allocate some spaces for the "array"
One thing to check for...
If your class is defined as a typedef:
typedef struct myclass { };
Then you try to refer to it as struct myclass
anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:
typedef struct mystruct {}...
struct mystruct *myvar = value;
Instead use...
mystruct *myvar = value;
Common mistake.
A keystore needs a keystore file. The KeyStore
class needs a FileInputStream
. But if you supply null (instead of FileInputStream
instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool
.
Following code creates an empty keystore with empty password
KeyStore ks2 = KeyStore.getInstance("jks"); ks2.load(null,"".toCharArray()); FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore"); ks2.store(out, "".toCharArray());
Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.
The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):
Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"
Updated for the shifting:
d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"
You need to require 'date'
for this btw.
you could use is_displayed() like below
res = driver.find_element_by_id("some_id").is_displayed()
assert res, 'element not displayed!'
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
<a href="javascript:alert('Please be sure to set your printer to Landscape.');window.print();">Print Me...</a>
or
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>
If you want multiple lines consider this:
<textarea rows="2"></textarea>
Specify rows as needed.
NOTE: Hopefully this changed in the latest version.
You cannot copy data between a MongoDB 4.0 mongod instance (regardless of the FCV value) and a MongoDB 3.4 and earlier mongod instance. https://docs.mongodb.com/v4.0/reference/method/db.copyDatabase/
ALERT: Hey folks just be careful while copying the database, if you don't want to mess up the different collections under single database.
The following shows you how to rename
> show dbs;
testing
games
movies
To rename you use the following syntax
db.copyDatabase("old db name","new db name")
Example:
db.copyDatabase('testing','newTesting')
Now you can safely delete the old db by the following way
use testing;
db.dropDatabase(); //Here the db **testing** is deleted successfully
Now just think what happens if you try renaming the new database name with existing database name
Example:
db.copyDatabase('testing','movies');
So in this context all the collections (tables) of testing will be copied to movies database.
name
attribute points to the column containing the asociation, i.e. column name of the foreign keyreferencedColumnName
attribute points to the related column in asociated/referenced entity, i.e. column name of the primary keyYou are not required to fill the referencedColumnName
if the referenced entity has single column as PK, because there is no doubt what column it references (i.e. the Address
single column ID).
@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() { return address; }
However if the referenced entity has PK that spans multiple columns the order in which you specify @JoinColumn
annotations has significance. It might work without the referencedColumnName
specified, but that is just by luck. So you should map it like this:
@ManyToOne
@JoinColumns({
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() { return address; }
or in case of ManyToMany
:
@ManyToMany
@JoinTable(
name="CUST_ADDR",
joinColumns=
@JoinColumn(name="CUST_ID"),
inverseJoinColumns={
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
}
)
Two queries generated by Hibernate of the same join table mapping, both without referenced column specified. Only the order of @JoinColumn
annotations were changed.
/* load collection Client.emails */
select
emails0_.id_client as id1_18_1_,
emails0_.rev as rev18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_
from client_email emails0_
inner join email email1_ on emails0_.id_email=email1_.id_email
where emails0_.id_client='2' and
emails0_.rev='18'
/* load collection Client.emails */
select
emails0_.rev as rev18_1_,
emails0_.id_client as id2_18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_
from client_email emails0_
inner join email email1_ on emails0_.id_email=email1_.id_email
where emails0_.rev='2' and
emails0_.id_client='18'
We are querying a join table to get client's emails. The {2, 18}
is composite ID of Client. The order of column names is determined by your order of @JoinColumn
annotations. The order of both integers is always the same, probably sorted by hibernate and that's why proper alignment with join table columns is required and we can't or should rely on mapping order.
The interesting thing is the order of the integers does not match the order in which they are mapped in the entity - in that case I would expect {18, 2}
. So it seems the Hibernate is sorting the column names before it use them in query. If this is true and you would order your @JoinColumn
in the same way you would not need referencedColumnName
, but I say this only for illustration.
Properly filled referencedColumnName
attributes result in exactly same query without the ambiguity, in my case the second query (rev = 2
, id_client = 18
).
if you can't or don't want to set the autoincrement property of the id, you can set value for the id for each row, like this:
INSERT INTO role (id, name, created)
SELECT
(select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
, name
, created
FROM (
VALUES
('Content Coordinator', GETDATE())
, ('Content Viewer', GETDATE())
) AS x(name, created)
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
typeof:
var foo;
if (typeof foo == "undefined"){
//do stuff
}
<div runat="server">
is mapped to a HtmlGenericControl
.
Try using BtnventCss.Attributes.Add("class", "hom_but_a");
At the top first set up database connection as follow:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
$query= $mysqli->query("SELECT PcID from PC");
?>
Then include the following code in HTML inside form
<select name="selected_pcid" id='selected_pcid'>
<?php
while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
$value= $rows['id'];
?>
<option value="<?= $value?>"><?= $value?></option>
<?php } ?>
</select>
However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.
In case you get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." Specifically for PUT and DELETE requests, you could try to disable WebDAV on IIS.
Apparently, the WebDAVModule is enabled by default and is disabling PUT and DELETE requests by default.
To disable the WebDAVModule, add this to your web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
You can also post runnable using the view from any other thread. But be sure that the view is not null:
tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});
According to the Documentation:
"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
You should include a hidden CSRF (cross site request forgery) token field in the form so that the CSRF protection middleware can validate the request.
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
So when doing ajax requests, you'll need to pass the csrf token via data parameter.
Here's the sample code.
var request = $.ajax({
url : "http://localhost/some/action",
method:"post",
data : {"_token":"{{ csrf_token() }}"} //pass the CSRF_TOKEN()
});
You can do this.
git clone https://github.com/sferik/sign-in-with-twitter.git signin
Use serialize
and deserialize
methods in SerializationUtils
from commons-lang.