You can use Object.keys functionality to get the keys like:
const tempObjects={foo:"bar"}
Object.keys(tempObjects).forEach(obj=>{
console.log("Key->"+obj+ "value->"+tempObjects[obj]);
});
PAGEIOLATCH_SH
wait type usually comes up as the result of fragmented or unoptimized index.
Often reasons for excessive PAGEIOLATCH_SH
wait type are:
In order to try and resolve having high PAGEIOLATCH_SH
wait type, you can check:
PAGEIOLATCH_SH
wait typesAlways keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH
can be expected.
You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types
You can use win32api
or ctypes
module to use win32 apis for controlling mouse or any gui
Here is a fun example to control mouse using win32api:
import win32api
import time
import math
for i in range(500):
x = int(500+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
A click using ctypes:
import ctypes
# see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 20)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
Here you go:
http://jsfiddle.net/damsarabi/gwAdA/
You cannot use width: 100px, because the display is table-cell. You can however use Max-width: 100px. then your box will never get bigger than 100px. but you need to add overflow:hidden to make sure the contect don't bleed to other cells. you can also add white-space: nowrap if you wish to keep the height from increasing.
SIMPLEST ANSWER
just spread the set inside []
let mySet = new Set()
mySet.add(1)
mySet.add(5)
mySet.add(5)
let arr = [...mySet ]
Result: [1,5]
Looks like the type is boolean and therefore can never be null and should be false by default.
I looked up for packages related to removing outliers, and found this package (surprisingly called "outliers"!): https://cran.r-project.org/web/packages/outliers/outliers.pdf
if you go through it you see different ways of removing outliers and among them I found rm.outlier
most convenient one to use and as it says in the link above:
"If the outlier is detected and confirmed by statistical tests, this function can remove it or replace by
sample mean or median" and also here is the usage part from the same source:
"Usage
rm.outlier(x, fill = FALSE, median = FALSE, opposite = FALSE)
Arguments
x a dataset, most frequently a vector. If argument is a dataframe, then outlier is
removed from each column by sapply. The same behavior is applied by apply
when the matrix is given.
fill If set to TRUE, the median or mean is placed instead of outlier. Otherwise, the
outlier(s) is/are simply removed.
median If set to TRUE, median is used instead of mean in outlier replacement.
opposite if set to TRUE, gives opposite value (if largest value has maximum difference
from the mean, it gives smallest and vice versa)
"
DataSet myDataset = new DataSet();
DataTable customers = myDataset.Tables.Add("Customers");
customers.Columns.Add("Name");
customers.Columns.Add("Age");
customers.Rows.Add("Chris", "25");
//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
currentRow = myCustomers.Rows[i];
listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));
}
Using Git for Windows it is easier to use HTTPS url.
Open a git shell then git clone https://github.com/user/repo
. Enter username and password when prompted. No need to setup a SSH key.
Look into using the includePaths parameter...
"The SASS compiler uses each path in loadPaths when resolving SASS @imports."
In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.
In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).
As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.
Here's my one-liner solution:
screen -S internet-check -d -m -- bash -c 'while ! ping -c 1 google.com; do echo -; done; echo Google responding to ping | mail -s internet-back [email protected]'
This runs an infinite ping in a new screen session until there is a response, at which point it sends an e-mail to [email protected]
. Useful in the age of e-mail sent to phones.
(You might want to check that mail
is configured correctly by just running echo test | mail -s test [email protected]
first. Of course you can do whatever you want from done;
onwards, sound a bell, start a web browser, use your imagination.)
If we want to assign a scaler value eg: 10 to all rows of a new column in a df:
df = df.assign(new_col=lambda x:10) # x is each row passed in to the lambda func
df will now have new column 'new_col' with value=10 in all rows.
Best aproach for me was:
private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int X = 1;
foreach(DataGridViewRow row in grid_receptie.Rows)
{
row.Cells["NR_CRT"].Value = X;
X++;
}
}
After trying out ngGrid, ngTable, trNgGrid and Smart Table, I have come to the conclusion that Smart Table is by far the best implementation AngularJS-wise and Bootstrap-wise. It is built exactly the same way as you would build your own, naive table using standard angular. On top of that, they have added a few directives that help you do sorting, filtering etc. Their approach also makes it quite simple to extend yourself. The fact that they use the regular html tags for tables and the standard ng-repeat for the rows and standard bootstrap for formatting makes this my clear winner.
Their JS code depends on angular and your html can depend on bootstrap if you want to. The JS code is 4 kb in total and you can even easily pick stuff out of there if you want to reach an even smaller footprint.
Where the other grids will give you claustrophobia in different areas, Smart Table just feels open and to the point.
If you rely heavily on inline editing and other advanced features, you might get up and running quicker with ngTable for instance. However, you are free to add such features quite easily in Smart Table.
Don't miss Smart Table!!!
I have no relation to Smart Table, except from using it myself.
Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__
you can do simplify things a bit.
Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.
from __future__ import division
def Pythag(league):
def win_percentages():
for team, (runs_scored, runs_allowed) in league.iteritems():
win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
yield win_percentage
for win_percentage in win_percentages():
print win_percentage
Apart from what Andy mentioned, there is another difference which could be important - write-host directly writes to the host and return nothing, meaning that you can't redirect the output, e.g., to a file.
---- script a.ps1 ----
write-host "hello"
Now run in PowerShell:
PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>
As seen, you can't redirect them into a file. This maybe surprising for someone who are not careful.
But if switched to use write-output instead, you'll get redirection working as expected.
If you using ajax to load modal's body such way and want to be able to reload it's content
<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- Content will be loaded here -->
</div>
</div>
</div>
use
<script>
$(function() {
$('.modal').on('hidden.bs.modal', function(){
$(this).removeData('bs.modal');
});
});
</script>
private void RunAsync()
{
string param = "Hi";
Task.Run(() => MethodWithParameter(param));
}
private void MethodWithParameter(string param)
{
//Do stuff
}
Edit
Due to popular demand I must note that the Task
launched will run in parallel with the calling thread. Assuming the default TaskScheduler
this will use the .NET ThreadPool
. Anyways, this means you need to account for whatever parameter(s) being passed to the Task
as potentially being accessed by multiple threads at once, making them shared state. This includes accessing them on the calling thread.
In my above code that case is made entirely moot. Strings are immutable. That's why I used them as an example. But say you're not using a String
...
One solution is to use async
and await
. This, by default, will capture the SynchronizationContext
of the calling thread and will create a continuation for the rest of the method after the call to await
and attach it to the created Task
. If this method is running on the WinForms GUI thread it will be of type WindowsFormsSynchronizationContext
.
The continuation will run after being posted back to the captured SynchronizationContext
- again only by default. So you'll be back on the thread you started with after the await
call. You can change this in a variety of ways, notably using ConfigureAwait
. In short, the rest of that method will not continue until after the Task
has completed on another thread. But the calling thread will continue to run in parallel, just not the rest of the method.
This waiting to complete running the rest of the method may or may not be desirable. If nothing in that method later accesses the parameters passed to the Task
you may not want to use await
at all.
Or maybe you use those parameters much later on in the method. No reason to await
immediately as you could continue safely doing work. Remember, you can store the Task
returned in a variable and await
on it later - even in the same method. For instance, once you need to access the passed parameters safely after doing a bunch some other work. Again, you do not need to await
on the Task
right when you run it.
Anyways, a simple way to make this thread-safe with respect to the parameters passed to Task.Run
is to do this:
You must first decorate RunAsync
with async
:
private async void RunAsync()
Important Note
Preferably the method marked async
should not return void, as the linked documentation mentions. The common exception to this is event handlers such as button clicks and such. They must return void. Otherwise I always try to return a Task
or Task<TResult>
when using async
. It's good practice for a quite a few reasons.
Now you can await
running the Task
like below. You cannot use await
without async
.
await Task.Run(() => MethodWithParameter(param));
//Code here and below in the same method will not run until AFTER the above task has completed in one fashion or another
So, in general, if you await
the task you can avoid treating passed in parameters as a potentially shared resource with all the pitfalls of modifying something from multiple threads at once. Also, beware of closures. I won't cover those in depth but the linked article does a great job of it.
Side Note
A bit off topic, but be careful using any type of "blocking" on the WinForms GUI thread due to it being marked with [STAThread]
. Using await
won't block at all, but I do sometimes see it used in conjunction with some sort of blocking.
"Block" is in quotes because you technically cannot block the WinForms GUI thread. Yes, if you use lock
on the WinForms GUI thread it will still pump messages, despite you thinking it's "blocked". It's not.
This can cause bizarre issues in very rare cases. One of the reasons you never want to use a lock
when painting, for example. But that's a fringe and complex case; however I've seen it cause crazy issues. So I noted it for completeness sake.
Hmisc has %nin%
function, which should do this.
https://www.rdocumentation.org/packages/Hmisc/versions/4.4-0/topics/%25nin%25
df['Name']='abc'
will add the new column and set all rows to that value:
In [79]:
df
Out[79]:
Date, Open, High, Low, Close
0 01-01-2015, 565, 600, 400, 450
In [80]:
df['Name'] = 'abc'
df
Out[80]:
Date, Open, High, Low, Close Name
0 01-01-2015, 565, 600, 400, 450 abc
I was struggling with this problem, and I learned (thanks to this post) that:
div:first-child {_x000D_
opacity: .99; _x000D_
}_x000D_
_x000D_
.red, .green, .blue {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
color: white;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.red {_x000D_
z-index: 1;_x000D_
top: 20px;_x000D_
left: 20px;_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.green {_x000D_
top: 60px;_x000D_
left: 60px;_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.blue {_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
background: blue;_x000D_
}
_x000D_
<div>_x000D_
<span class="red">Red</span>_x000D_
</div>_x000D_
<div>_x000D_
<span class="green">Green</span>_x000D_
</div>_x000D_
<div>_x000D_
<span class="blue">Blue</span>_x000D_
</div>
_x000D_
I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
First, convert the base 64 string to an Image
, then use the Image.Save
method.
To convert from base 64 string to Image
:
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
To convert from Image
to base 64 string:
public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to base 64 string
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Finally, you can easily to call Image.Save(filePath);
to save the image.
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
The above answer by pl_rock is correct, the only thing I would add is to expect the ARG inside the Dockerfile if not you won't have access to it. So if you are doing
docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 --build-arg number_of_replicas=2 --no-cache .
Then inside the Dockerfile you should add
ARG number_of_replicas
ARG number_of_shards
I was running into this problem, so I hope I help someone (myself) in the future.
Note: I am not sure this will be of any help to you, but you never know.
I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html
ENJOY :-)
There are several causes for this error, I got this error because I checked "Reallocate all files to folder" in the Files tab of Restore Database window but the default path did not exist on my local machine. I had the ldf/mdf files in another folder, once I changed that I was able to restore.
I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:
<p>
Hello {
<span>World</span>
}!
</p>
or
<p>
Hello {}
<span>World</span>
{} again!
</p>
Each of these produces clean html without additional
or other extraneous markup. It creates fewer text nodes than using {' '}
, and allows using of html entities where {' hello & goodbye '}
does not.
If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")
z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)
w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis
It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.
I prefer to use getters rather than constants. Those getters might return constant values, e.g. public int getMaxConnections() {return 10;}
, but anything that needs the constant will go through a getter.
One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.
The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.
in django.utils.module_loading.module_has_submodule
import sys
import os
import imp
def module_has_submodule(package, module_name):
"""
check module in package
django.utils.module_loading.module_has_submodule
"""
name = ".".join([package.__name__, module_name])
try:
# None indicates a cached miss; see mark_miss() in Python/import.c.
return sys.modules[name] is not None
except KeyError:
pass
try:
package_path = package.__path__ # No __path__, then not a package.
except AttributeError:
# Since the remainder of this function assumes that we're dealing with
# a package (module with a __path__), so if it's not, then bail here.
return False
for finder in sys.meta_path:
if finder.find_module(name, package_path):
return True
for entry in package_path:
try:
# Try the cached finder.
finder = sys.path_importer_cache[entry]
if finder is None:
# Implicit import machinery should be used.
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
continue
# Else see if the finder knows of a loader.
elif finder.find_module(name):
return True
else:
continue
except KeyError:
# No cached finder, so try and make one.
for hook in sys.path_hooks:
try:
finder = hook(entry)
# XXX Could cache in sys.path_importer_cache
if finder.find_module(name):
return True
else:
# Once a finder is found, stop the search.
break
except ImportError:
# Continue the search for a finder.
continue
else:
# No finder found.
# Try the implicit import machinery if searching a directory.
if os.path.isdir(entry):
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
pass
# XXX Could insert None or NullImporter
else:
# Exhausted the search, so the module cannot be found.
return False
Although ObjectMapper is thread safe, I would strongly discourage from declaring it as a static variable, especially in multithreaded application. Not even because it is a bad practice, but because you are running a heavy risk of deadlocking. I am telling it from my own experience. I created an application with 4 identical threads that were getting and processing JSON data from web services. My application was frequently stalling on the following command, according to the thread dump:
Map aPage = mapper.readValue(reader, Map.class);
Beside that, performance was not good. When I replaced static variable with the instance based variable, stalling disappeared and performance quadrupled. I.e. 2.4 millions JSON documents were processed in 40min.56sec., instead of 2.5 hours previously.
On Android Studio 0.5.8 I managed to change my icon set by right clicking on the 'res' folder and selecting New > Image Asset. This brings you to the icon screen you are presented when creating the application, here after you change the icon it confirms that it will replace all the icons. Confirm and done.
Most likely, as mentioned by others, it is a class carrying the css values:
.clear{clear: both;}
in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.
In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.
Unless it is the most trivial case, there is only one sane way to use command line options in Ruby. It is called docopt and documented here.
What is amazing with it, is it's simplicity. All you have to do, is specify the "help" text for your command. What you write there will then be auto-parsed by the standalone (!) ruby library.
From the example:
#!/usr/bin/env ruby
require 'docopt.rb'
doc = <<DOCOPT
Usage: #{__FILE__} --help
#{__FILE__} -v...
#{__FILE__} go [go]
#{__FILE__} (--path=<path>)...
#{__FILE__} <file> <file>
Try: #{__FILE__} -vvvvvvvvvv
#{__FILE__} go go
#{__FILE__} --path ./here --path ./there
#{__FILE__} this.txt that.txt
DOCOPT
begin
require "pp"
pp Docopt::docopt(doc)
rescue Docopt::Exit => e
puts e.message
end
The output:
$ ./counted_example.rb -h
Usage: ./counted_example.rb --help
./counted_example.rb -v...
./counted_example.rb go [go]
./counted_example.rb (--path=<path>)...
./counted_example.rb <file> <file>
Try: ./counted_example.rb -vvvvvvvvvv
./counted_example.rb go go
./counted_example.rb --path ./here --path ./there
./counted_example.rb this.txt that.txt
$ ./counted_example.rb something else
{"--help"=>false,
"-v"=>0,
"go"=>0,
"--path"=>[],
"<file>"=>["something", "else"]}
$ ./counted_example.rb -v
{"--help"=>false, "-v"=>1, "go"=>0, "--path"=>[], "<file>"=>[]}
$ ./counted_example.rb go go
{"--help"=>false, "-v"=>0, "go"=>2, "--path"=>[], "<file>"=>[]}
Enjoy!
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
app.use() works like that:
which very simple.
And only then express will do the rest of the stuff like routing.
Layout Weight works like a ratio. For example, if there is a vertical layout and there are two items(such as buttons or textviews), one having layout weight 2 and the other having layout weight 3 respectively. Then the 1st item will occupy 2 out of 5 portion of the screen/layout and the other one 3 out of 5 portion. Here 5 is the weight sum. i.e. Weight sum divides the whole layout into defined portions. And Layout Weight defines how much portion does the particular item occupies out of the total Weight Sum pre-defined. Weight sum can be manually declared as well. Buttons, textviews, edittexts etc all are organized using weightsum and layout weight when using linear layouts for UI design.
A little bit simpler using regex and toJSON()
.
var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]
Which at the time of writing gives you "20151111180924"
.
The good thing of using toJSON()
is that everything comes already padded.
Why not just the good ol' javascript?
$('#element')[0].click()
Use source command to import large DB
mysql -u username -p
> source sqldbfile.sql
this can import any large DB
Make sure you are using the Public IP of you aws ec2 instance to ping.
edit the secuity group that is attached to your EC2 instance and add an inbound rule for ICMP protocol.
try pinging, if this doesnt fix, then add outbound rule for ICMP in the security group.
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
Working fine for me Resolve Json Infinite Recursion problem when working with Jackson
This is what I have done in oneToMany and ManyToOne Mapping
@ManyToOne
@JoinColumn(name="Key")
@JsonBackReference
private LgcyIsp Key;
@OneToMany(mappedBy="LgcyIsp ")
@JsonManagedReference
private List<Safety> safety;
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.
Your choices are to:
Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).
Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.
s = s.Replace("\"",string.Empty);
$time = strtotime($oldtime);
Then use date()
to put it into the correct format.
This is a known issue. The problem is that a div tag has the style "overflow: auto" which apparently is not implemented well with WebKit which is used by Safari and Chrome (see Emanuele Greco's answer). I did not know how to take advantage of Emanuele's suggestion to use the RS:ReportViewerHost element, but I solved it using JavaScript.
Problem
Solution
Since "overflow: auto" is specified in the style attribute of the div element with id "ctl31_ctl10", we can't override it in a stylesheet file so I resorted to JavaScript. I appended the following code to "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js"
function FixSafari()
{
var element = document.getElementById("ctl31_ctl10");
if (element)
{
element.style.overflow = "visible"; //default overflow value
}
}
// Code from http://stackoverflow.com/questions/9434/how-do-i-add-an-additional-window-onload-event-in-javascript
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', FixSafari, false); // NB **not** 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', FixSafari);
}
Note
There appears to be a solution for SSRS 2005 that I have not tried but I don't think it is applicable to SSRS 2008 because I can't find the "DocMapAndReportFrame" class.
Member functions that do not modify the class instance should be declared as const
:
int getId() const {
return id;
}
string getName() const {
return name;
}
Anytime you see "discards qualifiers", it's talking about const
or volatile
.
to upload a file using curl in Windows I found that the path requires escaped double quotes
e.g.
curl -v -F 'upload=@\"C:/myfile.txt\"' URL
subinacl.exe
from Microsoft:subinacl.exe
is in C:\Program Files (x86)\Windows Resource Kits\Tools\
).cd C:\Program Files (x86)\Windows Resource Kits\Tools\
subinacl /SERVICE \\MachineName\bst /GRANT=domainname.com\username=F
orsubinacl /SERVICE \\MachineName\bst /GRANT=username=F
There are some default colors defined in android.R.color
int c = getResources().getColor(android.R.color.primary_text_dark);
Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the width and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
Usage
import cv2
image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()
Using this example image
Simply downscale to width=100
(left) or upscale to width=300
(right)
Add inside your input tag: onkeyup="value=value.replace(/[^\d]/g,'')"
It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (Chapter 3). Briefly, in C you have multiple namespaces: tags, types, member names and identifiers. typedef
introduces an alias for a type and locates it in the tag namespace. Namely,
typedef struct Tag{
...members...
}Type;
defines two things. One Tag in the tag namespace and one Type in the type namespace. So you can do both Type myType
and struct Tag myTagType
. Declarations like struct Type myType
or Tag myTagType
are illegal. In addition, in a declaration like this:
typedef Type *Type_ptr;
we define a pointer to our Type. So if we declare:
Type_ptr var1, var2;
struct Tag *myTagType1, myTagType2;
then var1
,var2
and myTagType1
are pointers to Type but myTagType2
not.
In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot look here for details. Example:
typedef struct MyWriter_t{
MyPipe super;
MyQueue relative;
uint32_t flags;
...
}MyWriter;
you can do:
void my_writer_func(MyPipe *s)
{
MyWriter *self = (MyWriter *) s;
uint32_t myFlags = self->flags;
...
}
So you can access an outer member (flags
) by the inner struct (MyPipe
) through casting. For me it is less confusing to cast the whole type than doing (struct MyWriter_ *) s;
every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.
Finally, the last aspect with typedef
ed types is the inability to extend them, in contrast to macros. If for example, you have:
#define X char[10] or
typedef char Y[10]
you can then declare
unsigned X x; but not
unsigned Y y;
We do not really care for this for structs because it does not apply to storage specifiers (volatile
and const
).
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
if (!secondaryPassword.equals(initialPassword))
ROOT default app is usually Tomcat Manager - which can be useful so I felt like keeping it around.
So the way i made my app ROOT and kept TCmgr was like this.
renamed ROOT to something else
mv ROOT TCmgr
then created a symbolic link whereby ROOT points to the app i want to make the default.
ln -s <your app> ROOT
worked for me and seemed the easiest approach.
<pre lang="xml" >{{xmlString}}</pre>
This worked for me. Thanks to http://www.codeproject.com/Answers/998872/Display-XML-in-HTML-Div#answer1
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',
bbox_inches='tight', pad_inches=0, format='pdf', dpi=1200)
You guys are really giving me a headache. What you can do is make your layer-list drawable via xml first (meaning a background as the first layer, a drawable that represents secondary progress as the second layer, and another drawable that represents the primary progress as the last layer), then change the color on the code by doing the following:
public void setPrimaryProgressColor(int colorInstance) {
if (progressBar.getProgressDrawable() instanceof LayerDrawable) {
Log.d(mLogTag, "Drawable is a layer drawable");
LayerDrawable layered = (LayerDrawable) progressBar.getProgressDrawable();
Drawable circleDrawableExample = layered.getDrawable(<whichever is your index of android.R.id.progress>);
circleDrawableExample.setColorFilter(colorInstance, PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(layered);
} else {
Log.d(mLogTag, "Fallback in case it's not a LayerDrawable");
progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
}
This method will give you the best flexibility of having the measurement of your original drawable declared on the xml, WITH NO MODIFICATION ON ITS STRUCTURE AFTERWARDS, especially if you need to have the xml file screen folder specific, then just modifying ONLY THE COLOR via the code. No re-instantiating a new ShapeDrawable from scratch whatsoever.
This code copies and pastes all sheets (not cell values) from one source workbook to a destination workbook:
Private Sub copypastesheets()
Dim wbSource, wbDestination As Object
Dim nbSheets As Integer
Set wbSource = Workbooks("your_source_workbook_name")
Set wbDestination = Workbooks("your_destination_workbook_name")
nbSheets = wbDestination.Sheets.Count - 1
For Each sheetItem In wbSource.Sheets
nbSheets = nbSheets + 1
sheetItem.Copy after:=wbDestination.Sheets(nbSheets)
Next sheetItem
End Sub
ES6 1-liner
// :: splitAt = number => Array<any>|string => Array<Array<any>|string>_x000D_
const splitAt = index => x => [x.slice(0, index), x.slice(index)]_x000D_
_x000D_
console.log(_x000D_
splitAt(1)('foo'), // ["f", "oo"]_x000D_
splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]_x000D_
)_x000D_
_x000D_
Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:
scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
0
\u0000
or 0
0.0
false
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
Hexadecimal IP Address to String IP
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
uint32_t ip = 0x0AA40001;
string ip_str="";
int temp = 0;
for (int i = 0; i < 8; i++){
if (i % 2 == 0)
{
temp += ip & 15;
ip = ip >> 4;
}
else
{
stringstream ss;
temp += (ip & 15) * 16;
ip = ip >> 4;
ss << temp;
ip_str = ss.str()+"." + ip_str;
temp = 0;
}
}
ip_str.pop_back();
cout << ip_str;
}
Output:10.164.0.1
You can nest your queries:
select * from (
select bla
from bla
where bla
order by finaldate desc
)
where rownum < 2
My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface
From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.
create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode
How to spin up a zookeper environment within minutes on docker for windows, linux or mac:
One time set up:
docker network create dn
Run server in a terminal window:
docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper
Run client in a second terminal window:
docker run -it --rm --network dn zookeeper zkCli.sh -server zook
See also documentation of image on dockerhub
If you don't want the buttons to scale, but adjust the spacing between the buttons (equal spacing between all buttons), you can use views with weight="1" which will fill the space between the buttons:
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" >
</Space>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@null"
android:gravity="center_horizontal|center_vertical"
android:src="@drawable/tars_active" />
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" >
</Space>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@null"
android:gravity="center_horizontal|center_vertical"
android:src="@drawable/videos_active" />
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" >
</Space>
NOTE - If this answer doesn't help you, please take the time to scroll down through the other answers that people have added since.
Short answer
This can happen if you add a method to an interface in one assembly, and then to an implementing class in another assembly, but you rebuild the implementing assembly without referencing the new version of the interface assembly.
In this case, DummyItem implements an interface from another assembly. The SetShort method was recently added to both the interface and the DummyItem - but the assembly containing DummyItem was rebuilt referencing the previous version of the interface assembly. So the SetShort method is effectively there, but without the magic sauce linking it to the equivalent method in the interface.
Long answer
If you want to try reproducing this, try the following:
Create a class library project: InterfaceDef, add just one class, and build:
public interface IInterface
{
string GetString(string key);
//short GetShort(string key);
}
Create a second class library project: Implementation (with separate solution), copy InterfaceDef.dll into project directory and add as file reference, add just one class, and build:
public class ImplementingClass : IInterface
{
#region IInterface Members
public string GetString(string key)
{
return "hello world";
}
//public short GetShort(string key)
//{
// return 1;
//}
#endregion
}
Create a third, console project: ClientCode, copy the two dlls into the project directory, add file references, and add the following code into the Main method:
IInterface test = new ImplementingClass();
string s = test.GetString("dummykey");
Console.WriteLine(s);
Console.ReadKey();
Run the code once, the console says "hello world"
Uncomment the code in the two dll projects and rebuild - copy the two dlls back into the ClientCode project, rebuild and try running again. TypeLoadException occurs when trying to instantiate the ImplementingClass.
You can be more precise with CSS background-origin:
background-origin: content-box;
This will make image respect the padding of the box.
Make the image 100% bright so it is clear. And then on Img hover reduce it to whatever brightness you want.
img {_x000D_
-webkit-transition: all 1s ease;_x000D_
-moz-transition: all 1s ease;_x000D_
-o-transition: all 1s ease;_x000D_
-ms-transition: all 1s ease;_x000D_
transition: all 1s ease;_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
-webkit-filter: brightness(70%);_x000D_
filter: brightness(70%);_x000D_
}
_x000D_
<img src="http://dummyimage.com/300x150/ebebeb/000.jpg">
_x000D_
That will do it, Hope that helps
One simple method is to use place
to use an image as a background image. This is the type of thing that place
is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid
or pack
other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
Dissenting voice here: after 5 years of rspec I don't like let
very much.
It becomes difficult to reason about setup when some things that have been declared in setup are not actually affecting state, while others are.
Eventually, out of frustration someone just changes let
to let!
(same thing without lazy evaluation) in order to get their spec working. If this works out for them, a new habit is born: when a new spec is added to an older suite and it doesn't work, the first thing the writer tries is to add bangs to random let
calls.
Pretty soon all the performance benefits are gone.
I would rather teach Ruby to my team than the tricks of rspec. Instance variables or method calls are useful everywhere in this project and others, let
syntax will only be useful in rspec.
let()
is good for expensive dependencies that we don't want to create over and over.
It also pairs well with subject
, allowing you to dry up repeated calls to multi-argument methods
Expensive dependencies repeated in many times, and methods with big signatures are both points where we could make the code better:
In all these cases, I can address the symptom of difficult tests with a soothing balm of rspec magic, or I can try address the cause. I feel like I spent way too much of the last few years on the former and now I want some better code.
To answer the original question: I would prefer not to, but I do still use let
. I mostly use it to fit in with the style of the rest of the team (it seems like most Rails programmers in the world are now deep into their rspec magic so that is very often). Sometimes I use it when I'm adding a test to some code that I don't have control of, or don't have time to refactor to a better abstraction: i.e. when the only option is the painkiller.
I can see a number of reasons:
Readability
string s = string.Format("Hey, {0} it is the {1}st day of {2}. I feel {3}!", _name, _day, _month, _feeling);
vs:
string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ". I feel " + feeling + "!";
Format Specifiers (and this includes the fact you can write custom formatters)
string s = string.Format("Invoice number: {0:0000}", _invoiceNum);
vs:
string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)
String Template Persistence
What if I want to store string templates in the database? With string formatting:
_id _translation
1 Welcome {0} to {1}. Today is {2}.
2 You have {0} products in your basket.
3 Thank-you for your order. Your {0} will arrive in {1} working days.
vs:
_id _translation
1 Welcome
2 to
3 . Today is
4 .
5 You have
6 products in your basket.
7 Someone
8 just shoot
9 the developer.
I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.
To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"
Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.
The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..
[Serializable]
public class FileMetaDataDto
{
.
. a constructor... etc and several other properties edited for brevity
.
public int Id { get; private set; }
public string Version { get; private set; }
public List<MetaDataValueDto> CustomFields { get; set; }
}
On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.
So the wsdl before update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
</s:sequence>
</s:complexType>
The wsdl after update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" />
<s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" />
<s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
<s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" />
</s:sequence>
</s:complexType>
To check if a directory named "Folder" exists use:
QDir("Folder").exists();
To create a new folder named "MyFolder" use:
QDir().mkdir("MyFolder");
Also useful is the coalesce operator ??:
VB:
Return Iif( s IsNot Nothing, s, "My Default Value" )
C#:
return s ?? "My Default Value";
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
If you want to sort by the order that items were inserted instead of of the order of the keys, you should have a look to Python's collections.OrderedDict. (Python 3 only)
I Hope this code is beneficial for you
public class Register extends Activity
{
EditText FirstName, PhoneNo, EmailId,weight;
Button Register;
private static final Pattern EMAIL_PATTERN = Pattern
.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
private static final Pattern USERFIRSTNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PHONE_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Register=(Button) findViewById(R.id.register);
FirstName=(EditText)findViewById(R.id.person_firstname);
PhoneNo =(EditText)findViewById(R.id.phone_no);
EmailId=(EditText)findViewById(R.id.email_id);
weight=(EditText) findViewById(R.id.weight);
Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sFirstName= FirstName.getText().toString();
sPhoneNo= PhoneNo.getText().toString();
sEmailId= EmailId.getText().toString();
sweight= weight.getText().toString();
if(sFirstName.equals("")||sPhoneNo.equals("")||sEmailId.equals("")||sweight.equals(""))
{
if ((!CheckUsername(sFirstName)))
{
Toast.makeText(Register.this, "FirstName can not be null",Toast.LENGTH_LONG).show();
}
else if ((!Checkphoneno(sPhoneNo)))
{
Toast.makeText(Register.this, "ENTER VALID mobile no ",Toast.LENGTH_LONG).show();
}
else if ((!CheckEmail(sEmailId)))
{
Toast.makeText(Register.this, "ENTER VALID EMAIL ID",Toast.LENGTH_LONG).show();
}
else if ((!Checkweight(sweight)))
{
Toast.makeText(Register.this, "ENTER Weight in kg",Toast.LENGTH_LONG).show();
}
}
}
private boolean CheckEmail(String sEmailId) {
return EMAIL_PATTERN.matcher(sEmailId).matches();
}
private boolean CheckUsername(String sFirstName) {
return USERFIRSTNAME_PATTERN.matcher(sFirstName).matches();
}
private boolean Checkphoneno(String sPhoneNo) {
return PHONE_PATTERN.matcher(sPhoneNo).matches();
}
private boolean Checkweight(String sweight) {
return Weight_PATTERN.matcher(sweight).matches();
}
});
If you want to delete manually (for me it was easier), follow this:
Let's get this example with "teste".
1 - First change the explorer to "project" and open "settings.gradle";
2 - Delete the module you want;
3 - Go to your root folder of your project and delete the module folder.
Having learned of this feature only just now while reading your question, I can only speculate. This seems to provide several advantages over a file-level static variable:
I'd be interested in learning if anyone has used anonymous namespaces in real code.
You may use DateDiff
and compare by day.
DateDiff(dd,@date1,@date2) > 0
It means @date2 > @date1
For example :
select DateDiff(dd, '01/01/2021 10:20:00', '02/01/2021 10:20:00')
has the result : 1
If you just wanted to change the example and put the table at the top, then loc='top'
in the table declaration is what you need,
the_table = ax.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='top')
Then adjusting the plot with,
plt.subplots_adjust(left=0.2, top=0.8)
A more flexible option is to put the table in its own axis using subplots,
import numpy as np
import matplotlib.pyplot as plt
fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')
axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()
which looks like this,
You are then free to adjust the locations of the axis as required.
We can use below Curl command in Windows Command prompt to send the request.
Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^
symbol.
curl http://localhost:7101/module/url ^
-d @D:/request.xml ^
-H "Content-Type: text/xml" ^
-H "SOAPAction: process" ^
-H "Authorization: Basic xyz" ^
-X POST
I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
In numpy, there's numpy.mean()
.
I've been working in the address processing domain for about 5 years now, and there really is no silver bullet. The correct solution is going to depend on the value of the data. If it's not very valuable, throw it through a parser as the other answers suggest. If it's even somewhat valuable you'll definitely need to have a human evaluate/correct all the results of the parser. If you're looking for a fully automated, repeatable solution, you probably want to talk to a address correction vendor like Group1 or Trillium.
And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.
Here's two options. I prefer the navigationAlt option since it involves less work in the end:
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
#navigation li {_x000D_
color: green;_x000D_
}_x000D_
#navigation li .navigationLevel2 {_x000D_
color: red;_x000D_
}_x000D_
#navigationAlt {_x000D_
color: green;_x000D_
}_x000D_
#navigationAlt ul {_x000D_
color: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<ul id="navigation">_x000D_
<li>Level 1 item_x000D_
<ul>_x000D_
<li class="navigationLevel2">Level 2 item</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<ul id="navigationAlt">_x000D_
<li>Level 1 item_x000D_
<ul>_x000D_
<li>Level 2 item</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.
Here is the code for the approach I worked out on a win form web browser control:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate(@"path\to\file");
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
//Progress Changed fires multiple times, however after the Navigated event it is fired only once,
//and at this point it is ready to print
webBrowser1.ProgressChanged += (o, args) =>
{
webBrowser1.Print();//Note this does not print only brings up the print preview dialog
//Should be on a separate task to ensure the main thread
//can fully initialize the print dialog
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);//We need to wait before we can send enter
//This assumes that the print preview is still in focus
Action g = () =>
{
SendKeys.SendWait("{ENTER}");
};
this.Invoke(g);
});
};
}
There are 2 options you can go with HTTP URL Hits : GET / POST
GET Request :-
HttpURLConnection.setFollowRedirects(true); // defaults to true
String url = "https://name_of_the_url";
URL request_url = new URL(url);
HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
http_conn.setConnectTimeout(100000);
http_conn.setReadTimeout(100000);
http_conn.setInstanceFollowRedirects(true);
System.out.println(String.valueOf(http_conn.getResponseCode()));
POST request :-
HttpURLConnection.setFollowRedirects(true); // defaults to true
String url = "https://name_of_the_url"
URL request_url = new URL(url);
HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
http_conn.setConnectTimeout(100000);
http_conn.setReadTimeout(100000);
http_conn.setInstanceFollowRedirects(true);
http_conn.setDoOutput(true);
PrintWriter out = new PrintWriter(http_conn.getOutputStream());
if (urlparameter != null) {
out.println(urlparameter);
}
out.close();
out = null;
System.out.println(String.valueOf(http_conn.getResponseCode()));
Swift applications are supported on iOS 7 and above as stated in Beta 4 release notes. iOS 6.0, 6.1, 7.0, 7.1, 8.0 in Xcode 6 Beta
Swift applications are supported on platforms OS X 10.9 and above. OS X 10.4 to 10.10 in Deployment Target. I have tested on targeting 10.5 to 10.10, and running on 10.9.3
I had a read of the spec and did some testing in Chrome, and if you catch the "invalid" event and return false that seems to allow form submission.
I am using jquery, with this HTML.
// suppress "invalid" events on URL inputs_x000D_
$('input[type="url"]').bind('invalid', function() {_x000D_
alert('invalid');_x000D_
return false;_x000D_
});_x000D_
_x000D_
document.forms[0].onsubmit = function () {_x000D_
alert('form submitted');_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="url" value="http://" />_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
I haven't tested this in any other browsers.
Using jquery you can do it this way
$("#order").click(function(e){
e.preventDefault();
window.location="login.php";
});
Also in HMTL you can do it this way
<form name="frm" action="login.php" method="POST">
...
</form>
Hope this helps
Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.
Some where able to get an updated favicon by adding an URL parameter: ?v=1
after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).
<link rel="icon" type="image/x-icon" href="favicon.ico?v=2" />
How did you import the favicon? How you should add it.
Normal favicon:
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
PNG/GIF favicon:
<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />
in the <head>
Tag.
Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?
Try to rename it from favicon.{whatever}
to {yourfaviconname}.{whatever}
but I would suggest you to still have the normal favicon. This has solved my issue on IE.
Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:
<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />
Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp
I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.
You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h
only for the _TCHAR
macro.
Then, precompiled header is usually a per-project file in Visual Studio world, so:
#include <stdafx.h>
to #include "stdafx.h"
. It is supposed to be a project local file, not to be resolved in include directories.Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h
.
If you use Libpq binding for respective language, according to its documentation URI is formed as follows:
postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
Here are examples from same document
postgresql://
postgresql://localhost
postgresql://localhost:5432
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://localhost/mydb?user=other&password=secret
I recently encountered this problem while working on a contract project(deemed classified). The system in which I had to run the code did not have internet access, for security purposes of course, and so installing dependencies, using composer and npm, was becoming huge pain.
After much deliberation with my colleague, we decided to just wing it and copy paste our dependencies rather than doing composer install or npm install.
This led us to NOT add vendors and npm_modules in gitignore. This is when I encountered this problem.
Changed but not updated:
modified: vendor/plugins/open_flash_chart_2 (modified content, untracked content)
I googled this a bit and found this helpful thread on SO. Not being too much of a pro in Git, and being a little intoxicated while working on it, I just searched for all the submodules in the vendors folder
find . -name ".git"
This gave me some 4-5 dependencies that had git on them. I removed all these .git folders and voila, it worked. I knows it's hack, and not a very geeky one anyways. O Gods of SO, please forgive me! Next time I promise to read up on gitlinks and obey O mighty Linus Tovalds.
Character.isDigit(string.charAt(0))
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
Or the slower regex solutions:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0)
and substring(0, 1)
will throw a StringIndexOutOfBoundsException
. startsWith
does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.
If you're already using jQuery, you could look at using the jQuery Number Format plugin.
The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.
$.number( 123, 2 ); // Returns '123.00'
You can also get jQuery Number Format from GitHub.
If you have context data along with css and js in your html template. Than you have good option to use pdfjs.
In your code you can use like this.
from django.template.loader import get_template
import pdfkit
from django.conf import settings
context={....}
template = get_template('reports/products.html')
html_string = template.render(context)
pdfkit.from_string(html_string, os.path.join(settings.BASE_DIR, "media", 'products_report-%s.pdf'%(id)))
In your HTML you can link extranal or internal css and js, it will generate best quality of pdf.
I have an S3 and used this guide from Google:
https://developers.google.com/chrome-developer-tools/docs/remote-debugging
Really easy, works flawlessly.
Here was an idea i was thinking of:
Have an iframe on page and have a referencer.
Have a form in which you move the INPUT:File element to.
Form: A processing page AND a target of the FRAME.
The result will post to the frame, and then you can just send the fetched data up a level to the image tag you want with something like:
data:image/png;base64,asdfasdfasdfasdfa
and the page loads.
I believe it works for me, and depending you might be able to do something like:
.aftersubmit(function(){
stopPropigation()// or some other code which would prevent a refresh.
});
Download the source code, unzip it to and directory, and execute python setup.py install.
This is the problem with your $PATH:
/usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin
.
$PATH
is where the shell searches for command files. Folders to search in need to be separated with a colon. And so you want /usr/local/mysql/bin/
in your path but instead it searches in /usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin
, which probably doesn't exist.
Instead you want ${PATH}:/usr/local/mysql/bin
.
So do export PATH=${PATH}:/usr/local/mysql/bin
.
If you want this to be run every time you open terminal put it in the file .bash_profile
, which is run when Terminal opens.
Try this:
var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
item.Text = "";
}
The initial width of a block level element like div or p is auto.
Use width:auto to undo explicitly specified widths.
if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border.
So, next time you find yourself setting the width of a block level element to 100% to make it occupy all available width, consider if what you really want is setting it to auto.
Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!
$string_val = 'a.b';
$parts = explode('.', $string_val);
print_r($parts);
scala> lazy val lazyEight = {
| println("I am lazy !")
| 8
| }
lazyEight: Int = <lazy>
scala> lazyEight
I am lazy !
res1: Int = 8
Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.
Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).
That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:
if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();
(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).
While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.
I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.
2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront
method do this (in conjunction with modified code from what is above):
setVisible(true);
toFront();
requestFocus();
repaint();
...
public @Override void toFront() {
int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;
super.setExtendedState(sta);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
As of Java 8_20, this code seems to be working fine.
As per W3C spec,
The list properties ... do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker ...
But the idea with a span inside the list above should work fine!
Alt + Shift + F10 will show the menu associated with the smart tag.
Use this way,
int orientation = getResources().getConfiguration().orientation;
String Orintaion = "";
switch (orientation)
{
case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
case Configuration.ORIENTATION_PORTRAIT: Orintaion = "Portrait"; break;
default: Orintaion = "Square";break;
}
in the String you have the Oriantion
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)
This is just main
and Ctrl-Space.
I know that this is an old question that has been well answered, but for my own amusement I wrote the following reverse function and thought I would share it in case it was useful for anyone else. It handles both surrogate pairs and combining marks:
function StringReverse (str)
{
var charArray = [];
for (var i = 0; i < str.length; i++)
{
if (i+1 < str.length)
{
var value = str.charCodeAt(i);
var nextValue = str.charCodeAt(i+1);
if ( ( value >= 0xD800 && value <= 0xDBFF
&& (nextValue & 0xFC00) == 0xDC00) // Surrogate pair)
|| (nextValue >= 0x0300 && nextValue <= 0x036F)) // Combining marks
{
charArray.unshift(str.substring(i, i+2));
i++; // Skip the other half
continue;
}
}
// Otherwise we just have a rogue surrogate marker or a plain old character.
charArray.unshift(str[i]);
}
return charArray.join('');
}
All props to Mathias, Punycode, and various other references for schooling me on the complexities of character encoding in JavaScript.
I believe the proper way of adding pthread
in CMake
is with the following
find_package (Threads REQUIRED)
target_link_libraries(helloworld
${CMAKE_THREAD_LIBS_INIT}
)
After some googling I found this:
curl -c cookie.txt -d "LoginName=someuser" -d "password=somepass" https://oursite/a
curl -b cookie.txt https://oursite/b
No idea if it works, but it might lead you in the right direction.
What you want cannot be done, because plt.legend()
places a legend in the current axes, in your case in the last one.
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.
The input operator for number skips leading whitespace, so you can just read the number in a loop:
while (myfile >> a)
{
// ...
}
Add this in MainActivity.
Intent intent = new Intent(getApplicationContext(), Heightimage.class);
startActivity(intent);
To understand it in a easier way, following are the diffrences between JSON object and JSON array:
Link to Tabular Difference : https://i.stack.imgur.com/GIqI9.png
JSON Array
1. Arrays in JSON are used to organize a collection of related items
(Which could be JSON objects)
2. Array values must be of type string, number, object, array, boolean or null
3. Syntax:
[ "Ford", "BMW", "Fiat" ]
4. JSON arrays are surrounded by square brackets [].
**Tip to remember** : Here, order of element is important. That means you have
to go straight like the shape of the bracket i.e. straight lines.
(Note :It is just my logic to remember the shape of both.)
5. Order of elements is important. Example: ["Ford","BMW","Fiat"] is not
equal to ["Fiat","BMW","Ford"]
6. JSON can store nested Arrays that are passed as a value.
JSON Object
1. JSON objects are written in key/value pairs.
2. Keys must be strings, and values must be a valid JSON data type (string, number,
object, array, boolean or null).Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
3. Syntax:
{ "name":"Somya", "age":25, "car":null }
4. JSON objects are surrounded by curly braces {}
Tip to remember : Here, order of element is not important. That means you can go
the way you like. Therefore the shape of the braces i.e. wavy.
(Note : It is just my logic to remember the shape of both.)
5. Order of elements is not important.
Example: { rollno: 1, firstname: 'Somya'}
is equal to
{ firstname: 'Somya', rollno: 1}
6. JSON can store nested objects in JSON format in addition to nested arrays.
$("input[type=checkbox]").on("change", function() {
if (this.checked) {
//do your stuff
}
});
You get only the name because you return only the name return "login";
. It's @RestController
and this controller returns data rather than a view; because of this, you get only content that you return from method.
If you want to show view with this name you need to use Spring MVC, see this example.
Another way of solving this problem is using Reactive Extensions:
public static Task TimeoutAfter(this Task task, TimeSpan timeout, IScheduler scheduler)
{
return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}
Test up above using below code in your unit test, it works for me
TestScheduler scheduler = new TestScheduler();
Task task = Task.Run(() =>
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
Thread.Sleep(1000);
}
})
.TimeoutAfter(TimeSpan.FromSeconds(5), scheduler)
.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
scheduler.AdvanceBy(TimeSpan.FromSeconds(6).Ticks);
You may need the following namespace:
using System.Threading.Tasks;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using Microsoft.Reactive.Testing;
using System.Threading;
using System.Reactive.Concurrency;
I have changed the folder hierarchy
/shop/shop_name/base.html To /shop_name/shop/base.html
and then below would work.
{% extends shop_name|add:"/shop/base.html"%}
Now its able to extend the base.html page.
I know this is an old thread but an easier solution would be to embed an input within the label like so:
<label>Label one: <input id="input1" type="text"></label>
_x000D_
I guess the proper solution is:
(1) backup your-file/your-directory
(2) svn revert your-file/your-directory
(3) svn update your-file/your-directory
(4) Merge the backup your-file/your-directory to the updated one.
(5) svn ci -m "My work here is done"
it's should overlap, so it turned off. Try to open in your text editor and find display_errors
and turn it on. It works for me
It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:
while read input
do
echo $input
done < filename
If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>
You could do something like this:
create procedure test
as
BEGIN
create table #ids
(
rn int,
id int
)
insert into #ids (rn, id)
select distinct row_number() over(order by id) as rn, id
from table
declare @id int
declare @totalrows int = (select count(*) from #ids)
declare @currentrow int = 0
while @currentrow < @totalrows
begin
set @id = (select id from #ids where rn = @currentrow)
exec stored_proc @varName=@id, @otherVarName='test'
set @currentrow = @currentrow +1
end
END
var Results= query.GroupBy(f => new { /* add members here */ });
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
/tmp/myfile
first line text
wanted text
other text
the command
$ grep -n "wanted text" /tmp/myfile | awk -F ":" '{print $1}'
2
I have a simple form to submit testimonials, I also was having trouble clearing the form, what I did was after the query is submitted successfully I and before redirecting to another page I cleared the imputs $name =''; ect. The page submitted and redirected with no errors.
Select "File" -> "Project Structure".
Under "Project Settings" select "Project"
From there you can select the "Project SDK".
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
To simplify Amiram Korach's solution:
dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))
No need to use Distinct() or ToList()
var result=[];
var app = angular.module('app', []);
app.controller('myCtrl', function ($scope, $http) {
var url="";// your request url
var request={};// your request parameters
var headers = {
// 'Authorization': 'Basic ' + btoa(username + ":" + password),
'Access-Control-Allow-Origin': true,
'Content-Type': 'application/json; charset=utf-8',
"X-Requested-With": "XMLHttpRequest"
}
$http.post(url, request, {
headers
})
.then(function Success(response) {
result.push(response.data);
$scope.Data = result;
},
function Error(response) {
result.push(response.data);
$scope.Data = result;
console.log(response.statusText + " " + response.status)
});
});
And also add following code in your WebApiConfig file
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Another alternative
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Simple solution with an example :
<div id="id_div">
<p>content<p>
</div>
Move this DIV to other DIV with id = "other_div_id"
$('#other_div_id').prepend( $('#id_div') );
Finish
For future people CTRL+ALT+D or just view > report data in ancient ssrs 2008 VS BI. In newer 2017 SSRS, it's still the same. Funny how they change a bunch of things around, yet kept this the same.
HTML:
<textarea rows="10" cols="20" id="text"></textarea>
CSS:
#text
{
overflow-y:scroll;
}
Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.
Column pruning
Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).
Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.
import pandas as pd
pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])
Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.
If the data is stored in a CSV file, you can read it like this:
import pandas as pd
pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])
usecols
can't skip over entire columns because of the row nature of the CSV file format.
Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.
Popularity
Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.
Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.
Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.
Schema
Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.
Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.
Column metadata
Parquet stores metadata statistics for each column and lets users add their own column metadata as well.
The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.
Here's how to fetch the column statistics with PyArrow.
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
has_min_max: True
min: 1
max: 9
null_count: 0
distinct_count: 0
num_values: 3
physical_type: INT64
logical_type: None
converted_type (legacy): NONE
Complex column types
Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.
Compression
Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.
first_name,age
ken,30
felicia,36
mia,2
This data is easier to compress when the related types are stored in the same row:
ken,felicia,mia
30,36,2
Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.
Mutable nature of file
Parquet files are immutable, as described here. CSV files are mutable.
Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.
Data lakes
In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.
Running console svn cleanup
has solved the same problem for me.
I tested this code and it works great:
class MyClass: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
}
Initialise the view and use it like below:
var view = MyClass.instanceFromNib()
self.view.addSubview(view)
OR
var view = MyClass.instanceFromNib
self.view.addSubview(view())
UPDATE Swift >=3.x & Swift >=4.x
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}
function remove_script_tags($html){
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
$remove = [];
foreach($script as $item){
$remove[] = $item;
}
foreach ($remove as $item){
$item->parentNode->removeChild($item);
}
$html = $dom->saveHTML();
$html = preg_replace('/<!DOCTYPE.*?<html>.*?<body><p>/ims', '', $html);
$html = str_replace('</p></body></html>', '', $html);
return $html;
}
Dejan's answer was good, but saveHTML() adds unnecessary doctype and body tags, this should get rid of it. See https://3v4l.org/82FNP
Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.
Setting the passenger.Title
with a value that equals to a title.Value
should work.
View:
<select [(ngModel)]="passenger.Title">
<option *ngFor="let title of titleArray" [value]="title.Value">
{{title.Text}}
</option>
</select>
TypeScript used:
class Passenger {
constructor(public Title: string) { };
}
class ValueAndText {
constructor(public Value: string, public Text: string) { }
}
...
export class AppComponent {
passenger: Passenger = new Passenger("Lord");
titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
new ValueAndText("Lord", "Lord-Text")];
}
Oracle views like ALL_TABLES and ALL_CONSTRAINTS have an owner column, which you can use to restrict your query. There are also variants of these tables beginning with USER instead of ALL, which only list objects which can be accessed by the current user.
One of these views should help to solve your problem. They always worked fine for me for similar problems.
I figured out such data design:
Main sheet: Column A: Pump codes (numbers)
Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'
=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)
Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.
Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B
=INDIRECT("Ruhrpumpen!A"&$B2)
Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:
=INDIRECT("Ruhrpumpen!B"&$B2)
Sheet 'Ruhrpumpen':
Column A: some data about a certain pump
Column B: some more data
Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.
Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls
I wrote the code from the accepted answer as a jQuery plugin, which I find more useful. (also, it now ignores hidden, disabled, and readonly form elements).
$.fn.enterAsTab = function () {
$(this).find('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])"),
idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
return this;
};
This way I can do $('#form-id').enterAsTab(); ... Figured I'd post since no one has posted it as a $ plugin yet and they aren't entirely intuitive to write.
var = False
if not var: print 'learnt stuff'
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
This worked for me with slight modification and without any plugin
Input : Wed Apr 11 2018 00:00:00 GMT+0000
$.date = function(orginaldate) {
var date = new Date(orginaldate);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = month + "/" + day + "/" + year;
return date;
};
$.date('Wed Apr 11 2018 00:00:00 GMT+0000')
Output: 04/11/2018
char check1[10], check2[10];
int foo;
do{
printf(">> ");
scanf(" %s", check1);
foo = strtol(check1, NULL, 10); // convert the string to decimal number
sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number
If the input is number, you can use foo
as your input.
Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:
drush watchdog-show --tail
Available in drush v8 and below.
This will give you a live look at the logs from your console.
With a regular expression and the function gsub()
:
group <- c("12357e", "12575e", "197e18", "e18947")
group
[1] "12357e" "12575e" "197e18" "e18947"
gsub("e", "", group)
[1] "12357" "12575" "19718" "18947"
What gsub
does here is to replace each occurrence of "e"
with an empty string ""
.
See ?regexp
or gsub
for more help.
You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.
These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types>
tag.
(thanks to Cheeso for pointing out my inaccurate usage of terms)
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.You can either choose to set the headers manually, or make an HTTP interceptor that automatically sets header(s) every time a request is being made.
Setting a header:
http
.post('/api/items/add', body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
})
.subscribe();
Setting headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
Local variable (immutable instantiate again)
let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');
this.http
.post('api/items/add', body, { headers: headers })
.subscribe()
The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.
From the Angular docs.
A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.
From the Angular docs.
Make sure you use @angular/common/http
throughout your application. That way your requests will be catched by the interceptor.
Step 1, create the service:
import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (true) { // e.g. if token exists, otherwise use incomming request.
return next.handle(req.clone({
setHeaders: {
'AuthenticationToken': localStorage.getItem('TOKEN'),
'Tenant': localStorage.getItem('TENANT')
}
}));
}
else {
return next.handle(req);
}
}
}
Step 2, add it to your module:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HeaderInterceptor,
multi: true // Add this line when using multiple interceptors.
},
// ...
]
Useful links:
Create the Button
and add it to Form.Controls
list to display it on your form:
Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45); //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list
Create the button click method here:
void buttonOk_Click(object sender, EventArgs e)
{
MessageBox.Show("clicked");
this.Close(); //all your choice to close it or remove this line
}
$('#submit_button').click(function() {
if (!$("input[@name='name']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the radio buttons is checked!');
}
});
In a more general way you can use "INTERVAL". Here some examples:
1) add a day
select sysdate + INTERVAL '1' DAY from dual;
2) add 20 days
select sysdate + INTERVAL '20' DAY from dual;
2) add some minutes
select sysdate + INTERVAL '15' MINUTE from dual;
You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.
The extern
keyword takes on different forms depending on the environment. If a declaration is available, the extern
keyword takes the linkage as that specified earlier in the translation unit. In the absence of any such declaration, extern
specifies external linkage.
static int g();
extern int g(); /* g has internal linkage */
extern int j(); /* j has tentative external linkage */
extern int h();
static int h(); /* error */
Here are the relevant paragraphs from the C99 draft (n1256):
6.2.2 Linkages of identifiers
[...]
4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.
5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
First, install Python 3 pip using:
sudo apt-get install python3-pip
Then, to use Python 3 pip
use:
pip3 install <module-name>
For Python 2 pip
use:
pip install <module-name>
A more compact and efficient way would be perhaps:
cols = ['frame', 'count']
N = 4
dat = pd.DataFrame(columns = cols)
for i in range(N):
dat = dat.append({'frame': str(i), 'count':i},ignore_index=True)
output would be:
>>> dat
frame count
0 0 0
1 1 1
2 2 2
3 3 3
The following helped me as I didn't have DBA access and also wanted the column names.
See: https://dataedo.com/kb/query/oracle/list-table-indexes
select ind.table_owner || '.' || ind.table_name as "TABLE",
ind.index_name,
LISTAGG(ind_col.column_name, ',')
WITHIN GROUP(order by ind_col.column_position) as columns,
ind.index_type,
ind.uniqueness
from sys.all_indexes ind
join sys.all_ind_columns ind_col
on ind.owner = ind_col.index_owner
and ind.index_name = ind_col.index_name
where ind.table_owner not in ('ANONYMOUS','CTXSYS','DBSNMP','EXFSYS',
'MDSYS', 'MGMT_VIEW','OLAPSYS','OWBSYS','ORDPLUGINS', 'ORDSYS',
'SI_INFORMTN_SCHEMA','SYS','SYSMAN','SYSTEM', 'TSMSYS','WK_TEST',
'WKPROXY','WMSYS','XDB','APEX_040000','APEX_040200',
'DIP', 'FLOWS_30000','FLOWS_FILES','MDDATA', 'ORACLE_OCM', 'XS$NULL',
'SPATIAL_CSW_ADMIN_USR', 'SPATIAL_WFS_ADMIN_USR', 'PUBLIC',
'LBACSYS', 'OUTLN', 'WKSYS', 'APEX_PUBLIC_USER')
-- AND ind.table_name='TableNameGoesHereIfYouWantASpecificTable'
group by ind.table_owner,
ind.table_name,
ind.index_name,
ind.index_type,
ind.uniqueness
order by ind.table_owner,
ind.table_name;
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
The expression
"" + i
leads to string conversion of i
at runtime. The overall type of the expression is String
. i
is first converted to an Integer
object (new Integer(i)
), then String.valueOf(Object obj)
is called. So it is equivalent to
"" + String.valueOf(new Integer(i));
Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i))
which will produce the very same result.
The advantage of ""+i
is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.
(Reference: JLS 15.8.1)
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
Because you are passing three arguments to a four arguments method. Also, you are not using the passed closure.
If you want to specify the operations to be made on top of the source
contents, then use a closure. It would be something like this:
def copyAndReplaceText(source, dest, closure){
dest.write(closure( source.text ))
}
// And you can keep your usage as:
copyAndReplaceText(source, dest){
it.replaceAll('Visa', 'Passport!!!!')
}
If you will always swap strings, pass both, as your method signature already states:
def copyAndReplaceText(source, dest, targetText, replaceText){
dest.write(source.text.replaceAll(targetText, replaceText))
}
copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')
You can use it with the arrow function as well like as below :
var demoArray = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
var result = demoArray.filter( obj => obj.name === 'apples')[0];
console.log(result);
// {name: 'apples', quantity: 2}
first select the table you you would like to make the relation with >> then go to operation , for each table there is difference operation setting, >> inside operation "storage engine" choose innoDB option
innoDB will allow you to view the "relation view" which will help you make the foreign key
lapply
is probably a better choice than apply
here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.
The pattern is:
df[cols] <- lapply(df[cols], FUN)
The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:
wifi[4:9] <- lapply(wifi[4:9], A)
An example of using column names:
wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)
I got this error message because while coding my project auto update compile version in my build.gradle
file :
android {
...
buildToolsVersion "23.0.2"
...
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0' }
Solve it by correcting the version:
android {
...
buildToolsVersion "23.0.2"
...
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}
Here's what I came up with.
form.addEventListener("submit", (e) => { //On Submit
let key = e.charCode || e.keyCode || 0 //get the key code
if (key = 13) { //If enter key
e.preventDefault()
const inputs = Array.from(document.querySelectorAll("form input")) //Get array of inputs
let nextInput = inputs[inputs.indexOf(document.activeElement) + 1] //get index of input after the current input
nextInput.focus() //focus new input
}
}
Moving into the world of 3D if you want to check if a 3D point is in a Unit Sphere you end up doing something similar. All that is needed to work in 2D is to use 2D vector operations.
public static bool Intersects(Vector3 point, Vector3 center, float radius)
{
Vector3 displacementToCenter = point - center;
float radiusSqr = radius * radius;
bool intersects = displacementToCenter.magnitude < radiusSqr;
return intersects;
}
Very slightly tweaking Slipp's awesome answer, you can use his aliases to log just one branch:
[alias]
lgBranch1 = log --graph --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(bold white)— %an%C(reset)%C(bold yellow)%d%C(reset)' --abbrev-commit --date=relative
lgBranch2 = log --graph --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(bold white)— %an%C(reset)' --abbrev-commit
lg = !"git lg1"
By leaving off the --all
you can now do
git lgBranch1 <branch name>
or even
git lgBranch1 --all
Something like this should do the trick:
$(document).ready(function() {
$('#toptitle').text(function(i, oldText) {
return oldText === 'Profil' ? 'New word' : oldText;
});
});
This only replaces the content when it is Profil
. See text
in the jQuery API.
In Kibana 6.5, you can generate CSV under the Share Tab -> CSV Reports.
The request will be queued. Once the CSV is generated, it will be available for download under Management -> Reporting
I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the "deleting" event to do the cleanup:
class User extends Eloquent
{
public function photos()
{
return $this->has_many('Photo');
}
// this is a recommended way to declare event handlers
public static function boot() {
parent::boot();
static::deleting(function($user) { // before delete() method call this
$user->photos()->delete();
// do the rest of the cleanup...
});
}
}
You should probably also put the whole thing inside a transaction, to ensure the referential integrity..
Some thoughts on the BitmapDecode example... Basically it uses the ancient, but rather featureless Movie class from android.graphics. On recent API versions you need to turn off hardware acceleration, as described here. It was segfaulting for me otherwise.
<activity
android:hardwareAccelerated="false"
android:name="foo.GifActivity"
android:label="The state of computer animation 2014">
</activity>
Here is the BitmapDecode example shortened with only the GIF part. You have to make your own Widget (View) and draw it by yourself. Not quite as powerful as an ImageView.
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.*;
import android.view.View;
public class GifActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GifView(this));
}
static class GifView extends View {
Movie movie;
GifView(Context context) {
super(context);
movie = Movie.decodeStream(
context.getResources().openRawResource(
R.drawable.some_gif));
}
@Override
protected void onDraw(Canvas canvas) {
if (movie != null) {
movie.setTime(
(int) SystemClock.uptimeMillis() % movie.duration());
movie.draw(canvas, 0, 0);
invalidate();
}
}
}
}
2 other methods, one with ImageView another with WebView can be found in this fine tutorial. The ImageView method uses the Apache licensed android-gifview from Google Code.
I ran into the same issue and couldn't decide between laughing or smashing my head on the table when I read this error...
What git really tries to tell you: "You are already in a merge state and need to resolve the conflicts there first!"
You tried a merge and a conflict occured. Then, git stays in the merge state and if you want to resolve the merge with other commands git thinks you want to execute a new merge and so it tells you you can't do this because of your current unmerged files...
You can leave this state with git merge --abort
and now try to execute other commands.
In my case I tried a pull and wanted to resolve the conflicts by hand when the error occured...
Wikipedia has the following information about USING
:
The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the case above, there will be a single DepartmentID column and no employee.DepartmentID or department.DepartmentID.
Tables that it was talking about:
The Postgres documentation also defines them pretty well:
The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true.
The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.
Furthermore, the output of JOIN USING suppresses redundant columns: there is no need to print both of the matched columns, since they must have equal values. While JOIN ON produces all columns from T1 followed by all columns from T2, JOIN USING produces one output column for each of the listed column pairs (in the listed order), followed by any remaining columns from T1, followed by any remaining columns from T2.
For port 80 (which was the original question), Daniel is exactly right. I recently moved to https
and had to switch from iptables
to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I
Created an SSL Certificate Signing Request (CSR) via OpenSSL
openssl genrsa 2048 > private-key.pem
openssl req -new -key private-key.pem -out csr.pem
Changed the location
in /etc/nginx/conf.d/example_ssl.conf
to
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Real-IP $remote_addr;
}
Formatted the cert for nginx by cat
-ing the individual certs together and linked to it in my nginx example_ssl.conf
file (and uncommented stuff, got rid of 'example' in the name,...)
ssl_certificate /etc/nginx/ssl/cert_bundle.cert;
ssl_certificate_key /etc/nginx/ssl/private-key.pem;
Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.
foreach ($all_address as $aa) {
$mail->AddAddress($aa);
}
The problem is somewhere else in your code, because this works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
and testing your approach, which uses a vector iterator also works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
cout << *it << endl;
}
Again, your problem is somewhere else. Maybe what you think is a \t
character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.
Output:
* size of the vector: 3
test
test2
test3
in my case just
const myReducers = combineReducers({
user: UserReducer
});
const store: any = createStore(
myReducers,
applyMiddleware(thunk)
);
shallow(<Login />, { context: { store } });