Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.
You can do this instead:
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))
From SQL Server point of view:
Clustering will give you an active - passive configuration. Meaning in a 2 node cluster, one of them will be the active (serving) and the other one will be passive (waiting to take over when the active node fails). It's a high availability from hardware point of view.
You can have an active-active cluster, but it will require multiple instances of SQL Server running on each node. (i.e. Instance 1 on Node A failing over to Instance 2 on Node B, and instance 1 on Node B failing over to instance 2 on Node A).
Load balancing (at least from SQL Server point of view) does not exists (at least in the same sense of web server load balancing). You can't balance load that way. However, you can split your application to run on some database on server 1 and also run on some database on server 2, etc. This is the primary mean of "load balancing" in SQL world.
Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
function displayFile(whatOption, whatColor) {_x000D_
var Test01 = {_x000D_
rectangle: {_x000D_
red: "RectangleRedFile",_x000D_
blue: "RectangleBlueFile"_x000D_
},_x000D_
square: {_x000D_
red: "SquareRedFile",_x000D_
blue: "SquareBlueFile"_x000D_
}_x000D_
};_x000D_
var filename = Test01[whatOption][whatColor];_x000D_
alert(filename);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
I created a small tool that imports csv
file into PostgreSQL super easy, just a command and it will create and populate the tables, unfortunately, at the moment all fields automatically created uses the type TEXT
csv2pg users.csv -d ";" -H 192.168.99.100 -U postgres -B mydatabase
The tool can be found on https://github.com/eduardonunesp/csv2pg
pycrc is a Python script that generates C CRC code, with options to select the CRC size, algorithm and model.
It's released under the MIT licence. Is that acceptable for your purposes?
The method viewWillAppear
should be taken in the context of what is going on in your own application, and not in the context of your application being placed in the foreground when you switch back to it from another app.
In other words, if someone looks at another application or takes a phone call, then switches back to your app which was earlier on backgrounded, your UIViewController which was already visible when you left your app 'doesn't care' so to speak -- as far as it is concerned, it's never disappeared and it's still visible -- and so viewWillAppear
isn't called.
I recommend against calling the viewWillAppear
yourself -- it has a specific meaning which you shouldn't subvert! A refactoring you can do to achieve the same effect might be as follows:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self doMyLayoutStuff:self];
}
- (void)doMyLayoutStuff:(id)sender {
// stuff
}
Then also you trigger doMyLayoutStuff
from the appropriate notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doMyLayoutStuff:) name:UIApplicationDidChangeStatusBarFrameNotification object:self];
There's no out of the box way to tell which is the 'current' UIViewController by the way. But you can find ways around that, e.g. there are delegate methods of UINavigationController for finding out when a UIViewController is presented therein. You could use such a thing to track the latest UIViewController which has been presented.
Update
If you layout out UIs with the appropriate autoresizing masks on the various bits, sometimes you don't even need to deal with the 'manual' laying out of your UI - it just gets dealt with...
Here's a slightly more flexible approach using the match
method. With this, you can extract more than one string:
s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)
# Use 'captures' to get an array of the captures
matchdata.captures # ["ants","pants"]
# Or use raw indices
matchdata[0] # whole regex match: "<ants> <pants>"
matchdata[1] # first capture: "ants"
matchdata[2] # second capture: "pants"
The MOUSEBUTTONDOWN
event occurs once when you click the mouse button and the MOUSEBUTTONUP
event occurs once when the mouse button is released. The pygame.event.Event()
object has two attributes that provide information about the mouse event. pos
is a tuple that stores the position that was clicked. button
stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event
.
Use the rect
attribute of the pygame.sprite.Sprite
object and the collidepoint
method to see if the Sprite was clicked.
Pass the list of events to the update
method of the pygame.sprite.Group
so that you can process the events in the Sprite class:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseClick
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.click_image, color, (25, 25), 25)
pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.clicked = False
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.clicked = not self.clicked
self.image = self.click_image if self.clicked else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
See further Creating multiple sprites with different update()'s from the same sprite class in Pygame
The current position of the mouse can be determined via pygame.mouse.get_pos()
. The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed()
returns a list of Boolean values ??that represent the state (True
or False
) of all mouse buttons. The state of a button is True
as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True
. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.
Detect evaluate the mouse states in the Update
method of the pygame.sprite.Sprite
object:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
if self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseHover
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.hover_image, color, (25, 25), 25)
pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.hover = False
def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
#self.hover = self.rect.collidepoint(mouse_pos)
self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)
self.image = self.hover_image if self.hover else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update()
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
A basic implementation which you'll need to adapt would look something like this:
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
// can return this or...
let params = kvp.join('&');
// reload page with new params
document.location.search = params;
}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
the slow regex method I benchmarked against for completions sake (approx +150% slower)
function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);
var s = document.location.search;
var kvp = key+"="+value;
var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
s = s.replace(r,"$1"+kvp);
if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
//again, do what you will here
document.location.search = s;
}
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
If you make data table or datagridview from the code you can save all data using this simple method.this method not recomended but its working 100%, even you are not install MS Excel in your computer.
try
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
saveFileDialog1.FileName = "Employee Details.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fname = saveFileDialog1.FileName;
StreamWriter wr = new StreamWriter(fname);
for (int i = 0; i <DataTable.Columns.Count; i++)
{
wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (DataTable.Rows.Count); i++)
{
for (int j = 0; j < DataTable.Columns.Count; j++)
{
if (DataTable.Rows[i][j] != null)
{
wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
}
catch (Exception)
{
MessageBox.Show("Error Create Excel Sheet!");
}
$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";
This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma
Last-Modified : The last modified date for the requested object
If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.
ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.
If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.
the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:
the server will return 304 when the if statement is False, and browser will use cache.
Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:
Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.
Incorrect:
$response = $client->post('http://example.com/api', [
'body' => [
'name' => 'Example name',
]
])
Correct:
$response = $client->post('http://example.com/api', [
'json' => [
'name' => 'Example name',
]
])
Correct:
$response = $client->post('http://example.com/api', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode([
'name' => 'Example name',
])
])
If you mean File.separator
and File.pathSeparator
then:
File.pathSeparator
is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ;
to separate the file paths so on Windows File.pathSeparator
would be ;
.
File.separator
is either /
or \
that is used to split up the path to a specific file. For example on Windows it is \
or C:\Documents\Test
My code was broken because I was using a deprecated technique. It used to be this:
video.src = window.URL.createObjectURL(localMediaStream);
video.play();
Then I replaced that with this:
video.srcObject = localMediaStream;
video.play();
That worked beautifully.
EDIT: Recently localMediaStream
has been deprecated and replaced with MediaStream
. The latest code looks like this:
video.srcObject = new MediaStream();
References:
Using UnderscoreJS:
angular.module('myModule')
.run(['$rootScope', function($rootScope) { $rootScope.range = _.range; }]);
Applying this to $rootScope
makes it available everywhere:
<div ng-repeat="x in range(1,10)">
{{x}}
</div>
In Java, HashMap works by using hashCode to locate a bucket. Each bucket is a list of items residing in that bucket. The items are scanned, using equals for comparison. When adding items, the HashMap is resized once a certain load percentage is reached.
So, sometimes it will have to compare against a few items, but generally it's much closer to O(1) than O(n). For practical purposes, that's all you should need to know.
You can use the contains selector to search for elements containing a specific text
var elem = $('div.text_div:contains("This div contains some text")')?;
elem.text(elem.text().replace("contains", "Hello everyone"));
??????????????????????????????????????????
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
dt.Rows[1].ItemArray
gives you a copy of item arrays. When you modify it, you're not modifying the original.
You can simply do this:
dt.Rows[1][3] = "Value";
ItemArray property is used when you want to modify all row values.
ex.:
dt.Rows[1].ItemArray = newItemArray;
Your header file Hash.h
declares "what class hash
should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp
. By including the header in your main file, the compiler is informed of the description of class Hash
when compiling the file, but not how class Hash
actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)
) cannot be found.
The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:
g++ -o main Hash.cpp main.cpp
will create the main program called "main".
In Kotlin,
val stringArray = commasString.replace(", ", ",").split(",")
where stringArray
is List<String>
and commasString
is String
with commas and spaces
This happened to me because I had a ddd()
or dd()
;die; in my routes/web.php file I forgot about.
Please follow below steps to install python 3 with pip:
Step 1 : Install Python from download here
Step 2 : you’ll need to download get-pip.py
Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .
Step 4 : Enter command python get-pip.py
in cmd.
Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version
@controller is a singleton object, and if inject a prototype bean to a singleton class will make the prototype bean also as singleton unless u specify using lookup-method property which actually create a new instance of prototype bean for every call you make.
I was using jruby, in my case I created under config/initializers
postgres_driver.rb
$CLASSPATH << '~/.rbenv/versions/jruby-1.7.17/lib/ruby/gems/shared/gems/jdbc-postgres-9.4.1200/lib/postgresql-9.4-1200.jdbc4.jar'
or wherever your driver is, and that's it !
Mysql-native has been outdated so it became MySQL2 that is a new module created with the help of the original MySQL module's team. This module has more features and I think it has what you want as it has prepared statements(by using.execute()) like in PHP for more security.
It's also very active(the last change was from 2-1 days) I didn't try it before but I think it's what you want and more.
You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]
Note: for option 4 for you'll need to import numpy as np
Update: You can also use the .query
method for this too. This allows for method chaining:
5. df.query("column not in @values")
.
where values
is a list of the values that you don't want to include.
As we can see in ActionController::Base
, before_action
is just a new syntax for before_filter
.
However all before_filters
syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
From cppreference when incrementing iterators:
You should prefer pre-increment operator (++iter) to post-increment operator (iter++) if you are not going to use the old value. Post-increment is generally implemented as follows:
Iter operator++(int) {
Iter tmp(*this); // store the old value in a temporary object
++*this; // call pre-increment
return tmp; // return the old value }
Obviously, it's less efficient than pre-increment.
Pre-increment does not generate the temporary object. This can make a significant difference if your object is expensive to create.
In .NET Core 3.1 you can do the following in the model class:
public bool? Active { get; set; }
In the DbContext OnModelCreating you add the default value.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Foundation>()
.Property(b => b.Active)
.HasDefaultValueSql("1");
base.OnModelCreating(modelBuilder);
}
Resulting in the following in the database
Note: If you don't have nullable (bool?) for you property you will get the following warning
The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used for inserts when the property value is 'null'.
On Window machine install any version of Git. I installed
Git-2.14.1-64-bit.exe
. Got to search program and search for git.exe. The file can be located under
C:\Users\sd\AppData\Local\Programs\Git\bin\git.exe
.
Open Intelli IDEA>Settings>Version Control>Git. On Path To Git executable add the path. Click on Test button. It will show a message as
Git executed successfully
Now click on Apply and Save. This will solve the issue. .
If you don't want to use jquery, use this:
<script>
// without jquery
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
// run your open popup function after 5 sec = 5000
PopUp();
}, 5000)
});
</script>
OR With jquery
<script>
$(document).ready(function(){
setTimeout(function(){
// open popup after 5 seconds
PopUp();
},5000);
});
</script>
With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.
The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:
<iframe type="text/html"
width="640"
height="385"
src="http://www.youtube.com/embed/VIDEO_ID"
frameborder="0">
</iframe>
If you are behind a firewall you will have to configure the Tortoise client to connect to it. Right click somewhere in your window, select "TortoiseSVN", select "settings", and then select "network" on the left side of the panel. Fill out all the required fields. Good luck.
In addition to the above answer, this is the actual code:
[[UIDevice currentDevice] name];
The issue could be that Github isn't present in your ~/.ssh/known_hosts file.
Append GitHub to the list of authorized hosts:
ssh-keyscan -H github.com >> ~/.ssh/known_hosts
There's little. From portability viewpoint, char
cannot be smaller than 8 bits, and nothing can be smaller than char
, so if a given C implementation has an unsigned 8-bit integer type, it's going to be char
. Alternatively, it may not have one at all, at which point any typedef
tricks are moot.
It could be used to better document your code in a sense that it's clear that you require 8-bit bytes there and nothing else. But in practice it's a reasonable expectation virtually anywhere already (there are DSP platforms on which it's not true, but chances of your code running there is slim, and you could just as well error out using a static assert at the top of your program on such a platform).
PEP 8 defines that it is better to use the is
operator when comparing singletons.
It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.
As Apple stated:
In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)
You can use Boost demangle to accomplish a nice looking name:
#include <boost/units/detail/utility.hpp>
and something like
To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);
Example of CSS Text Gradient
background-image: -moz-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -webkit-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -o-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -ms-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: linear-gradient(top,#E605C1 0%,#3B113B 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
position:relative;
display:inline-block; /*required*/
Online generator textgradient.com
I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.
Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).
This method takes one Function as an argument, this function accepts one parameter T as an input argument and return one stream of parameter R as a return value. When this function is applied on each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
If we want to bind to a dictionary ie
<ComboBox SelectedValue="{Binding Pathology, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{x:Static RnxGlobal:CLocalizedEnums.PathologiesValues}" DisplayMemberPath="Value" SelectedValuePath="Key"
Margin="{StaticResource SmallMarginLeftBottom}"/>
then SelectedItem will not work whilist SelectedValue will
Usually a back-reference is either $1
or \1
(backslash one) for the first capture group (the first match of a pattern in parentheses), and indeed Sublime supports both syntaxes. So try:
my name used to be \1
or
my name used to be $1
Also note that your original capture pattern:
my name is (\w)+
is incorrect and will only capture the final letter of the name rather than the whole name. You should use the following pattern to capture all of the letters of the name:
my name is (\w+)
To select an option, use .val('value-of-the-option')
on the select element. To trigger the change element, use .change()
or .trigger('change')
.
The problems in your code are the comma instead of the dot in $('.check'),trigger('change');
and the fact that you call it before binding the event handler.
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
I found the solution, Thanks all for reply.
category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));
But, I have already dont know the reason. I cant understand fully.
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
If there is still issue around access after creating SSH and adding it in your Bitbucket account or wherever, you need to do the following in terminal on GitBash, OSX or Linux:
# Lists already added identities (‘ssh keys’)
ssh-add -l
Then, if you don't see your key listed, add it with the following (replace identity
with its real name):
# Add a new identity
ssh-add ~/.ssh/identity
This worked for me.
You don't appear to understand what still reachable
means.
Anything still reachable
is not a leak. You don't need to do anything about it.
This is nothing to do with hardware nor software. Simply that RGB are the 3 primary colours which can be combined in various ways to produce every other colour. It is more about the human convention/perception of colours which carried over.
You may find this article interesting.
firstOrCreate()
checks for all the arguments to be present before it finds
a match. If not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value'])
with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate()
and firstOrNew()
:
firstOrCreate()
will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.firstOrNew()
will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save()
on the model). Otherwise it will give you the matched item.Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name
or some mandatory field), you should use firstOrNew()
. If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate()
.
ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:
select s.id, s.age, c.count
from students s
inner join (
select age, count(*) as count
from students
group by age
) c on s.age = c.age
order by id
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.
sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'
You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows.
Advantage of below approach is thats you can avoid dirty looking URL with it. eg: /home(aux:login) etc.
Assuming on load you are bootstraping appComponent.
app.component.html
<div class="layout">
<div class="page-header">
//first outlet to load required component
<router-outlet name='child1'></router-outlet>
</div>
<div class="content">
//second outlet to load required component
<router-outlet name='child2'></router-outlet>
</div>
</div>
Add following to your router.
{
path: 'home', // you can keep it empty if you do not want /home
component: 'appComponent',
children: [
{
path: '',
component: childOneComponent,
outlet: 'child1'
},
{
path: '',
component: childTwoComponent,
outlet: 'child2'
}
]
}
Now when /home is loaded appComponent will get load with allocated template, then angular router will check the route and load the children component in specified router outlet on the basis of name.
Like above you can configure your router to have multiple router-outlet in same route.
The thing I use is this:
In your template an alert area
<div id="alert-area"></div>
Then an jQuery function for showing an alert
function newAlert (type, message) {
$("#alert-area").append($("<div class='alert-message " + type + " fade in' data-alert><p> " + message + " </p></div>"));
$(".alert-message").delay(2000).fadeOut("slow", function () { $(this).remove(); });
}
newAlert('success', 'Oh yeah!');
For those who are having a hard time finding the "merge buttons".
The little lightbulp icon with merge options only shows up if you click precisely on the "merge conflict marker"
<<<<<<<
Steps (in VS Code 1.29.x):
I know this is an old post and you marked the question as answered. I was looking for the same thing recently and I found the histedit
extension very useful. The process is explained here:
http://knowledgestockpile.blogspot.com/2010/12/changing-commit-message-of-revision-in.html
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
You can have multiple versions of GCC on your box, to select the one you want to use call it with full path, e.g. instead of g++
use full path /usr/bin/g++
on command line (depends where your gcc lives).
For compiling projects it depends what system do you use, I'm not sure about Xcode (I'm happy with default atm) but when you use Makefiles you can set GXX=/usr/bin/g++ and so on.
EDIT
There's now a xcrun
script that can be queried to select appropriate version of build tools on mac. Apart from man xcrun
I've googled this explanation about xcode and command line tools which pretty much summarizes how to use it.
use below code
Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
You create the relationships the other way around; add foreign keys to the Person
type to create a Many-to-One relationship:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
Anniversary, on_delete=models.CASCADE)
address = models.ForeignKey(
Address, on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person
entries.
Anniversary
and Address
objects will be given a reverse, backwards relationship too; by default it'll be called person_set
but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.
The problem is that the true y is binary (zeros and ones), while your predictions are not. You probably generated probabilities and not predictions, hence the result :) Try instead to generate class membership, and it should work!
You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.
The preferred approach should be:
Double.valueOf(d).longValue()
From the Double (Java Platform SE 7) documentation:
Double.valueOf(d)
Returns a
Double
instance representing the specifieddouble
value. If a newDouble
instance is not required, this method should generally be used in preference to the constructorDouble(double)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values.
This may not be exactly on target because I am not completely clear on what you want to do. However, assuming you mean you want to assign a different class to a div in response to an event, the answer is yes, you can certainly do this with jQuery. I am only a jQuery beginner, but I have used the following in my code:
$(document).ready(function() {
$("#someElementID").click(function() { // this is your event
$("#divID").addClass("second"); // here your adding the new class
)};
)};
If you wanted to replace the first class with the second class, I believe you would use removeClass first and then addClass as I did above. toggleClass may also be worth a look. The jQuery documentation is well written for these type of changes, with examples.
Someone else my have a better option, but I hope that helps!
Using CSS only, no. You need to use jQuery to add it.
Try the code below to prevent the default behaviour scrolling back to the top of the page
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
For more information on event.preventDefault() have a look here at the official documentation.
you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn
List<AttributeHistory> findByValueIn(List<String> values);
The static
keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.
Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.
Take a look at these. I didn't use more parenthesis to keep it readable, so remember that multiplication is done before addition or subtraction.
Both below return:
hr mins sec timediff
73 12 30 73:12:30
This is written to not use a sub-query and be the most readable and understandable:
declare @StartDate datetime,
@EndDate datetime
set @StartDate = '10/01/2012 08:40:18.000'
set @EndDate = '10/04/2012 09:52:48.000'
select datediff(hour, @StartDate, @EndDate) hr,
datediff(minute, @StartDate, @EndDate)
- datediff(hour, @StartDate, @EndDate) * 60 mins,
datediff(second, @StartDate, @EndDate)
- (datediff(minute, @StartDate, @EndDate) * 60) sec,
cast(datediff(hour, @StartDate, @EndDate) as varchar)+':'+
cast(datediff(minute, @StartDate, @EndDate)
- datediff(hour, @StartDate, @EndDate) * 60 as varchar)+':'+
cast(datediff(second, @StartDate, @EndDate)
- (datediff(minute, @StartDate, @EndDate) * 60) as varchar) timediff
This is a version that would perform better if you have a lot of data. It requires a sub-query.
declare @StartDate datetime,
@EndDate datetime
set @StartDate = '10/01/2012 08:40:18.000'
set @EndDate = '10/04/2012 09:52:48.000'
select s.seconds / 3600 hrs,
s.seconds / 60 - (seconds / 3600 ) * 60 mins,
s.seconds - (s.seconds / 60) * 60 seconds,
cast(s.seconds / 3600 as varchar) + ':' +
cast((s.seconds / 60 - (seconds / 3600 ) * 60) as varchar) + ':' +
cast((s.seconds - (s.seconds / 60) * 60) as varchar) timediff
from (select datediff(second, @StartDate, @EndDate) as seconds) s
It's declaring the string as nvarchar
data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
Close the nodejs terminal and Rebuild.
To run it as a full daemon from a shell, you'll need to use setsid
and redirect its output. You can redirect the output to a logfile, or to /dev/null
to discard it. Assuming your script is called myscript.sh, use the following command:
setsid myscript.sh >/dev/null 2>&1 < /dev/null &
This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null
with your /path/to/logfile.
You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).
Here the simple step that you can easily set phpMyAdmin Password.
C:\xampp\phpMyAdmin
and find config.inc.php
fileconfig.inc.php
file in Text editor like Notepad++.$cfg['Servers'][$a]['auth_type'] = 'config';
in config.inc.php
file.$cfg['Servers'][$a]['auth_type'] = 'config';
to $cfg['Servers'][$a]['auth_type'] = 'cookie';
in config.inc.php
file and Save the changes.localhost/phpmyadmin
. Enter username is root. password is null means empty. you don't type anything leave blank and press GO button.Simple variant:
Regex.Replace(input, @"\r\n|\r|\n", "\r\n")
For better performance:
static Regex newline_pattern = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
[...]
newline_pattern.Replace(input, "\r\n");
int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).
With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to write
Integer n = 9;
which is interpreted as
Integer n = Integer.valueOf(9);
For weeks, you can use function difftime
:
date1 <- strptime("14.01.2013", format="%d.%m.%Y")
date2 <- strptime("26.03.2014", format="%d.%m.%Y")
difftime(date2,date1,units="weeks")
Time difference of 62.28571 weeks
But difftime
doesn't work with duration over weeks.
The following is a very suboptimal solution using cut.POSIXt
for those durations but you can work around it:
seq1 <- seq(date1,date2, by="days")
nlevels(cut(seq1,"months"))
15
nlevels(cut(seq1,"quarters"))
5
nlevels(cut(seq1,"years"))
2
This is however the number of months, quarters or years spanned by your time interval and not the duration of your time interval expressed in months, quarters, years (since those do not have a constant duration). Considering the comment you made on @SvenHohenstein answer I would think you can use nlevels(cut(seq1,"months")) - 1
for what you're trying to achieve.
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
ProductionWorker
extends Employee
, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super();
call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super();
cannot be placed automatically due to the fact that Employee's constructor has parameters.
You either need to define a default constructor in your Employee
class, or call super('Erkan', 21, new Date());
in the first line of the constructor in ProductionWorker.
No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/
directory, or Scripts\
on Windows).
The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.
HEAD: the current commit your repo is on. Most of the time HEAD
points to the latest commit in your current branch, but that doesn't have to be the case. HEAD
really just means "what is my repo currently pointing at".
In the event that the commit HEAD
refers to is not the tip of any branch, this is called a "detached head".
master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.
origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.
HEAD
is an official notion in git. HEAD
always has a well-defined meaning. master
and origin
are common names usually used in git, but they don't have to be.
you would possibbly need to specify the height of container and then set the nav's height to 100%.
Edit: had a quick look around and it seems that the height property applies to the parents height so you will indeed need to set the containers height.
NB: setting the height of the body element to 100% only scales it to the height of the browser window. Any content which goeds over one page will not have the same background etc.
The general idiom for assigning to a value that isn't used is to name it _
.
for _ in range(times):
do_stuff()
This is in the case if first answer does not work The latest version of git does not require to set proxy it directly uses system proxy settings .so just do these
unset HTTP_PROXY
unset HTTPS_PROXY
in some systems you may also have to do
unset http_proxy
unset https_proxy
if you want to permanantly remove proxy then
sudo gsettings set org.gnome.system.proxy mode 'none'
I rise to the challenge of providing the signed answer:
def f(x,y):
import math
return min(y-x, y-x+2*math.pi, y-x-2*math.pi, key=abs)
You cannot concatenate raw strings like this. operator+
only works with two std::string
objects or with one std::string
and one raw string (on either side of the operation).
std::string s("...");
s + s; // OK
s + "x"; // OK
"x" + s; // OK
"x" + "x" // error
The easiest solution is to turn your raw string into a std::string
first:
"Do you feel " + std::string(AGE) + " years old?";
Of course, you should not use a macro in the first place. C++ is not C. Use const
or, in C++11 with proper compiler support, constexpr
.
WordNet database might be helpful. I once worked on a Firefox add-on which deals with words and all kinds of simple to complicated associations between them and stuff. Looks like WordNet will be very much useful to you.
Here it is in MySQL format. And this one (web-archived link) uses Wordnet v3.0 data, rather than the older Wordnet 2.0 data.
I'd like to add another vote for the StringFormat object. You can use this simply to specify "center, center" and the text will be drawn centrally in the rectangle or points provided:
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
However there is one issue with this in CF. If you use Center for both values then it turns TextWrapping off. No idea why this happens, it appears to be a bug with the CF.
#define interface struct
in some of Optima++ headers (Optima++ is/was a Watcom/Powersoft IDE I had to work with).
Try this:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
e.g @:
Either call cancel()
on the Timer
if that's all it's doing, or cancel()
on the TimerTask
if the timer itself has other tasks which you wish to continue.
In Laravel 5.7, put your CSS or JS file into Public directory.
For CSS:
<link rel="stylesheet" href="{{ asset('bootstrap.min.css') }}">
For JS:
<script type="text/javascript" src="{{ asset('bootstrap.js') }}"></script>
You could make a JavaScript method to check to see if the Enter key was hit, and if it is, to stop the submit.
<script type="text/javascript">
function noenter() {
return !(window.event && window.event.keyCode == 13); }
</script>
Just call that on the submit method.
What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping
instead of dict
as per the ABC PEP.
def value_list(x):
if isinstance(x, dict):
return list(set(x.values()))
elif isinstance(x, basestring):
return [x]
else:
return None
I have similar trouble in test config, because of using AOP. I added this line of code in spring-config.xml
<aop:config proxy-target-class="true"/>
And it works !
I think the issue with the deployment descriptor and dependencies that you are using.
I was having the same issue that I resolved by doing these things. Update your POM.XML
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
Also, add this code inside your build tag under the POM.XML only Since Container needs to know that where is your resource file configured.
<build>
<finalName>HatchWaysAppAPI</finalName>
<sourceDirectory>src/main/resources</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Change your resource folder according to your requirement.
Your Web.xml should be like this.
<servlet>
<servlet-name>HatchWaysAppAPI Maven Webapp</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.hatchwaysapi.mainController</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HatchWaysAppAPI Maven Webapp</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
Note This configuration only for the maven if you not using maven than ignore Pom.XML just do config of the Web.xml.
Key elements of a zero-downtime migration is:
CONFIG SET slave-read-only no
)In short:
Additionally redis have options which allows to disable a source redis to accept writes right after detaching a target:
min-slaves-to-write
min-slaves-max-lag
This topic covered by
Very good explanation from RedisLabs team https://redislabs.com/blog/real-time-synchronization-tool-for-redis-migration (use web.archive.org)
And even their interactive tool for migrate: https://github.com/RedisLabs/redis-migrate
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
Both remove() and insert() have a runtime efficiency of O(n) for both ArrayLists and LinkedLists. However the reason behind the linear processing time comes from two very different reasons:
In an ArrayList you get to the element in O(1), but actually removing or inserting something makes it O(n) because all the following elements need to be changed.
In a LinkedList it takes O(n) to actually get to the desired element, because we have to start at the very beginning until we reach the desired index. Removing or inserting is constant once we get there, because we only have to change 1 reference for remove() and 2 references for insert().
Which of the two is faster for inserting and removing depends on where it happens. If we are closer to the beginning the LinkedList will be faster, because we have to go through relatively few elements. If we are closer to the end an ArrayList will be faster, because we get there in constant time and only have to change the few remaining elements that follow it.
Bonus: While there is no way of making these two methods O(1) for an ArrayList, there actually is a way to do this in LinkedLists. Lets say we want to go through the entire List removing and inserting elements on our way. Usually you would start from the very beginning for each elements using the LinkedList, we could also "save" the current element we're working on with an Iterator. With the help of the Iterator we get a O(1) efficiency for remove() and insert() when working in a LinkedList. Making it the only performance benefit I'm aware of where a LinkedList is always better than an ArrayList.
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
how to retrieve keystore password
You cannot retrieve the password. If you forgot it, you are doomed.
how to retrieve key alias
$ keytool -list -v -keystore <store>
But you need keystore password for this first.
EDIT
What I don't remember is the 'Key Password'
No password can be restored. If you forgot key password for good then you are doomed too and there's no other way than trying harder to recall it. There's no password reset thing nor anything like that.
Be aware that if you forgot your password for good then you will issue no further updates to your app (docs):
Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.
You could load the external page with jquery:
<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script> <div id="testLoad"></div> //would this help
A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.
You denote that fact by appending the "= 0" to the declaration, like this:
class AbstractBase
{
virtual void PureVirtualFunction() = 0;
}
Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:
class Derived : public AbstractBase
{
virtual void PureVirtualFunction() override { }
}
By adding the override
keyword, the compiler will ensure that there is a base class virtual function with the same signature.
This is as close as I can get to the natural feel of Python's "in" operator. You have to define your own type. Then you can extend the functionality of that type by adding a method like "has" which behaves like you'd hope.
package main
import "fmt"
type StrSlice []string
func (list StrSlice) Has(a string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func main() {
var testList = StrSlice{"The", "big", "dog", "has", "fleas"}
if testList.Has("dog") {
fmt.Println("Yay!")
}
}
I have a utility library where I define a few common things like this for several types of slices, like those containing integers or my own other structs.
Yes, it runs in linear time, but that's not the point. The point is to ask and learn what common language constructs Go has and doesn't have. It's a good exercise. Whether this answer is silly or useful is up to the reader.
You can put this in your .h file for your class and define it as property, in XCode 7:
@property int (*stuffILike) [10];
I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:
sudo npm install -g bower
If you have control over the server, I would strongly recommend resizing the images server side with ImageMagik. Downloading large images and resizing them on the phone is a waste of many precious resources - bandwidth, battery and memory. All of which are scarce on phones.
You can also use Index.set_names
as follows:
In [25]: x = pd.DataFrame({'year':[1,1,1,1,2,2,2,2],
....: 'country':['A','A','B','B','A','A','B','B'],
....: 'prod':[1,2,1,2,1,2,1,2],
....: 'val':[10,20,15,25,20,30,25,35]})
In [26]: x = x.set_index(['year','country','prod']).squeeze()
In [27]: x
Out[27]:
year country prod
1 A 1 10
2 20
B 1 15
2 25
2 A 1 20
2 30
B 1 25
2 35
Name: val, dtype: int64
In [28]: x.index = x.index.set_names('foo', level=1)
In [29]: x
Out[29]:
year foo prod
1 A 1 10
2 20
B 1 15
2 25
2 A 1 20
2 30
B 1 25
2 35
Name: val, dtype: int64
cdate(Format([Datum im Format DDMMYYYY],'##/##/####') )
converts string without punctuation characters into date
Try this:
$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Like that:
$ command >>output 2>>error
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
return word
def anotherFunction():
for letter in word:
print("_",end=" ")
svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt
There are several methods.
If you want just the consolidated string value returned, this is a good quick and easy approach
DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
AND ISSUE = 19602
SELECT @combinedString as StringValue
Which will return your combined string.
You can also try one of the XML methods e.g.
SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ','
FROM jira.customfieldvalue v2
WHERE v2.Customfield = v1.Customfield
AND v2.Issue = v1.issue
ORDER BY ID
FOR XML PATH('') ) D ( StringValues )
WHERE customfield = 12534
AND ISSUE = 19602
Many solutions have been provided, but I have not seen this one, which uses package chron:
hours = times(strftime(times, format="%T"))
plot(val~hours)
(sorry, I am not entitled to post an image, you'll have to plot it yourself)
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.
In properties:
security:
datasource:
jdbcUrl: jdbc:mysql://ip:3306/security
username: user
password: pass
In java:
@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){
return DataSourceBuilder
.create()
.build();
}
Sorry, didn't quite get your question. So something like this?
str.ToCharArray().Any(char.IsDigit);
Or does the value have to be an integer completely, without any additional strings?
if(str.ToCharArray().All(char.IsDigit(c));
For me I had to uninstall "Citrix Virtual Desktop Agent" on my VM
This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.
It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):
Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.
You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.
The chrome developers also do change this periodically. They changed it recently from badidea
to thisisunsafe
so everyone using badidea
, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:
Rotate the interstitial bypass keyword
The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.
I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.
If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN
field in certificates now so if just using the old subject
field then even adding it to the certificate store will not result in a green padlock.
If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.
HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.
Make the extensions you want one string i.e ".mp3.jpg.wma.wmf" and then check if each file contains the extension you want. This works with .net 2.0 as it does not use LINQ.
string myExtensions=".jpg.mp3";
string[] files=System.IO.Directory.GetFiles("C:\myfolder");
foreach(string file in files)
{
if(myExtensions.ToLower().contains(System.IO.Path.GetExtension(s).ToLower()))
{
//this file has passed, do something with this file
}
}
The advantage with this approach is you can add or remove extensions without editing the code i.e to add png images, just write myExtensions=".jpg.mp3.png".
Use ViewCompat.setBackground(view, background);
On Windows 7, with Samsung Nexus S, it showed nothing in Device Manager, the adb devices
command showed no devices, but when plugged in device said USB debugging was on and connected.
I used Andrea's Feb 2 answer to install the Google USB driver, which created the /gooogle/usb_driver directory and used RobertNovelo's Mar 7 answer to go to the link and follow the instructions. The device showed up in Device Manager under 'other'. I right clicked on it and selected update driver, and now it shows up in Device Manager under 'Android device', and now command line adb devices
lists it.
weights.reshape(a, b)
will return a new tensor with the same data as weights with size (a, b) as in it copies the data to another part of memory.
weights.resize_(a, b)
returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory.
weights.view(a, b)
will return a new tensor with the same data as weights with size (a, b)
One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...
@HostBinding('attr.something')
get something() {
return this.somethingElse;
}
It works, because it is a get
accessor. You couldn't use a function equivalent:
@HostBinding('attr.something')
something() {
return this.somethingElse;
}
Otherwise, the benefit of using @HostBinding
is it assures change detection is run when the bound value changes.
String methodName= "...";
String[] args = {};
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
// for static methods we can use null as instance of class
m.invoke(null, new Object[] {args});
break;
}
}
[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]
will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)
ADD: Here is an alternate syntax that achieves the same thing without the cast.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];
here is the solution that I decided to use.
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
string name = certificate.Subject;
DateTime expirationDate = DateTime.Parse(certificate.GetExpirationDateString());
if (sslPolicyErrors == SslPolicyErrors.None || (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch && name.EndsWith(".acceptabledomain.com") && expirationDate > DateTime.Now))
{
return true;
}
return false;
};
As long as volumes are associated with a container(either running or not), they cannot be removed.
You have to run
docker inspect <container-id>/<container-name>
on each of the running/non-running containers where this volume might have been mounted onto.
If the volume is mounted onto any one of the containers, you should see it in the Mounts section of the inspect command output. Something like this :-
"Mounts": [
{
"Type": "volume",
"Name": "user1",
"Source": "/var/lib/docker/volumes/user1/_data",
"Destination": "/opt",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
After figuring out the responsible container(s), use :-
docker rm -f container-1 container-2 ...container-n
in case of running containers
docker rm container-1 container-2 ...container-n
in case of non-running containers
to completely remove the containers from the host machine.
Then try removing the volume using the command :-
docker volume remove <volume-name/volume-id>
For those that are following the example on this GoogleMaps - MapWithMarker project, you may remove the marker by doing so
override fun onMapReady(googleMap: GoogleMap?) {
googleMap?.apply {
// Remove marker
clear()
val sydney = LatLng(-33.852, 151.211)
addMarker(
MarkerOptions()
.position(sydney)
.title("Marker in Sydney")
)
moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
String y = "hello";
would work (note the double quotes).
char y = 'h'; this will work for chars (note the single quotes)
but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.
You change the bundle display name in the info.plist. It's as simple as that.
Changing the 'bundle display name' (as opposed to 'bundle name') is the only way to include characters like '+' in your applications name. Including special characters in the project name will cause an error when uploading to the app store!
i suggest PDFMerger from github.com, so easy like ::
include 'PDFMerger.php';
$pdf = new PDFMerger;
$pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')
->addPDF('samplepdfs/two.pdf', '1-2')
->addPDF('samplepdfs/three.pdf', 'all')
->merge('file', 'samplepdfs/TEST2.pdf'); // REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options
Just to add the information I was looking for: pragma mark
is Xcode specific, so if you deal with a C++ project that you open in different IDEs, it does not have any effect there. In Qt Creator, for example, it does not add categories for methods, nor generate any warnings/errors.
EDIT
#pragma
is a preprocessor directive which comes from C programming language. Its purpose is to specify implementation-dependent information to the compiler - that is, each compiler might choose to interpret this directive as it wants. That said, it is rather considered an extension which does not change/influence the code itself. So compilers might as well ignore it.
Xcode is an IDE which takes advantage of #pragma
and uses it in its own specific way. The point is, #pragma
is not Xcode and even Objective-C specific.
Just complementing what Donal Fellows said, you can use List with @RequestParam
public String controllerMethod(@RequestParam(value="myParam") List<ObjectToParse> myParam){
....
}
Hope it helps!
Make sure branch "master" exists! It's not just a name apparently.
I got this error after creating a blank bare repo, pushing a branch named "dev" to it, and trying to use git log in the bare repo. Interestingly, git branch knows that dev is the only branch existing (so I think this is a git bug).
Solution: I repeated the procedure, this time having renamed "dev" to "master" on the working repo before pushing to the bare repo. Success!
In Java 8 we have multiple ways to iterate over collection classes.
The collections that implement Iterable
(for example all lists) now have forEach
method. We can use method-reference introduced in Java 8.
Arrays.asList(1,2,3,4).forEach(System.out::println);
We can also iterate over a list using Stream as:
Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
Arrays.asList(1,2,3,4).stream().forEachOrdered(System.out::println);
We should prefer forEachOrdered
over forEach
because the behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept.
The advantage with streams is that we can also make use of parallel streams wherever appropriate. If the objective is only to print the items irrespective of the order then we can use parallel stream as:
Arrays.asList(1,2,3,4).parallelStream().forEach(System.out::println);
In Python you might be in for some surprises if you ask for forgiveness in this case.
try-except is not the right paradigm here.
If you accidentally get negative indices your in for a surprise.
Better solution is to provide the test function yourself:
def index_in_array(M, index):
return index[0] >= 0 and index[1] >= 0 and index[0]< M.shape[0] and index[1] < M.shape[1]
It is possible for the TCP socket to be "closing" and your code to not have yet been notified.
Here is a animation for the life cycle. http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle
Basically, the connection was closed by the client. You already have throws IOException
and SocketException
extends IOException
. This is working just fine. You just need to properly handle IOException
because it is a normal part of the api.
EDIT: The RST
packet occurs when a packet is received on a socket which does not exist or was closed. There is no difference to your application. Depending on the implementation the reset
state may stick and closed
will never officially occur.
Try using type
:
type foobar
For example:
$ type ls
ls is aliased to `ls --color=auto'
$ type foobar
-bash: type: foobar: not found
This is preferable to which
for a few reasons:
The default which
implementations only support the -a
option that shows all options, so you have to find an alternative version to support aliases
type
will tell you exactly what you are looking at (be it a Bash function or an alias or a proper binary).
type
doesn't require a subprocess
type
cannot be masked by a binary (for example, on a Linux box, if you create a program called which
which appears in path before the real which
, things hit the fan. type
, on the other hand, is a shell built-in (yes, a subordinate inadvertently did this once).
this.setState({ abc.xyz: 'new value' });
syntax is not allowed.
You have to pass the whole object.
this.setState({abc: {xyz: 'new value'}});
If you have other variables in abc
var abc = this.state.abc;
abc.xyz = 'new value';
this.setState({abc: abc});
You can have ordinary variables, if they don't rely on this.props and this.state
.
Do this:
function changeHeight() { document.getElementById('chartdiv').style.height = "200px" } <button type="button" onClick="changeHeight();"> Click Me!</button>
Dim result2 = From s In mySession.Query(Of CSucursal)()
Where (From c In mySession.Query(Of CCiudad)()
From cs In mySession.Query(Of CCiudadSucursal)()
Where cs.id_ciudad Is c
Where cs.id_sucursal Is s
Where c.id = IdCiudad
Where s.accion <> "E" AndAlso s.accion <> Nothing
Where cs.accion <> "E" AndAlso cs.accion <> Nothing
Select c.descripcion).Single() Is Nothing
Where s.accion <> "E" AndAlso s.accion <> Nothing
Select s.id, s.Descripcion
The solution I chose is similar to Daniel's, but rather than use an object factory and override the toString, I explicitly add the hash to the object when it is first requested through a getHashCode function. A little messy, but better for my needs :)
Function.prototype.getHashCode = (function(id) {
return function() {
if (!this.hashCode) {
this.hashCode = '<hash|#' + (id++) + '>';
}
return this.hashCode;
}
}(0));
A demonstration of lazy
- as defined above - execution when defined vs execution when accessed: (using 2.12.7 scala shell)
// compiler says this is ok when it is lazy
scala> lazy val t: Int = t
t: Int = <lazy>
//however when executed, t recursively calls itself, and causes a StackOverflowError
scala> t
java.lang.StackOverflowError
...
// when the t is initialized to itself un-lazily, the compiler warns you of the recursive call
scala> val t: Int = t
<console>:12: warning: value t does nothing other than call itself recursively
val t: Int = t
Try this
<input type="text" style="font-size:18pt;height:420px;width:200px;">
Or else
<input type="text" id="txtbox">
with the css:
#txtbox
{
font-size:18pt;
height:420px;
width:200px;
}
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.
For MVC5, in case you are building an application from scratch. You need to add a web.config file to the Views folder and paste the following code in it.
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
Note that for MVC 3 you will have to change version to 3.0.0.0 at
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
You may have to close and open the *.cshtml page again to see the changes.
Another option is to use showtext
package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.
# install.packages('showtext', dependencies = TRUE)
library(showtext)
Import some Google Fonts
# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")
Load font from the current search path into showtext
# Check the current search path for fonts
font_paths()
#> [1] "C:\\Windows\\Fonts"
# List available font files in the search path
font_files()
#> [1] "AcadEref.ttf"
#> [2] "AGENCYB.TTF"
#> [428] "pala.ttf"
#> [429] "palab.ttf"
#> [430] "palabi.ttf"
#> [431] "palai.ttf"
# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")
font_families()
#> [1] "sans" "serif" "mono" "wqy-microhei"
#> [5] "Montserrat" "Roboto" "Palatino"
## automatically use showtext for new devices
showtext_auto()
Plot: need to open Windows graphics device as showtext
does not work well with RStudio built-in graphics device
# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()
myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"
library(ggplot2)
a <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text = element_text(size = 16, family = myFont1)) +
annotate("text", 4, 30, label = 'Palatino Linotype',
family = myFont3, size = 10) +
annotate("text", 1, 11, label = 'Roboto', hjust = 0,
family = myFont2, size = 10)
## On-screen device
print(a)
## Save to PNG
ggsave("plot_showtext.png", plot = a,
type = 'cairo',
width = 6, height = 6, dpi = 150)
## Save to PDF
ggsave("plot_showtext.pdf", plot = a,
device = cairo_pdf,
width = 6, height = 6, dpi = 150)
## turn showtext off if no longer needed
showtext_auto(FALSE)
Edit: another workaround to use showtext
in RStudio. Run the following code at the beginning of the R session (source)
trace(grDevices::png, exit = quote({
showtext::showtext_begin()
}), print = FALSE)
option: custom detector class
abstract public class
Long_hold
extends View.OnTouchListener
{
public@Override boolean
onTouch(View view, MotionEvent touch)
{
switch(touch.getAction())
{
case ACTION_DOWN: down(touch); return true;
case ACTION_MOVE: move(touch);
}
return true;
}
private long
time_0;
private float
x_0, y_0;
private void
down(MotionEvent touch)
{
time_0= touch.getEventTime();
x_0= touch.getX();
y_0= touch.getY();
}
private void
move(MotionEvent touch)
{
if(held_too_short(touch) {return;}
if(moved_too_much(touch)) {return;}
long_press(touch);
}
abstract protected void
long_hold(MotionEvent touch);
}
use
private double
moved_too_much(MotionEvent touch)
{
return Math.hypot(
x_0 -touch.getX(),
y_0 -touch.getY()) >TOLERANCE;
}
private double
held_too_short(MotionEvent touch)
{
return touch.getEventTime()-time_0 <DOWN_PERIOD;
}
where
TOLERANCE
is the maximum tolerated movement
DOWN_PERIOD
is the time one has to press
import
static android.view.MotionEvent.ACTION_MOVE;
static android.view.MotionEvent.ACTION_DOWN;
in code
setOnTouchListener(new Long_hold()
{
protected@Override boolean
long_hold(MotionEvent touch)
{
/*your code on long hold*/
}
});
Short Form: If your main is within a jar, you'll probably need an additional '-jar pathTo/yourJar/YourJarsName.jar ' explicitly declared to get it working (even though 'YourJarsName.jar' was on the classpath) (or, expressed to answer the original question that was asked 5 years ago: you don't need to redeclare each jar explicitly, but does seem, even with java6 you need to redeclare your own jar ...)
Long Form: (I've made this explicit to the point that I hope even interlopers to java can make use of this)
Like many here I'm using eclipse to export jars: (File->Export-->'Runnable JAR File'). There are three options on 'Library handling' eclipse (Juno) offers:
opt1: "Extract required libraries into generated JAR"
opt2: "Package required libraries into generated JAR"
opt3: "Copy required libraries into a sub-folder next to the generated JAR"
Typically I'd use opt2 (and opt1 was definitely breaking), however native code in one of the jars I'm using I discovered breaks with the handy "jarinjar" trick that eclipse leverages when you choose that option. Even after realizing I needed opt3, and then finding this StackOverflow entry, it still took me some time to figure it out how to launch my main outside of eclipse, so here's what worked for me, as it's useful for others...
If you named your jar: "fooBarTheJarFile.jar" and all is set to export to the dir: "/theFully/qualifiedPath/toYourChosenDir".
(meaning the 'Export destination' field will read: '/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar' )
After you hit finish, you'll find eclipse then puts all the libraries into a folder named 'fooBarTheJarFile_lib' within that export directory, giving you something like:
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar01.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar02.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar03.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar04.jar
You can then launch from anywhere on your system with:
java -classpath "/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*" -jar /theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain
(For Java Newbies: 'package.path_to.the_class_with.your_main' is the declared package-path that you'll find at the top of the 'TheClassWithYourMain.java' file that contains the 'main(String[] args){...}' that you wish to run from outside java)
The pitfall to notice: is that having 'fooBarTheJarFile.jar' within the list of jars on your declared classpath is not enough. You need to explicitly declare '-jar', and redeclare the location of that jar.
e.g. this breaks:
java -classpath "/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar;/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*" somepackages.inside.yourJar.leadingToTheMain.TheClassWithYourMain
restated with relative paths:
cd /theFully/qualifiedPath/toYourChosenDir/;
BREAKS: java -cp "fooBarTheJarFile_lib/*" package.path_to.the_class_with.your_main.TheClassWithYourMain
BREAKS: java -cp ".;fooBarTheJarFile_lib/*" package.path_to.the_class_with.your_main.TheClassWithYourMain
BREAKS: java -cp ".;fooBarTheJarFile_lib/*" -jar package.path_to.the_class_with.your_main.TheClassWithYourMain
WORKS: java -cp ".;fooBarTheJarFile_lib/*" -jar fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain
(using java version "1.6.0_27"; via OpenJDK 64-Bit Server VM on ubuntu 12.04)
<form>
syn<input type="checkbox" name="checkfield" id="g01-01" />
</form>
js:
$('#g01-01').on('change',function(){
var _val = $(this).is(':checked') ? 'checked' : 'unchecked';
alert(_val);
});
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
In one statement: No.
In one transaction: Yes
BEGIN TRANSACTION
DECLARE @DataID int;
INSERT INTO DataTable (Column1 ...) VALUES (....);
SELECT @DataID = scope_identity();
INSERT INTO LinkTable VALUES (@ObjectID, @DataID);
COMMIT
The good news is that the above code is also guaranteed to be atomic, and can be sent to the server from a client application with one sql string in a single function call as if it were one statement. You could also apply a trigger to one table to get the effect of a single insert. However, it's ultimately still two statements and you probably don't want to run the trigger for every insert.
For Windows users: curly braces have special meaning in PowerShell. You can either surround with single quotes or escape with backtick. For example:
git checkout 'stash@{0}' YourFile
Without it, you may receive an error:
Unknown switch 'e'
ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 input.mp4
N/A
. See the other methods listed below.ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 input.mkv
-skip_frame nokey
option to only count key frames.If you do not have ffprobe
you can use ffmpeg
instead:
ffmpeg -i input.mkv -map 0:v:0 -c copy -f null -
frame=
near the end of the console output.-discard nokey
input option (before -i
) to only count key frames.Ignore the MP4/M4V/M4A/MOV edit list with the -ignore_editlist 1
input option. Default is to not ignore the edit list.
-v error
This hides "info" output (version info, etc) which makes parsing easier.
-count_frames
Count the number of frames per stream and report it in the corresponding stream section.
-select_streams v:0
Select only the video stream.
-show_entries stream=nb_frames
or -show_entries stream=nb_read_frames
Show only the entry for nb_frames
or nb_read_frames
.
-of default=nokey=1:noprint_wrappers=1
Set output format (aka the "writer") to default
, do not print the key of each field (nokey=1
), and do not print the section header and footer (noprint_wrappers=1
). There are shorter alternatives such as -of csv=p=0
.
The well known mediainfo
tool can output the number of frames:
mediainfo --Output="Video;%FrameCount%" input.avi
For MP4/M4V/M4A files.
MP4Box
from gpac can show the number of frames:
MP4Box -info input.mp4
Refer to the Media Info
line in the output for the video stream in question:
Media Info: Language "Undetermined (und)" - Type "vide:avc1" - 2525 samples
In this example the video stream has 2525 frames.
For MP4/M4V/M4A/MOV files.
boxdumper
is a simple tool from l-smash. It will output a large amount of information. Under the stsz
sample size box section refer to sample_count
for the number of frames. In this example the input has 1900 video frames:
boxdumper input.mp4
...
[stsz: Sample Size Box]
position = 342641
size = 7620
version = 0
flags = 0x000000
sample_size = 0 (variable)
sample_count = 1900
stsz
atom.With lodash/fp you can create a function with _.flow()
that 1st groups by a key, and then map each group, and omits a key from each item:
const { flow, groupBy, mapValues, map, omit } = _;_x000D_
_x000D_
const groupAndOmitBy = key => flow(_x000D_
groupBy(key),_x000D_
mapValues(map(omit(key)))_x000D_
);_x000D_
_x000D_
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
const groupAndOmitMake = groupAndOmitBy('make');_x000D_
_x000D_
const result = groupAndOmitMake(cars);_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
_x000D_
For me none of the solution worked, but If i disconnect the phone from laptop and then run the build, it succeeds and then I connect and run on the phone. I still couldn't figure out the final fix.
The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:
var len = menuitems.length;
for (var i = 0; i < len; i++){
(function(i) {
$('<li/>',{
'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
'click':function(){
menuitems[i].action();
},
'class':o.itemClass
}).appendTo('.'+o.listClass);
})(i);
}
In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.
If you use addToBackStack()
, you can use following code.
List<Fragment> fragments = fragmentManager.getFragments();
activeFragment = fragments.get(fragments.size() - 1);
You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This is because it's the parent of the View that needs to know what size to allocate to the View.
Not sure if that's exactly what you need, but we are using profiles to define the environment we are running at and specific bean for each environment, so it's something like that:
<bean name="myBean" class="myClass">
<constructor-arg name="name" value="originalValue" />
</bean>
<beans profile="DEV, default">
<!-- Specific DEV configurations, also default if no profile defined -->
<bean name="myBean" class="myClass">
<constructor-arg name="name" value="overrideValue" />
</bean>
</beans>
<beans profile="CI, UAT">
<!-- Specific CI / UAT configurations -->
</beans>
<beans profile="PROD">
<!-- Specific PROD configurations -->
</beans>
So in this case, if I don't define a profile or if I define it as "DEV" myBean will get "overrideValue" for it's name argument. But if I set the profile to "CI", "UAT" or "PROD" it will get "originalValue" as the value.
A formula for an angle from 0 to 2pi.
There is x=x2-x1 and y=y2-y1.The formula is working for
any value of x and y. For x=y=0 the result is undefined.
f(x,y)=pi()-pi()/2*(1+sign(x))*(1-sign(y^2))
-pi()/4*(2+sign(x))*sign(y)
-sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))
Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)
select state, count(*) from pg_stat_activity where pid <> pg_backend_pid() group by 1 order by 1;
class Foo {
public:
Foo(int a) {
}
}
int func() {
int a1, a2;
std::cin >> a1;
std::cin >> a2;
Foo f1(a1);
__asm push a1;
__asm lea ecx, [this];
__asm call Foo::Foo(int);
Foo* f2 = new Foo(a2);
__asm push sizeof(Foo);
__asm call operator new;//there's a lot instruction here(depends on system)
__asm push a2;
__asm call Foo::Foo(int);
delete f2;
}
It would be like this in asm. When you're in func
, the f1
and pointer f2
has been allocated on stack (automated storage). And by the way, Foo f1(a1)
has no instruction effects on stack pointer (esp
),It has been allocated, if func
wants get the member f1
, it's instruction is something like this: lea ecx [ebp+f1], call Foo::SomeFunc()
. Another thing the stack allocate may make someone think the memory is something like FIFO
, the FIFO
just happened when you go into some function, if you are in the function and allocate something like int i = 0
, there no push happened.
I prefer to suppress an exception rather than checking for the file's existence, to avoid a TOCTTOU bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress()
:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
If filename
is a pathlib.Path
object instead of a string, we can call its .unlink()
method instead of using os.remove()
. In my experience, Path objects are more useful than strings for filesystem manipulation.
Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
Container splitR(const std::string& input, const std::string& delims) {
Container out;
size_t delims_len = delims.size();
auto begIdx = 0;
auto endIdx = input.find(delims, begIdx);
if (endIdx == std::string::npos && input.size() != 0) {
insert_in_container(out, input);
}
while (endIdx != std::string::npos) {
insert_in_container(out, input.substr(begIdx, endIdx - begIdx));
begIdx = endIdx + delims_len;
endIdx = input.find(delims, begIdx);
if (endIdx == std::string::npos) {
insert_in_container(out, input.substr(begIdx, input.length() - begIdx));
}
}
return out;
}
You can also try using apply
with get
method of dictionary
, seems to be little faster than replace
:
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Testing with timeit
:
%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)
Result:
The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop
Using apply
:
%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Result:
The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop
Note: apply
with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.
They are project files, that hold the module information and meta data.
Just add *.iml
to .gitignore
.
In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml
files will be generated.
You can use a serial combination of git rebase
and git branch
to apply a group of commits onto another branch. As already posted by wolfc the first command actually copies the commits. However, the change is not visible until you add a branch name to the top most commit of the group.
Please open the picture in a new tab ...
To summarize the commands in text form:
gitk --all &
.git rebase --onto a b f
.HEAD
is marked.git branch selection
This should clarify things:
a
is the new root destination of the group.b
is the commit before the first commit of the group (exclusive).f
is the last commit of the group (inclusive).Afterwards, you could use git checkout feature && git reset --hard b
to delete the commits c
till f
from the feature
branch.
In addition to this answer, I wrote a blog post which describes the commands in another scenario which should help to generally use it.
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
label
and checkbox
inputKeeps the selected item opened and togglable.
.collapse{_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
label
and named radio
inputSimilar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio"
on both inputs.
.collapse{_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
tabindex
and :focus
Similar to radio
inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.
.collapse > a{_x000D_
background: #cdf;_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
<a>Collapse 1</a>_x000D_
<div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
<a>Collapse 2</a>_x000D_
<div>Content 2....</div>_x000D_
</div>
_x000D_
:target
Similar to using radio
input, you can additionally use Tab and ⏎ keys to operate
.collapse a{_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
<a href="#targ_1">Collapse 1</a>_x000D_
<div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
<a href="#targ_2">Collapse 2</a>_x000D_
<div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
<detail>
and <summary>
tags (pure HTML)You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.
<details>_x000D_
<summary>Collapse 1</summary>_x000D_
<p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
<summary>Collapse 2</summary>_x000D_
<p>Content 2...</p>_x000D_
</details>
_x000D_
From the documentation of SimpleDateFormat:
Letter Date or Time Component Presentation Examples
S Millisecond Number 978
So it is milliseconds, or 1/1000th of a second. You just format it with on 6 digits, so you add 3 extra leading zeroes...
You can check it this way:
Date d =new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(d));
Output:
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.0132
2013-10-07 12:13:27.00132
2013-10-07 12:13:27.000132
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
Another solution but without using ng-click which still works even for other tags than <a>
:
<tr [routerLink]="['/about']">
This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494
(This is my first day with angular. Gentle feedback is welcome)
<div ng-hide="myvar == null"></div>
or
<div ng-show="myvar != null"></div>
I'm pretty sure it's similar to Laravel template, this is how I did mine.
<link rel="stylesheet" href="/folder/stylesheets/stylesheet.css" />
Referred: CSS file pathing problem
Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates
consider example of list
List<Program> blabla= new List<Program>();
blabla.Add(new Program("shubham", 1));
blabla.Add(new Program("google", 3));
blabla.Add(new Program("world",5));
blabla.Add(new Program("hello", 5));
blabla.Add(new Program("bye", 2));
contains names and ages. Now say we want to find names on condition So I Will use,
Predicate<Program> test = delegate (Program p) { return p.age > 3; };
List<Program> matches = blabla.FindAll(test);
Action<Program> print = Console.WriteLine;
matches.ForEach(print);
tried to Keep it Simple!
These two terms differentiate between two different ways of walking a tree.
It is probably easiest just to exhibit the difference. Consider the tree:
A
/ \
B C
/ / \
D E F
A depth first traversal would visit the nodes in this order
A, B, D, C, E, F
Notice that you go all the way down one leg before moving on.
A breadth first traversal would visit the node in this order
A, B, C, D, E, F
Here we work all the way across each level before going down.
(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)
Both kinds of traversal can be achieved with the pseudocode:
Store the root node in Container
While (there are nodes in Container)
N = Get the "next" node from Container
Store all the children of N in Container
Do some work on N
The difference between the two traversal orders lies in the choice of Container
.
The recursive implementation looks like
ProcessNode(Node)
Work on the payload Node
Foreach child of Node
ProcessNode(child)
/* Alternate time to work on the payload Node (see below) */
The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.
At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:
D, B, E, F, C, A
which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.
This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Try this. It's C# code.
They are already in arrays: $name
is an array, as is $email
So all you need to do is add a bit of processing to attack both arrays:
$name = $_POST['name'];
$email = $_POST['account'];
foreach( $name as $key => $n ) {
print "The name is ".$n." and email is ".$email[$key].", thank you\n";
}
To handle more inputs, just extend the pattern:
$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];
foreach( $name as $key => $n ) {
print "The name is ".$n.", email is ".$email[$key].
", and location is ".$location[$key].". Thank you\n";
}
Other than the builtin developer tools, there is none that i know of. You might, however, be able to use Firebug Lite.
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)
I have a java.util.Date in the format yyyy-mm-dd
As other mentioned, the Date
class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.
The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.
If you have a java.util.Date
, convert to a Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
Define the time zone by which you want context for your Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Apply the ZoneId
to get a ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( z );
LocalDate
If you only care about the date without a time-of-day, extract a LocalDate
.
LocalDate localDate = zdt.toLocalDate();
To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString
. The java.time classes use the standard formats by default when generating/parsing strings.
String output = localDate.toString();
2017-01-23
If you want a MM-DD-YYYY format, define a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );
Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm
(minute of hour) rather than MM
(month of year).
Use the same DateTimeFormatter
object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.
LocalDate localDate = LocalDate.parse( "01-23-2017" , f );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.