The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:
$.validator.addMethod('cb_selectone', function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
}, 'Please select at least one option');
I dont really know what set does behind the scenes, so I just like to keep it simple.
def dupes(num_list):
unique = []
dupes = []
for i in num_list:
if i not in unique:
unique.append(i)
else:
dupes.append(i)
if len(dupes) != 0:
return False
else:
return True
You can implement it using View.scrollTo(..) also.
postDelayed(new Runnable() {
public void run() {
counter = (int) (counter + 10);
handler.postDelayed(this, 100);
llParent.scrollTo(counter , 0);
}
}
}, 1000L);
In my case, I had the Any XHR
flag set true on the XHR Breakpoints
settings, accessible over the Sources tab within Chrome's dev tools.
Uncheck it for Chrome to work normally again.
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
To get the keys:
function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
let result: string[] = [];
Object.keys(dict).map((key) =>
result.push(key),
);
return result;
}
Check that your log4j.properties
or log4j.xml
are copied to your IDE classpath and loads when calling BasicConfigurator.configure()
It's better to use ng-if
instead of ng-show
. ng-if
completely removes and recreates the element in the DOM and helps to avoid ng-shows blinking.
Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
print([l.strip() for l in my_list])
Output:
['this', 'is', 'a', 'list', 'of', 'words']
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
The following answer is to merge data into same table
MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif')
WHEN NOT MATCHED THEN
INSERT ( d.USERS_ID, d.USER_NAME)
VALUES ('123','itszaif');
This command checks if USER_ID
and USER_NAME
are matched, if not matched then it will insert.
I use something like this quite often
$wantedKeys = ['story', 'message'];
$hasWantedKeys = count(array_intersect(array_keys($source), $wantedKeys)) > 0
or to find the values for the wanted keys
$wantedValues = array_intersect_key($source, array_fill_keys($wantedKeys, 1))
This may be possible by using the refs attribute.
In the example of wanting to to reach a <div>
what you would want to do is use is <div ref="myExample">
. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample)
.
From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children
(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.
Here's the official react documentation on refs for more info.
A solution with storyboard and Swift:
Open your .storyboard file, select a TableViewController in your storyboard and "Enable" the Table View Controller: Refreshing feature in the Utilities.
Open the associated UITableViewController
class and add the following Swift 5 line into the viewDidLoad
method.
self.refreshControl?.addTarget(self, action: #selector(refresh), for: UIControl.Event.valueChanged)
Add the following method above the viewDidLoad method
func refresh(sender:AnyObject)
{
// Updating your data here...
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
Open a command prompt. Change to the eclipse home directory and type "eclipse -clean" e.g. C:/eclipse>eclipse -clean
This will ask for the workspace selection. It will also force to set it as the default workspace.
Then, go to eclipsehome-->configuration-->settings folder.
open org.eclipse.ui.de.prefs in a notepad.
set this property to true from false.
SHOW_WORKSPACE_SELECTION_DIALOG=true
You will be asked for a workspace selection everytime.
As I haven't seen any detailed explanation on how to check if we got a specific exception among a list of accepted one using context manager, or other exception details I will add mine (checked on python 3.8).
If I just want to check that function is raising for instance TypeError
, I would write:
with self.assertRaises(TypeError):
function_raising_some_exception(parameters)
If I want to check that function is raising either TypeError
or IndexError
, I would write:
with self.assertRaises((TypeError,IndexError)):
function_raising_some_exception(parameters)
And if I want even more details about the Exception raised I could catch it in a context like this:
# Here I catch any exception
with self.assertRaises(Exception) as e:
function_raising_some_exception(parameters)
# Here I check actual exception type (but I could
# check anything else about that specific exception,
# like it's actual message or values stored in the exception)
self.assertTrue(type(e.exception) in [TypeError,MatrixIsSingular])
If you just want to pass a std::string
to a function that needs const char*
you can use
std::string str;
const char * c = str.c_str();
If you want to get a writable copy, like char *
, you can do that with this:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
Edit: Notice that the above is not exception safe. If anything between the new
call and the delete
call throws, you will leak memory, as nothing will call delete
for you automatically. There are two immediate ways to solve this.
boost::scoped_array
will delete the memory for you upon going out of scope:
std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0
// get the char* using writable.get()
// memory is automatically freed if the smart pointer goes
// out of scope
This is the standard way (does not require any external library). You use std::vector
, which completely manages the memory for you.
std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
// get the char* using &writable[0] or &*writable.begin()
Cause: The error occurred since hibernate is not able to connect to the database.
Solution:
1. Please ensure that you have a database present at the server referred to in the configuration file eg. "hibernatedb" in this case.
2. Please see if the username and password for connecting to the db are correct.
3. Check if relevant jars required for the connection are mapped to the project.
The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.
If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".
see Bootstrap 3 docs: http://getbootstrap.com/css/#grid
Just look at setAccessible()
method used to access private
fields and methods:
Now there is a lot more conditions required for this method to work. The only reason it doesn't break almost all of older software is that modules autogenerated from plain JARs are very permissive (open and export everything for everyone).
IMHO you should pay your attention to Robot.class
Still if you want to move the mouse pointer physically, you need to take different approach using Robot class
Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);
Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked.
In all browsers these are in event.screenX
and event.screenY
.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want.
In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.
More details you can get here
Hope this be helpful to you.
Otherwise, you have function alpha
in package scales
in which you can directly input your vector of colors (even if they are factors as in your example):
library(scales)
cols <- cut(z, 6, labels = c("pink", "red", "yellow", "blue", "green", "purple"))
plot(x, y, main= "Fragment recruitment plot - FR-HIT",
ylab = "Percent identity", xlab = "Base pair position",
col = alpha(cols, 0.4), pch=16)
# For an alpha of 0.4, i. e. an opacity of 40%.
So if the insert time is what you need, it's already there:
Login to mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Lets make that database the one we are on now
> use penguins
switched to db penguins
Get the rows back:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
Get each row in yyyy-MM-dd HH:mm:ss format:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131
This is the code I have for moving an item down one place in a list:
if (this.folderImages.SelectedIndex > -1 && this.folderImages.SelectedIndex < this.folderImages.Items.Count - 1)
{
string imageName = this.folderImages.SelectedItem as string;
int index = this.folderImages.SelectedIndex;
this.folderImages.Items.RemoveAt(index);
this.folderImages.Items.Insert(index + 1, imageName);
this.folderImages.SelectedIndex = index + 1;
}
and this for moving it one place up:
if (this.folderImages.SelectedIndex > 0)
{
string imageName = this.folderImages.SelectedItem as string;
int index = this.folderImages.SelectedIndex;
this.folderImages.Items.RemoveAt(index);
this.folderImages.Items.Insert(index - 1, imageName);
this.folderImages.SelectedIndex = index - 1;
}
folderImages
is a ListBox
of course so the list is a ListBox.ObjectCollection
, not a List<T>
, but it does inherit from IList
so it should behave the same. Does this help?
Of course the former only works if the selected item is not the last item in the list and the latter if the selected item is not the first item.
I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.
This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,
1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']
2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")
3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".
Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.
Weird.
Assuming you are using Eclipse, on a MAC you can:
Eclipse.app
Eclipse -> Preferences
Java -> Installed JREs
Add...
buttonMacOS X VM
as the JRE type. Press Next./Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
JDK 1.7
. Click Finish.File -> New -> Java Project
.Use default JRE (currently JDK 1.7)
Hope this helps
I think you also may use this
>> import numpy
>> print numpy.__version__
Update:
for python3
use print(numpy.__version__)
Other possible solution:
tv.setText(Integer.toString(a1)); // where a1 - int value
static inner class: can declare static & non static members but can only access static members of its parents class.
non static inner class: can declare only non static members but can access static and non static member of its parent class.
I have many times succeeded to get div's without line breaks after them, by playing around with the float css attribute and the width css attribute.
Of course after working out the solution you have to test it in all browsers, and in each browser you have to re-size the windows to make sure that it works in all circumstances.
Take a look at the Cookie Plugin for jQuery.
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
I know is old topic but what about simple solution like while loop?
int function count(array[]) {
int i = 0;
while(array[i] != NULL) {
i++;
}
return i;
}
I know that is slower than sizeof() but this is another example of array count.
Model (App\Post.php):
/**
* Get all comments for this post.
*/
public function comments($published = false)
{
$comments = $this->hasMany('App\Comment');
if($published) $comments->where('published', 1);
return $comments;
}
Controller (App\Http\Controllers\PostController.php):
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function post($id)
{
$post = Post::with('comments')
->find($id);
return view('posts')->with('post', $post);
}
Blade template (posts.blade.php):
{{-- Get all comments--}}
@foreach ($post->comments as $comment)
code...
@endforeach
{{-- Get only published comments--}}
@foreach ($post->comments(true)->get() as $comment)
code...
@endforeach
The warning message Pseudo-terminal will not be allocated because stdin is not a terminal.
is due to the fact that no command is specified for ssh
while stdin is redirected from a here document.
Due to the lack of a specified command as an argument ssh
first expects an interactive login session (which would require the allocation of a pty on the remote host) but then has to realize that its local stdin is no tty/pty. Redirecting ssh
's stdin from a here document normally requires a command (such as /bin/sh
) to be specified as an argument to ssh
- and in such a case no pty will be allocated on the remote host by default.
Since there are no commands to be executed via ssh
that require the presence of a tty/pty (such as vim
or top
) the -t
switch to ssh
is superfluous.
Just use ssh -T user@server <<EOT ...
or ssh user@server /bin/bash <<EOT ...
and the warning will go away.
If <<EOF
is not escaped or single-quoted (i. e. <<\EOT
or <<'EOT'
) variables inside the here document will be expanded by the local shell before it is executing ssh ...
. The effect is that the variables inside the here document will remain empty because they are defined only in the remote shell.
So, if $REL_DIR
should be both accessible by the local shell and defined in the remote shell, $REL_DIR
has to be defined outside the here document before the ssh
command (version 1 below); or, if <<\EOT
or <<'EOT'
is used, the output of the ssh
command can be assigned to REL_DIR
if the only output of the ssh
command to stdout is genererated by echo "$REL_DIR"
inside the escaped/single-quoted here document (version 2 below).
A third option would be to store the here document in a variable and then pass this variable as a command argument to ssh -t user@server "$heredoc"
(version 3 below).
And, last but not least, it would be no bad idea to check if the directories on the remote host were created successfully (see: check if file exists on remote host with ssh).
# version 1
unset DEP_ROOT REL_DIR
DEP_ROOT='/tmp'
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR="${DEP_ROOT}/${datestamp}"
ssh localhost /bin/bash <<EOF
if [ ! -d "$DEP_ROOT" ] && [ ! -e "$DEP_ROOT" ]; then
echo "creating the root directory" 1>&2
mkdir "$DEP_ROOT"
fi
mkdir "$REL_DIR"
#echo "$REL_DIR"
exit
EOF
scp -r ./dir1 user@server:"$REL_DIR"
scp -r ./dir2 user@server:"$REL_DIR"
# version 2
REL_DIR="$(
ssh localhost /bin/bash <<\EOF
DEP_ROOT='/tmp'
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR="${DEP_ROOT}/${datestamp}"
if [ ! -d "$DEP_ROOT" ] && [ ! -e "$DEP_ROOT" ]; then
echo "creating the root directory" 1>&2
mkdir "$DEP_ROOT"
fi
mkdir "$REL_DIR"
echo "$REL_DIR"
exit
EOF
)"
scp -r ./dir1 user@server:"$REL_DIR"
scp -r ./dir2 user@server:"$REL_DIR"
# version 3
heredoc="$(cat <<'EOF'
# -onlcr: prevent the terminal from converting bare line feeds to carriage return/line feed pairs
stty -echo -onlcr
DEP_ROOT='/tmp'
datestamp="$(date +%Y%m%d%H%M%S)"
REL_DIR="${DEP_ROOT}/${datestamp}"
if [ ! -d "$DEP_ROOT" ] && [ ! -e "$DEP_ROOT" ]; then
echo "creating the root directory" 1>&2
mkdir "$DEP_ROOT"
fi
mkdir "$REL_DIR"
echo "$REL_DIR"
stty echo onlcr
exit
EOF
)"
REL_DIR="$(ssh -t localhost "$heredoc")"
scp -r ./dir1 user@server:"$REL_DIR"
scp -r ./dir2 user@server:"$REL_DIR"
This will return the first element
set.iterator().next();
The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).
For example:
struct foo_t {
int x;
char c;
};
Even though the c
field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8
(on a 32-bit system - rather a system with a 32-bit int
type) because there will need to be 3 bytes of padding after the c
field.
Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.
In case it is not possible to bind the addTarget to your UITextField, I advise you to bind one of them as suggested above, and insert the code for execution at the end of the shouldChangeCharactersIn method.
nameTextField.addTarget(self, action: #selector(RegistrationViewController.textFieldDidChange(_:)), for: .editingChanged)
@objc func textFieldDidChange(_ textField: UITextField) {
if phoneNumberTextField.text!.count == 17 && nameTextField.text!.count > 0 {
continueButtonOutlet.backgroundColor = UIColor(.green)
} else {
continueButtonOutlet.backgroundColor = .systemGray
}
}
And in call in shouldChangeCharactersIn func.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String
if phoneNumberTextField == textField {
textField.text = lastText.format("+7(NNN)-NNN-NN-NN", oldString: text)
textFieldDidChange(phoneNumberTextField)
return false
}
return true
}
Let's make it lazy!
from itertools import islice, tee
def window(iterable, size):
iterators = tee(iterable, size)
iterators = [islice(iterator, i, None) for i, iterator in enumerate(iterators)]
yield from zip(*iterators)
list(window(range(5), 3))
# [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
In one line, answer is as below;
[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]
I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.
<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>
Use the Stringify.Library nuget package
//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);
//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });
The combination of Ctrl + Shift + Alt + Down worked for me on Linux.
Try this one,
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
myComponent.grabFocus();
myComponent.requestFocus();//or inWindow
}
});
HTML CODE:
<div>
<video class="center" src="vd/vd1.mp4" controls poster="dossierimage/imagex.jpg" width="600">?</video>
</div>
CSS CODE:
.center {
margin-left: auto;
margin-right: auto;
display: block
}
Simpliest way for my opinion
var web = new WebClient();
var url = $"{hostname}/LoadDataSync?systemID={systemId}";
var responseString = web.DownloadString(url);
OR
var bytes = web.DownloadData(url);
Yes we can check the length of queue object created from collections.
from collections import deque
class Queue():
def __init__(self,batchSize=32):
#self.batchSie = batchSize
self._queue = deque(maxlen=batchSize)
def enqueue(self, items):
''' Appending the items to the queue'''
self._queue.append(items)
def dequeue(self):
'''remoe the items from the top if the queue becomes full '''
return self._queue.popleft()
Creating an object of class
q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])
Now retrieving the length of the queue
#check the len of queue
print(len(q._queue))
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item
print(len(q.dequeue()))
check the results in attached screen shot
Hope this helps...
To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:
Pattern 1 - using one-line methods for object creation
To use pattern 1 (testing a class called MyClass), you would replace a call like
Foo foo = new Foo( a, b, c );
with
Foo foo = makeFoo( a, b, c );
and write a one-line method
Foo makeFoo( A a, B b, C c ) { return new Foo( a, b, c ); }
It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.
When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.
Your test class might contain members like
@Mock private Foo mockFoo; private MyClass toTest = spy(new MyClass());
Lastly, inside your test method you mock out the call to makeFoo with a line like
doReturn( mockFoo ) .when( toTest ) .makeFoo( any( A.class ), any( B.class ), any( C.class ));
You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.
If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:
Pika is a CDN that takes care of providing module versions of popular packages
<script type='module'>
import * as $ from 'https://cdn.skypack.dev/jquery';
// use it!
$('#myDev').on('click', alert);
</script>
Skypack is Pika, so you could also use: import * as $ from 'https://cdn.pika.dev/jquery@^3.5.1';
You can just read from stdin unless the user supply a filename ?
If not, treat the special "filename" -
as meaning "read from stdin". The user would have to start the program like cat file | myprogram -
if he wants to pipe data to it, and myprogam file
if he wants it to read from a file.
int main(int argc,char *argv[] ) {
FILE *input;
if(argc != 2) {
usage();
return 1;
}
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"rb");
//check for errors
}
If you're on *nix, you can check whether stdin is a fifo:
struct stat st_info;
if(fstat(0,&st_info) != 0)
//error
}
if(S_ISFIFO(st_info.st_mode)) {
//stdin is a pipe
}
Though that won't handle the user doing myprogram <file
You can also check if stdin is a terminal/console
if(isatty(0)) {
//stdin is a terminal
}
you can write a code in various type
first i can write this
html
<a href="https://www.google.com/" onMouseOver="this.style.color='red'"
onMouseOut="this.style.color='blue'" class="one">Hello siraj</a>
css
.one{
text-decoration: none;
}
you can try another way
html
<a href="https://www.google.com/" class="one">Hello siraj</a>
css
.one{
text-decoration: none;
}
.one:hover{
color:blue;
}
.one:active{
color: red;
}
you can also try hover in jquery
java script
$(document).ready(function(){
$("p").hover(function(){
$(this).css("background-color", "yellow");
}, function(){
$(this).css("background-color", "pink");
});
});
html
<p>Hover the mouse pointer over this paragraph.</p>
in this code you have a three function in jquery first you ready a function which is the basic of function of jquery then second you have a hover function in this function when you hover a pointer to the text the color will be changed and then the next the when you release the pointer to the text it will be the different color and this is the third function
If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.
ui->comboBox->setCurrentText("choice 2");
From the Qt 5.7 documentation
The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.
Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop
Insert your fetched values into an array instead of echoing.
Use file_put_contents()
and insert json_encode($rows)
into that file, if $rows
is your data.
After changing lots in my POM and updating my JDK I was getting the "One or more constraints have not been satisfied" related to Google App Engine. The solution was to delete the Eclipse project settings and reimport it.
On OS X, I did this in Terminal by changing to the project directory and
rm -rf .project
rm -rf .settings
Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.
If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:
<TextView
android:id="@+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorLink="@color/your_color"
</TextView>
You can also set it in the code with:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);
Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.
CSS3: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm
.style1 {
...
background-size: 100%;
}
You can specify just width or height with:
background-size: 100% 50%;
Which will stretch it 100% of the width and 50% of the height.
Browser support: http://caniuse.com/#feat=background-img-opts
Here's something you can do with AlertBuilder
to make the title disappear:
TextView title = new TextView(this);
title.setVisibility(View.GONE);
builder.setCustomTitle(title);
If you happen to be using the Ruby on Rails' jQuery gem jquery-rails
and for some reason you can't refactor your legacy code, the last version that still supports is 2.1.3
and you can lock it by using the following syntax on your Gemfile
:
gem 'jquery-rails', '~> 2.1', '= 2.1.3'
then you can use the following command to update:
bundle update jquery-rails
I hope that help others facing a similar issue.
Use the CSS below, the first declaration will ensure your table sticks to the widths you provide (you'll need to add the classes in your HTML):
table{
table-layout:fixed;
}
th.from, th.date {
width: 15%;
}
th.subject{
width: 70%;
}
try this one out resizeable button
<button type="submit me" style="height: 25px; width: 100px">submit me</button>
var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
I had the same problem several times. The following solutions are solved my problem. I have listed out them according to complexity.
Restart the computer and see whether the problem is out
If it still exists, try to kill the process on running port usually 8080
netstat -ano | findstr 8080
taskkill /F /PID <PID>
If it still exists, go to 'android' directory as follow and go further
cd android
./gradlew clean
and start node
npm start
then run npx react-native run android
or expo stat
and press 'a'
Hope you will OK with the above issues.
This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.
See, for example, the code samples here:
Let's look at the example you posted:
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
return next();
} else {
res.redirect('/sessions/new');
}
});
} else {
res.redirect('/sessions/new');
}
}
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
});
The loadUser
function expects a function in its third argument, which is bound to the name next
. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser
is done (unless a user could not be found).
There's nothing special about the name next
in this example; we could have named it anything.
Take a look at this :
var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012
console.log(event.toLocaleDateString('ar-EG', options));
// expected output: ??????? ?? ??????? ????
console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012? 12? 20? ???
Source : Mozilla Doc
There is a new (sometime pre April 2013) option on the site that says "Clone in Windows".
This works very nicely if you already have the Windows GitHub Client as mentioned by @Tommy in his answer on this related question (How to download source in ZIP format from GitHub?).
Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.
With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
And here's the output:
It started happening to me when I changed variables for Android Studio. Go to your studio64.exe.vmoptions
file (located in c:\users\userName\.AndroidStudio{version}\
and comments the arguments.
The most likely reason would be that something else is using port 80. (Often this can be Skype, IIS, etc.)
This tutorials shows How to Change the Apache Port in XAMPP
You need to make two case
labels.
Control will fall through from the first label to the second, so they'll both execute the same code.
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
int add(int x, int y); // forward declaration using function prototype
Can you explain "forward declaration" more further? What is the problem if we use it in the main() function?
It's same as #include"add.h"
. If you know,preprocessor expands the file which you mention in #include
, in the .cpp file where you write the #include
directive. That means, if you write #include"add.h"
, you get the same thing, it is as if you doing "forward declaration".
I'm assuming that add.h
has this line:
int add(int x, int y);
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys()
or array_values()
, so I usually define this:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}
This might help to understand what is recorded at what level Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing severity - Log Level.
Number of levels recorded for each setting level:
ALL DEBUG INFO WARN ERROR FATAL OFF
•All
•DEBUG •DEBUG
•INFO •INFO •INFO
•WARN •WARN •WARN •WARN
•ERROR •ERROR •ERROR •ERROR •ERROR
•FATAL •FATAL •FATAL •FATAL •FATAL •FATAL
•OFF •OFF •OFF •OFF •OFF •OFF •OFF
It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE
would have been too narrow in its meaning.
-mmin is for minutes.
Try looking at the man page.
man find
for more types.
A easy way is
On MySQL 8.0.15 (maybe earlier than this too): the PASSWORD()
function does not work anymore, so you have to do:
Make sure you have stopped MySQL first (Go to: 'System Preferences' >> 'MySQL' and stop MySQL).
Run the server in safe mode with privilege bypass:
sudo mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
FLUSH PRIVILEGES;
exit;
Then
mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';
Finally, start your MySQL again.
Enlighten by @OlatunjiYso in this GitHub issue.
The AtomicBoolean
class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.
The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Hardware -> Erase all content and settings did the job for me (other things didn't).
DON'T DO THIS. Raising a bare
Exception
is absolutely not the right thing to do; see Aaron Hall's excellent answer instead.
Can't get much more pythonic than this:
raise Exception("I know python!")
See the raise statement docs for python if you'd like more info.
var response = taskwithresponse.Result;
var jsonString = response.ReadAsAsync<List<Job>>().Result;
Well another way to apply transition in this situation without using keyframes is to set the width of your element to zero and then unset it on hover
.className{
visibility:hidden;
opacity: 0;
transition: .2s;
width:0;
}
.className:hover{
visibility:visible;
margin-right: .5rem;
opacity: 1;
width:unset;
}
If you want to compare two Maps then, below code may help you
(new TreeMap<String, Object>(map1).toString().hashCode()) == new TreeMap<String, Object>(map2).toString().hashCode()
To print the N first characters you can remove the N+1 characters up to the end of line:
$ sed 's/.//5g' <<< "defn-test"
defn
I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):
print_r(file_get_contents($url));
Turned out there was a trailing <pre>
tag.
depends on the application. if there is only a few packages from each client, 100K is very easy for linux. A engineer of my team had done a test years ago, the result shows : when there is no package from client after connection established, linux epoll can watch 400k fd for readablity at cpu usage level under 50%.
I came with same question but after google, I found there is no big difference :)
From Github
If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* , express = require('express')
* , app = express();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @api public
*/
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
Also if you want to work with socket.io see their example
See this
I prefer app.listen()
:)
Code provided by SHS didn't work for me, but this one apparently did (I used a Bridging Header: #import <CommonCrypto/CommonCrypto.h>
):
extension String {
func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.data(using: String.Encoding.utf8),
let data = self.data(using: String.Encoding.utf8),
let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyLength,
iv,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString
}
else {
return nil
}
}
return nil
}
func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.data(using: String.Encoding.utf8),
let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
let cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyLength,
iv,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
return unencryptedMessage
}
else {
return nil
}
}
return nil
}
}
From my ViewController
:
let encoded = message.aesEncrypt(key: keyString, iv: iv)
let unencode = encoded?.aesDecrypt(key: keyString, iv: iv)
Do not use Javascript for this!
Modern HTML pages automatically allow a form's submit button to submit the page with the ENTER/RETURN key when any form field control in the web page has focus by the user, autofocus
attribute is set on a form field or button, or user tab's into any of the form fields.
So instead of Javascripting this, an easier solution is to add tabindex=0
on your form fields and button inside a form element then autofocus
on the first input control. The user can then press "ENTER" to submit the form at any point as they enter data:
<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
<label for="username1">Username</label>
<input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
<label for="password1">Password</label>
<input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
<button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>
The only way to do this is via various CSS hacks, which will make your page much more likely to fail on the next browser updates. If anything, it will be LESS safe than using a js-browser sniffer.
Uso algo simples assim ;)
DELIMITER $$
DROP FUNCTION IF EXISTS `uc_frist` $$
CREATE FUNCTION `uc_frist` (str VARCHAR(200)) RETURNS varchar(200)
BEGIN
set str:= lcase(str);
set str:= CONCAT(UCASE(LEFT(str, 1)),SUBSTRING(str, 2));
set str:= REPLACE(str, ' a', ' A');
set str:= REPLACE(str, ' b', ' B');
set str:= REPLACE(str, ' c', ' C');
set str:= REPLACE(str, ' d', ' D');
set str:= REPLACE(str, ' e', ' E');
set str:= REPLACE(str, ' f', ' F');
set str:= REPLACE(str, ' g', ' G');
set str:= REPLACE(str, ' h', ' H');
set str:= REPLACE(str, ' i', ' I');
set str:= REPLACE(str, ' j', ' J');
set str:= REPLACE(str, ' k', ' K');
set str:= REPLACE(str, ' l', ' L');
set str:= REPLACE(str, ' m', ' M');
set str:= REPLACE(str, ' n', ' N');
set str:= REPLACE(str, ' o', ' O');
set str:= REPLACE(str, ' p', ' P');
set str:= REPLACE(str, ' q', ' Q');
set str:= REPLACE(str, ' r', ' R');
set str:= REPLACE(str, ' s', ' S');
set str:= REPLACE(str, ' t', ' T');
set str:= REPLACE(str, ' u', ' U');
set str:= REPLACE(str, ' v', ' V');
set str:= REPLACE(str, ' w', ' W');
set str:= REPLACE(str, ' x', ' X');
set str:= REPLACE(str, ' y', ' Y');
set str:= REPLACE(str, ' z', ' Z');
return str;
END $$
DELIMITER ;
I use the following in a batch file:
path = %path%;C:\Windows\Microsoft.NET\Framework\v2.0.50727
regasm httpHelper\bin\Debug\httpHelper.dll /tlb:.\httpHelper.tlb /codebase
pause
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>{
private final ConcurrentMap<E, Object> theMap;
private static final Object dummy = new Object();
public ConcurrentHashSet(){
theMap = new ConcurrentHashMap<E, Object>();
}
@Override
public int size() {
return theMap.size();
}
@Override
public Iterator<E> iterator(){
return theMap.keySet().iterator();
}
@Override
public boolean isEmpty(){
return theMap.isEmpty();
}
@Override
public boolean add(final E o){
return theMap.put(o, ConcurrentHashSet.dummy) == null;
}
@Override
public boolean contains(final Object o){
return theMap.containsKey(o);
}
@Override
public void clear(){
theMap.clear();
}
@Override
public boolean remove(final Object o){
return theMap.remove(o) == ConcurrentHashSet.dummy;
}
public boolean addIfAbsent(final E o){
Object obj = theMap.putIfAbsent(o, ConcurrentHashSet.dummy);
return obj == null;
}
}
The order in which ng-click
and ng-model
will be executed is ambiguous (since neither explicitly set their priority
). The most stable solution to this would be to avoid using them on the same element.
Also, you probably do not want the behavior that the examples show; you want the checkbox
to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input
(with ng-model
) inside a label
(with ng-click
):
<label ng-click="onCompleteTodo(todo)">
<input type='checkbox' ng-model="todo.done">
{{todo.text}}
</label>
Working example: http://jsfiddle.net/b3NLH/1/
SELECT * FROM foo WHERE id>4 ORDER BY id LIMIT 1
sudo svn revert filename
this is the better way to revert a single file
First off, what compiler or dev environment are you using? If Visual Studio, you need to make a console application project to get console output.
Second,
std::cout << "Hello World" << std::endl;
should work in any C++ console application.
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
Just an examples for toLowerCase()
, toUpperCase()
and prototype for not yet available toTitleCase()
or toPropperCase()
String.prototype.toTitleCase = function() {_x000D_
return this.split(' ').map(i => i[0].toUpperCase() + i.substring(1).toLowerCase()).join(' ');_x000D_
}_x000D_
_x000D_
String.prototype.toPropperCase = function() {_x000D_
return this.toTitleCase();_x000D_
}_x000D_
_x000D_
var OriginalCase = 'Your Name';_x000D_
var lowercase = OriginalCase.toLowerCase();_x000D_
var upperCase = lowercase.toUpperCase();_x000D_
var titleCase = upperCase.toTitleCase();_x000D_
_x000D_
console.log('Original: ' + OriginalCase);_x000D_
console.log('toLowerCase(): ' + lowercase);_x000D_
console.log('toUpperCase(): ' + upperCase);_x000D_
console.log('toTitleCase(): ' + titleCase);
_x000D_
edited 2018
Assuming you are trying to pass the command line arguments as well.
import sys
import myModule
def main():
# this will just pass all of the system arguments as is
myModule.main(*sys.argv)
# all the argv but the script name
myModule.main(*sys.argv[1:])
Just a note: A queue is not required for threading.
This is the simplest example I could imagine that shows 10 processes running concurrently.
import threading
from random import randint
from time import sleep
def print_number(number):
# Sleeps a random 1 to 10 seconds
rand_int_var = randint(1, 10)
sleep(rand_int_var)
print "Thread " + str(number) + " slept for " + str(rand_int_var) + " seconds"
thread_list = []
for i in range(1, 10):
# Instantiates the thread
# (i) does not make a sequence, so (i,)
t = threading.Thread(target=print_number, args=(i,))
# Sticks the thread in a list so that it remains accessible
thread_list.append(t)
# Starts threads
for thread in thread_list:
thread.start()
# This blocks the calling thread until the thread whose join() method is called is terminated.
# From http://docs.python.org/2/library/threading.html#thread-objects
for thread in thread_list:
thread.join()
# Demonstrates that the main process waited for threads to complete
print "Done"
Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.
e.g. if you have it like:
<property name="hibernate.hbm2ddl.auto" value="create"/>
try changing it to:
<property name="hibernate.hbm2ddl.auto">create</property>
I just benchmarked a file transfer over both FTP and HTTP :
The result:
fdm
): 1 minuteSo, basically under a "real life" situation:
1) HTTP is faster than FTP when downloading one big file.
2) HTTP can use parallel chunk download which makes it 6x times faster than FTP depending on the network conditions.
When your ssh key is password protected run ssh-add
. npm probably hangs somewhere asking for your password.
You can also define case insensitive during the pattern compile:
pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class RadioButton extends JRadioButton {
public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
public Object[] getSelectedObjects() {
if ( isSelected() ) {
return new Object[] { RadioButton.this };
} else {
return new Object[0];
}
}
public RadioButton getButton() { return RadioButton.this; }
}
public RadioButton() { super(); setModel(new RadioButtonModel()); }
public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }
public static void main(String[] args) {
RadioButton b1 = new RadioButton("A");
RadioButton b2 = new RadioButton("B");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
b2.setSelected(true);
RadioButtonModel model = (RadioButtonModel)group.getSelection();
System.out.println(model.getButton().getText());
}
}
you can do this easily without manual editing or using fancy text editors. Here's a vbscript.
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
If objFS.GetExtensionName(strFile) = "jpg" Then
strFileName = strFile.Name
If InStr(strFileName,"Vacation2010") > 0 Then
strNewFileName = Replace(strFileName,"Vacation2010","December")
strFile.Name = strNewFileName
End If
End If
Next
save as myscript.vbs and
C:\test> cscript //nologo myscript.vbs
If you are using Webdriver then the item you are looking for is Selected.
Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.
So what you would look for in Selenium Webdriver is this
isChecked = e.findElement(By.tagName("input")).Selected;
As there is no Selected in WebDriver Java API, the above code should be as follows:
isChecked = e.findElement(By.tagName("input")).isSelected();
This one worked for me:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
update table_name set field1 = field1 + 1;
Make a call to the DB searching with myid (Id of the row) and get back specific columns:
var columns = db.Notifications
.Where(x => x.Id == myid)
.Select(n => new { n.NotificationTitle,
n.NotificationDescription,
n.NotificationOrder });
I found the information found at http://help.infragistics.com/Help/NetAdvantage/jQuery/2013.1/CLR4.0/html/igOlapXmlaDataSource_Configuring_IIS_for_Cross_Domain_OLAP_Data.html to be very helpful in setting up HTTP OPTIONS for a WCF service in IIS 7.
I added the following to my web.config and then moved the OPTIONSVerbHandler in the IIS 7 'hander mappings' list to the top of the list. I also gave the OPTIONSVerbHander read access by double clicking the hander in the handler mappings section then on 'Request Restrictions' and then clicking on the access tab.
Unfortunately I quickly found that IE doesn't seem to support adding headers to their XDomainRequest object (setting the Content-Type to text/xml and adding a SOAPAction header).
Just wanted to share this as I spent the better part of a day looking for how to handle it.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type, soapaction" />
</customHeaders>
</httpProtocol>
</system.webServer>
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:
File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
The 'react-json-view' provides solution rendering json string.
import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
If you just want to pause/stop animation smoothly
self.yourView.layer.speed = 0;
InputStream in = new ByteArrayInputStream(yourstring.getBytes());
I haven't been able to get good results from ImageMagick in this instance, but Inkscape does a nice job of scaling an SVG on Linux and Windows:
inkscape -z -w 1024 -h 1024 input.svg -e output.png
Note that you can omit one of the width/height parameters to have the other parameter scaled automatically based on the input image dimensions.
Edit (May 2020): Inkscape 1.0 users, please note that the command line arguments have changed:
inkscape -w 1024 -h 1024 input.svg -o output.png
Here's the result of scaling a 16x16 SVG to a 200x200 PNG using this command:
Just for reference, my Inkscape version (on Ubuntu 12.04) is:
Inkscape 0.48.3.1 r9886 (Mar 29 2012)
and on Windows 7, it is:
Inkscape 0.48.4 r9939 (Dec 17 2012)
These are escape characters which are used to manipulate string.
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
Read more about them from here.
http://docs.oracle.com/javase/tutorial/java/data/characters.html
I had this issue with a specific application and not the entire IIS site. In my case, access to the application directory was not the problem. Instead, I needed to give the application pool a recycle.
I think this was related to how the application was deployed and the IIS settings were set (done via scripts and a deployment agent).
?library
and you will see:
library(package)
andrequire(package)
both load the package with namepackage
and put it on the search list.require
is designed for use inside other functions; it returnsFALSE
and gives a warning (rather than an error aslibrary()
does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, calldetach(unload = TRUE)
orunloadNamespace
first.) If you want to load a package without putting it on the search list, userequireNamespace
.
And make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
To answer all your questions:
Can I use ROBOCOPY for this?
Yes, RC should fit your requirements (simplicity, only copy what needed)
What exactly does it mean to exclude?
It will exclude copying - RC calls it skipping
Would the
/XO
option copy only newer files, not files of the same age?
Yes, RC will only copy newer files. Files of the same age will be skipped.
(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO
)
Maybe in your case using the /MIR
option could be useful. In general RC is rather targeted at directories and directory trees than single files.
I tried above samples but not working for me. The simplest solution is working for me awesome:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#fff" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/Area"/>
</RelativeLayout>
function capitalize(s){
return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
output: "This Is The Worst String Ever"
It appears this solution supersedes mine: https://stackoverflow.com/a/7592235/104380
try
$this->load->view('home/home_view',$data);
instead of this:
$this->load->view(‘home\home_view’,$data);
Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.
As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.
Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."
Try this
rails destroy model Rating
It will remove model, migration, tests and fixtures
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "hello",; print "there"
hello there
>>> print "hello",; sys.stdout.softspace=False; print "there"
hellothere
But really, you should use sys.stdout.write
directly.
You can disable caching globally using $.ajaxSetup()
, for example:
$.ajaxSetup({ cache: false });
This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax()
call, set cache: false
on it locally, like this:
$.ajax({
cache: false,
//other options...
});
it's work for me html:
<button type="button" class="btn btn-primary" id="btnSaveSchedule">abc</button>
js
$("#btnSaveSchedule").text("new value");
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}
To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode
. The appropriate converter is automatically configured.
@PostMapping(value="/process")
public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
System.out.println(payload);
}
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
You should check for the type of the item in the localStorage
if(localStorage.token !== null) {
// this will only work if the token is set in the localStorage
}
if(typeof localStorage.token !== 'undefined') {
// do something with token
}
if(typeof localStorage.token === 'undefined') {
// token doesn't exist in the localStorage, maybe set it?
}
Try to set the element's value using the executeScript
method of JavascriptExecutor:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
simple example
<?php
echo '#start main# ';
function a(){
echo '{start[';
for($i=1; $i<=9; $i++)
yield $i;
echo ']end} ';
}
foreach(a() as $v)
echo $v.',';
echo '#end main#';
?>
output
#start main# {start[1,2,3,4,5,6,7,8,9,]end} #end main#
advanced example
<?php
echo '#start main# ';
function a(){
echo '{start[';
for($i=1; $i<=9; $i++)
yield $i;
echo ']end} ';
}
foreach(a() as $k => $v){
if($k === 5)
break;
echo $k.'=>'.$v.',';
}
echo '#end main#';
?>
output
#start main# {start[0=>1,1=>2,2=>3,3=>4,4=>5,#end main#
Main Activity
public class MainActivity extends Activity {
EditText user, password;
Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user = (EditText) findViewById(R.id.username_edit);
password = (EditText) findViewById(R.id.edit_password);
login = (Button) findViewById(R.id.btnSubmit);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Second.class);
String uservalue = user.getText().toString();
String name_value = password.getText().toString();
String password_value = password.getText().toString();
intent.putExtra("username", uservalue);
intent.putExtra("password", password_value);
startActivity(intent);
}
});
}
}
Second Activity in which you want to receive Data
public class Second extends Activity{
EditText name, pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
name = (EditText) findViewById(R.id.editText1);
pass = (EditText) findViewById(R.id.editText2);
String value = getIntent().getStringExtra("username");
String pass_val = getIntent().getStringExtra("password");
name.setText(value);
pass.setText(pass_val);
}
}
For email templates, inline CSS is the properly used method to style:
<thead>
<tr style="color: #fff; background: black;">
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
What about in one single line...
$('#txtSample').focus().val($('#txtSample').val());
This line works for me.
Here's the intended way to convert a String to a Date:
String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);
Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.
Code for adding fragment
public Fragment getItem(int position) {
switch (position){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
default:
break;
}
return null;
}
Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
Later you can make necessary corrections.. It worked for me.
Though djb2
, as presented on stackoverflow by cnicutar, is almost certainly better, I think it's worth showing the K&R hashes too:
1) Apparently a terrible hash algorithm, as presented in K&R 1st edition (source)
unsigned long hash(unsigned char *str)
{
unsigned int hash = 0;
int c;
while (c = *str++)
hash += c;
return hash;
}
2) Probably a pretty decent hash algorithm, as presented in K&R version 2 (verified by me on pg. 144 of the book); NB: be sure to remove % HASHSIZE
from the return statement if you plan on doing the modulus sizing-to-your-array-length outside the hash algorithm. Also, I recommend you make the return and "hashval" type unsigned long
instead of the simple unsigned
(int).
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31*hashval;
return hashval % HASHSIZE;
}
Note that it's clear from the two algorithms that one reason the 1st edition hash is so terrible is because it does NOT take into consideration string character order, so hash("ab")
would therefore return the same value as hash("ba")
. This is not so with the 2nd edition hash, however, which would (much better!) return two different values for those strings.
The GCC C++11 hashing functions used for unordered_map
(a hash table template) and unordered_set
(a hash set template) appear to be as follows.
Code:
// Implementation of Murmur hash for 32-bit size_t.
size_t _Hash_bytes(const void* ptr, size_t len, size_t seed)
{
const size_t m = 0x5bd1e995;
size_t hash = seed ^ len;
const char* buf = static_cast<const char*>(ptr);
// Mix 4 bytes at a time into the hash.
while (len >= 4)
{
size_t k = unaligned_load(buf);
k *= m;
k ^= k >> 24;
k *= m;
hash *= m;
hash ^= k;
buf += 4;
len -= 4;
}
// Handle the last few bytes of the input array.
switch (len)
{
case 3:
hash ^= static_cast<unsigned char>(buf[2]) << 16;
[[gnu::fallthrough]];
case 2:
hash ^= static_cast<unsigned char>(buf[1]) << 8;
[[gnu::fallthrough]];
case 1:
hash ^= static_cast<unsigned char>(buf[0]);
hash *= m;
};
// Do a few final mixes of the hash.
hash ^= hash >> 13;
hash *= m;
hash ^= hash >> 15;
return hash;
}
You don't need to add extra two classes (button button-primary), you just use the child class (button-primary) with css and it will apply parent as well as child css class. Here is the link:
Thanks to Jacob Lichner!
The Location
property has type Point
which is a struct.
Instead of trying to modify the existing Point
, try assigning a new Point
object:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y
);
Use Directory.GetDirectories
to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.
var directories = Directory.GetDirectories("your_directory_path");
By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.
Avoiding an UnauthorizedAccessException
It's easily possible that you'll get an UnauthorizedAccessException
if you hit a directory to which you don't have access.
You may have to create your own method that handles the exception, like this:
public class CustomSearcher
{
public static List<string> GetDirectories(string path, string searchPattern = "*",
SearchOption searchOption = SearchOption.AllDirectories)
{
if (searchOption == SearchOption.TopDirectoryOnly)
return Directory.GetDirectories(path, searchPattern).ToList();
var directories = new List<string>(GetDirectories(path, searchPattern));
for (var i = 0; i < directories.Count; i++)
directories.AddRange(GetDirectories(directories[i], searchPattern));
return directories;
}
private static List<string> GetDirectories(string path, string searchPattern)
{
try
{
return Directory.GetDirectories(path, searchPattern).ToList();
}
catch (UnauthorizedAccessException)
{
return new List<string>();
}
}
}
And then call it like this:
var directories = CustomSearcher.GetDirectories("your_directory_path");
This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException
, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.
If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:
df['a']= 'col' + df['a'].str[:]
This approach allows prepend, append, and subset string of df
.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.
I was struggling with this recently, and found the right way to create a default
task that runs sass
then sass:watch
was:
gulp.task('default', gulp.series('sass', 'sass:watch'));
Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:
uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft
This means that you need uname -r to distinguish it from native Linux.
I think you have deleted default .htaccess file inside the laravel public folder. upload the file it should fix your problem.
Unfortunately apple priority the device date format, so in some cases against what you put, swift change your format to 12hrs
To fix this is necessary to use setLocalizedDateFormatFromTemplate instead of dateFormat an hide the AM and PM
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss a")
formatter.amSymbol = ""
formatter.pmSymbol = ""
formatter.timeZone = TimeZone(secondsFromGMT: 0)
var prettyDate = formatter.string(from: Date())
You can check a very useful post with more information detailed in https://prograils.com/posts/the-curious-case-of-the-24-hour-time-format-in-swift
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
Simply wrap the code you want to execute into the onload event of the window object:
window.onload = function(){
// your code here
}
After @Arvis reply i decided to dig even deeper and I've written a tech article about this here: http://www.andreabaccega.com/blog/2015/08/16/how-to-avoid-fragments-overlapping-due-to-backstack-nightmare-in-android/
For the lazy developers around. My solution consists in always adding the transactions to the backstack and perform an extra FragmentManager.popBackStackImmediate()
when needed (automatically).
The code is very few lines of code and, in my example, I wanted to skip from C to A without jumping back to "B" if the user didn't went deeper in the backstack (ex from C navigates to D).
Hence the code attached would work as follow A -> B -> C (back) -> A & A -> B -> C -> D (back) -> C (back) -> B (back) -> A
where
fm.beginTransaction().replace(R.id.content, new CFragment()).commit()
were issued from "B" to "C" as in the question.
Ok,Ok here is the code :)
public static void performNoBackStackTransaction(FragmentManager fragmentManager, String tag, Fragment fragment) {
final int newBackStackLength = fragmentManager.getBackStackEntryCount() +1;
fragmentManager.beginTransaction()
.replace(R.id.content, fragment, tag)
.addToBackStack(tag)
.commit();
fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int nowCount = fragmentManager.getBackStackEntryCount();
if (newBackStackLength != nowCount) {
// we don't really care if going back or forward. we already performed the logic here.
fragmentManager.removeOnBackStackChangedListener(this);
if ( newBackStackLength > nowCount ) { // user pressed back
fragmentManager.popBackStackImmediate();
}
}
}
});
}
This annotation must be specified for persistent fields or properties of type java.util.Date
and java.util.Calendar
. It may only be specified for fields or properties of these types.
The Temporal
annotation may be used in conjunction with the Basic
annotation, the Id
annotation, or the ElementCollection
annotation (when the element collection value is of such a temporal type.
In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). Use the @Temporal
annotation to fine tune that.
The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date/time or both (TIMESTAMP
) in database table.
The temporal precision is not specified in core Java APIs. @Temporal
is a JPA
annotation that converts back and forth between timestamp and java.util.Date
. It also converts time-stamp
into time. For example, in the snippet below, @Temporal(TemporalType.DATE)
drops the time value and only preserves the date.
@Temporal(TemporalType.DATE)
private java.util.Date creationDate;
As per javadocs,
Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default
TemporalType.DATE
[Information above collected from various sources]
Rename the solution's corresponding .SUO file. The SUO file contains the TFS status (online/offline), amongst a host of other goodies.
Do this only if the "right-click on the solution name right at the top of the Solution Explorer and select the Go Online option" fails (because e.g. you installed VS2015 preview).
in your constructor you are creating another int array:
public Date(){
int[] data = {0,0,0};
}
Try this:
data = {0,0,0};
NOTE: By the way you do NOT need to initialize your array elements if it is declared as an instance variable. Instance variables automatically get their default values, which for an integer array, the default values are all zeroes.
If you had locally declared array though they you would need to initialize each element.
You can create an empty vector like so
vec <- numeric(0)
And then add elements using c()
vec <- c(vec, 1:5)
However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)
#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
echo "Usage: $0 DIRECTORY" >&2
exit 1
fi
Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.
More friendly error reporting:
#!/bin/sh
if [ "$#" -ne 1 ]; then
echo "Usage: $0 DIRECTORY" >&2
exit 1
fi
if ! [ -e "$1" ]; then
echo "$1 not found" >&2
exit 1
fi
if ! [ -d "$1" ]; then
echo "$1 not a directory" >&2
exit 1
fi
This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn();
is what you require
Just updating screenshots to help others as I am using a newer v18, circa 2019.
Here you can select certain tables or go with the default of all. For my own needs I'm indicating just the one table.
Next, there's the "Scripting Options" where you can choose output file, etc. As in multiple answers above (again, I'm just dusting off old answers for newer, v18.4 SQL Server Management Studio) what we're really wanting is under the "Advanced" button. For my own purposes, I need just the data.
Finally, there's a review summary before execution. After executing a report of operations' status is shown.
Most of these linker errors occur because of missing libraries.
I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.
That solved it for me on Xcode 6.3.2 for iOS 8.3
Cheers!
In my case, it was that the app had defaulted to a Wearable target device.
I removed the reference to Wearable in my Manifest, and the problem was solved.
<uses-library android:name="com.google.android.wearable" android:required="true" />
I needed to do this just now and required a cross-platform solution that was suitable for c++11, boost and openssl. I took D'Nabre's solution as a starting point and boiled it down to the following:
#include <openssl/md5.h>
#include <iomanip>
#include <sstream>
#include <boost/iostreams/device/mapped_file.hpp>
const std::string md5_from_file(const std::string& path)
{
unsigned char result[MD5_DIGEST_LENGTH];
boost::iostreams::mapped_file_source src(path);
MD5((unsigned char*)src.data(), src.size(), result);
std::ostringstream sout;
sout<<std::hex<<std::setfill('0');
for(auto c: result) sout<<std::setw(2)<<(int)c;
return sout.str();
}
A quick test executable demonstrates:
#include <iostream>
int main(int argc, char *argv[]) {
if(argc != 2) {
std::cerr<<"Must specify the file\n";
exit(-1);
}
std::cout<<md5_from_file(argv[1])<<" "<<argv[1]<<std::endl;
return 0;
}
Some linking notes:
Linux: -lcrypto -lboost_iostreams
Windows: -DBOOST_ALL_DYN_LINK libeay32.lib ssleay32.lib
I have created a working CodePen example to demonstrate how you might accomplish your goals.
I added ng-click
to the <form>
and removed the logic from your button:
<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />
Here's the updated template:
<section ng-app="app" ng-controller="MainCtrl">
<form class="well" name="addRelation" data-ng-click="save(model)">
<label>First Name</label>
<input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
<label>Last Name</label>
<input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
<label>Email</label>
<input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
<input class="btn" type="submit" value="SAVE" />
</form>
</section>
and controller code:
app.controller('MainCtrl', function($scope) {
$scope.save = function(model) {
$scope.addRelation.submitted = true;
if($scope.addRelation.$valid) {
// submit to db
console.log(model);
} else {
console.log('Errors in form data');
}
};
});
I hope this helps.
Why don't you let PHP do the job?
"UPDATE member_profile SET points= ' ". ($points+1) ." ' WHERE user_id = '".$userid."'"
In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1;
on the surrounding DIVs.
One thing which is invariably true is that at this time, the device would be suffocating for some memory (which is usually the reason for GC to most likely get triggered).
As mentioned by almost all authors earlier, this issue surfaces when Android tries to run GC while the app is in background. In most of the cases where we observed it, user paused the app by locking their screen. This might also indicate memory leak somewhere in the application, or the device being too loaded already. So the only legitimate way to minimize it is:
pgcrypto
ExtensionAs of Postgres 9.4, the pgcrypto
module includes the gen_random_uuid()
function. This function generates one of the random-number based Version 4 type of UUID.
Get contrib modules, if not already available.
sudo apt-get install postgresql-contrib-9.4
Use pgcrypto
module.
CREATE EXTENSION "pgcrypto";
The gen_random_uuid()
function should now available;
Example usage.
INSERT INTO items VALUES( gen_random_uuid(), 54.321, 31, 'desc 1', 31.94 ) ;
Quote from Postgres doc on uuid-ossp
module.
Note: If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.
ArrayList
is unique in its naming standards. Here are the equivalencies:
Array.push -> ArrayList.add(Object o); // Append the list
Array.pop -> ArrayList.remove(int index); // Remove list[index]
Array.shift -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list
Note that unshift
does not remove an element, but instead adds one to the list. Also note that corner-case behaviors are likely to be different between Java and JS, since they each have their own standards.
Here is a tool that generates relational diagrams from MySQL (on Windows at the moment). I have used it on a database with 400 tables. If the diagram is too big for a single diagram, it gets broken down into smaller ones. So you will probably end up with multiple diagrams and you can navigate between them by right clicking. It is all explained in the link below. The tool is free (as in free beer), the author uses it himself on consulting assignments, and lets other people use it. http://www.scmlite.com/Quick%20overview
You can also use PreviewKeyDown in WPF:
<TextBox PreviewKeyDown="EnterClicked" />
or in C#:
myTextBox.PreviewKeyDown += EnterClicked;
And then in the attached class:
void EnterClicked(object sender, KeyEventArgs e) {
if(e.Key == Key.Return) {
DoSomething();
e.Handled = true;
}
}
here is the best practiced method to center a div as position absolute
code --
#header {
background:black;
height:90px;
width:100%;
position:relative; // you forgot this, this is very important
}
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin: auto; // margin auto works just you need to put top left bottom right as 0
top:0;
bottom:0;
left:0;
right:0;
}
Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay
. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.
The key excerpt to look at is:
# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)
learning_rate = tf.train.exponential_decay(
0.01, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
train_size, # Decay step.
0.95, # Decay rate.
staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
0.9).minimize(loss,
global_step=batch)
Note the global_step=batch
parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.
Take a look at new Constraint
public class MyClass<T> where T : new()
{
protected T GetObject()
{
return new T();
}
}
T
could be a class that does not have a default constructor: in this case new T()
would be an invalid statement. The new()
constraint says that T
must have a default constructor, which makes new T()
legal.
You can apply the same constraint to a generic method:
public static T GetObject<T>() where T : new()
{
return new T();
}
If you need to pass parameters:
protected T GetObject(params object[] args)
{
return (T)Activator.CreateInstance(typeof(T), args);
}
You may also consider the Apache Commons JCI (Java Compiler Interface). Although this API seems to be focused on dynamic compilation of classes, it also includes classes in its API that monitors file changes.
If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a
as a "variable", and start thinking of it as a "name".
a
, b
, and c
aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.
Names don't have any of that. Values do, of course, and you can have lots of names for the same value.
If you give Notorious B.I.G.
a hot dog,* Biggie Smalls
and Chris Wallace
have a hot dog. If you change the first element of a
to 1, the first elements of b
and c
are 1.
If you want to know if two names are naming the same object, use the is
operator:
>>> a=b=c=[0,3,5]
>>> a is b
True
You then ask:
what is different from this?
d=e=f=3
e=4
print('f:',f)
print('e:',e)
Here, you're rebinding the name e
to the value 4
. That doesn't affect the names d
and f
in any way.
In your previous version, you were assigning to a[0]
, not to a
. So, from the point of view of a[0]
, you're rebinding a[0]
, but from the point of view of a
, you're changing it in-place.
You can use the id
function, which gives you some unique number representing the identity of an object, to see exactly which object is which even when is
can't help:
>>> a=b=c=[0,3,5]
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261120
>>> id(b[0])
4297261120
>>> a[0] = 1
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261216
>>> id(b[0])
4297261216
Notice that a[0]
has changed from 4297261120 to 4297261216—it's now a name for a different value. And b[0]
is also now a name for that same new value. That's because a
and b
are still naming the same object.
Under the covers, a[0]=1
is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1)
.) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1)
. Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1
.
user570826 asked:
What if we have,
a = b = c = 10
That's exactly the same situation as a = b = c = [1, 2, 3]
: you have three names for the same value.
But in this case, the value is an int
, and int
s are immutable. In either case, you can rebind a
to a different value (e.g., a = "Now I'm a string!"
), but the won't affect the original value, which b
and c
will still be names for. The difference is that with a list, you can change the value [1, 2, 3]
into [1, 2, 3, 4]
by doing, e.g., a.append(4)
; since that's actually changing the value that b
and c
are names for, b
will now b [1, 2, 3, 4]
. There's no way to change the value 10
into anything else. 10
is 10 forever, just like Claudia the vampire is 5 forever (at least until she's replaced by Kirsten Dunst).
* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.
For Windows...in order to make gradle re-download specific dependencies:
delete the dependencies you want to re-download from the directory below:
C:\Users\%USERNAME%\.gradle\caches\modules-2\files-2.1
delete all metadata directories at the path:
C:\Users\%USERNAME%\.gradle\caches\modules-2\metadata-*
run gradle build
(or gradlew build
if using gradle wrapper) in the project's root directory.
note: the numbers in the file paths above might be different for you.
The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.
You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \r
rather than the linux standard \n
or better still the suspenders and belt approach of windows with \r\n
.
pandas.read_csv(filename, sep='\t', lineterminator='\r')
You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.
import codecs
doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set
df = pandas.read_csv(doc, sep='\t')
Try this,
$('.nav-list li').click(function() {
$('.nav-list li.active').removeClass('active');
$(this).addClass('active');
});
In your context $(this)
will points to the UL
element not the Li
. Hence you are not getting the expected results.
New CSS Specs contain an experimental :has
pseudo selector that might be able to do this thing.
li:has(a:active) {
/* ... */
}
The browser support on this is basically non-existent at this time, but it is in consideration on the official specs.
While it is true that CSS cannot ASCEND, it is incorrect that you cannot grab the parent element of another element. Let me reiterate:
Using your HTML example code, you are able to grab the li without specifying li
ul * a {
property:value;
}
In this example, the ul is the parent of some element and that element is the parent of anchor. The downside of using this method is that if there is a ul with any child element that contains an anchor, it inherits the styles specified.
You may also use the child selector as well since you'll have to specify the parent element anyway.
ul>li a {
property:value;
}
In this example, the anchor must be a descendant of an li that MUST be a child of ul, meaning it must be within the tree following the ul declaration. This is going to be a bit more specific and will only grab a list item that contains an anchor AND is a child of ul.
SO, to answer your question by code.
ul.menu > li a.active {
property:value;
}
This should grab the ul with the class of menu, and the child list item that contains only an anchor with the class of active.
You can do this.
When hovering to the .item1
, it will change the .item2
element.
.item1 {
size:100%;
}
.item1:hover
{
.item2 {
border:none;
}
}
.item2{
border: solid 1px blue;
}
You can also do
rake db:rollback
if you have not added any data to the tables.Then edit the migration file by adding the email column to it and then call
rake db:migrate
This will work if you have rails 3.1 onwards installed in your system.
Much simpler way of doing it is change let the change in migration file be as it is. use
$rake db:migrate:redo
This will roll back the last migration and migrate it again.
A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.
If this is happening intermittently, then the most likely explanations are (IMO):
Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.
It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.
1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.
To add up on the answer, I used this at the beginning of the needed script. So it runs smoothly on different environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
Because I didn't want it to be alsways using the 'Agg'
backend, only when it would go through Travis CI for example.
I also had this issue. I had both VS code
and Android studio
installed in my system.
The error was in VS code
.
When i opened the same project on Android studio
, the dependency was not actually added to pubsec.yaml
. I added it there and ran pub.get
.
When I returned to VS Code
and everything was working fine.
So, Try opening it in other editor if you have, or through NotePad
.
Edit:
Opening widget_test.dart
and running it should also solve your issue.
As many excellent answers noted, there are a lot of limits that depend on your version of C++ compiler, operating system and computer characteristics. However, I suggest the following script on Python that checks the limit on your machine.
It uses binary search and on each iteration checks if the middle size is possible by creating a code that attempts to create an array of the size. The script tries to compile it (sorry, this part works only on Linux) and adjust binary search depending on the success. Check it out:
import os
cpp_source = 'int a[{}]; int main() {{ return 0; }}'
def check_if_array_size_compiles(size):
# Write to file 1.cpp
f = open(name='1.cpp', mode='w')
f.write(cpp_source.format(m))
f.close()
# Attempt to compile
os.system('g++ 1.cpp 2> errors')
# Read the errors files
errors = open('errors', 'r').read()
# Return if there is no errors
return len(errors) == 0
# Make a binary search. Try to create array with size m and
# adjust the r and l border depending on wheather we succeeded
# or not
l = 0
r = 10 ** 50
while r - l > 1:
m = (r + l) // 2
if check_if_array_size_compiles(m):
l = m
else:
r = m
answer = l + check_if_array_size_compiles(r)
print '{} is the maximum avaliable length'.format(answer)
You can save it to your machine and launch it, and it will print the maximum size you can create. For my machine it is 2305843009213693951.
To make it work you only need two things. Check if you are missing:
You need to add dependency for jersey-json if you are missing.For your reference I added this dependency into my pom.xml.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
function starts_with($s, $prefix){
// returns a bool
return strpos($s, $prefix) === 0;
}
starts_with($variable, "_");
This is CSS issues. I don't know why @Html.DropDownListFor in Bootstrap 4 doest work. Surely this is class design problem. Anyways the work arround is, if your Dropdown input box has CSS Padding: #px, # px; element then disable it. Hope this will work.
But I have declared that var in the top of the other files.
That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const
.
Instead, use var
, use only one declaration in your main file, or only assign to window.APP
exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.
If you are really worried about undefined being redefined, you can protect against this with some helper method like this:
function is_undefined(value) {
var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
return value === undefined_check;
}
This works because when someone writes undefined = "foo"
he only lets the name undefined
reference to a new value, but he doesn't change the actual value of undefined
.