Let me offer a textbook definition on "clustering index", which is taken from 15.6.1 from Database Systems: The Complete Book:
We may also speak of clustering indexes, which are indexes on an attribute or attributes such that all of tuples with a fixed value for the search key of this index appear on roughly as few blocks as can hold them.
To understand the definition, let's take a look at Example 15.10 provided by the textbook:
A relation
R(a,b)
that is sorted on attributea
and stored in that order, packed into blocks, is surely clusterd. An index ona
is a clustering index, since for a givena
-value a1, all the tuples with that value fora
are consecutive. They thus appear packed into blocks, execept possibly for the first and last blocks that containa
-value a1, as suggested in Fig.15.14. However, an index on b is unlikely to be clustering, since the tuples with a fixedb
-value will be spread all over the file unless the values ofa
andb
are very closely correlated.
Note that the definition does not enforce the data blocks have to be contiguous on the disk; it only says tuples with the search key are packed into as few data blocks as possible.
A related concept is clustered relation. A relation is "clustered" if its tuples are packed into roughly as few blocks as can possibly hold those tuples. In other words, from a disk block perspective, if it contains tuples from different relations, then those relations cannot be clustered (i.e., there is a more packed way to store such relation by swapping the tuples of that relation from other disk blocks with the tuples the doesn't belong to the relation in the current disk block). Clearly, R(a,b)
in example above is clustered.
To connect two concepts together, a clustered relation can have a clustering index and nonclustering index. However, for non-clustered relation, clustering index is not possible unless the index is built on top of the primary key of the relation.
"Cluster" as a word is spammed across all abstraction levels of database storage side (three levels of abstraction: tuples, blocks, file). A concept called "clustered file", which describes whether a file (an abstraction for a group of blocks (one or more disk blocks)) contains tuples from one relation or different relations. It doesn't relate to the clustering index concept as it is on file level.
However, some teaching material likes to define clustering index based on the clustered file definition. Those two types of definitions are the same on clustered relation level, no matter whether they define clustered relation in terms of data disk block or file. From the link in this paragraph,
An index on attribute(s) A on a file is a clustering index when: All tuples with attribute value A = a are stored sequentially (= consecutively) in the data file
Storing tuples consecutively is the same as saying "tuples are packed into roughly as few blocks as can possibly hold those tuples" (with minor difference on one talking about file, the other talking about disk). It's because storing tuple consecutively is the way to achieve "packed into roughly as few blocks as can possibly hold those tuples".
Clustered indexes are stored physically on the table. This means they are the fastest and you can only have one clustered index per table.
Non-clustered indexes are stored separately, and you can have as many as you want.
The best option is to set your clustered index on the most used unique column, usually the PK. You should always have a well selected clustered index in your tables, unless a very compelling reason--can't think of a single one, but hey, it may be out there--for not doing so comes up.
A comparison of a non-clustered index with a clustered index with an example
As an example of a non-clustered index, let’s say that we have a non-clustered index on the EmployeeID column. A non-clustered index will store both the value of the
EmployeeID
AND a pointer to the row in the Employee table where that value is actually stored. But a clustered index, on the other hand, will actually store the row data for a particular EmployeeID – so if you are running a query that looks for an EmployeeID of 15, the data from other columns in the table like
EmployeeName, EmployeeAddress, etc
. will all actually be stored in the leaf node of the clustered index itself.
This means that with a non-clustered index extra work is required to follow that pointer to the row in the table to retrieve any other desired values, as opposed to a clustered index which can just access the row directly since it is being stored in the same order as the clustered index itself. So, reading from a clustered index is generally faster than reading from a non-clustered index.
still alloca use is discouraged, why?
I don't perceive such a consensus. Lots of strong pros; a few cons:
while
or for
loop) or in several scopes, the memory accumulates per iteration/scope and is not released until the function exits: this contrasts with normal variables defined in the scope of a control structure (e.g. for {int i = 0; i < 2; ++i) { X }
would accumulate alloca
-ed memory requested at X, but memory for a fixed-sized array would be recycled per iteration).inline
functions that call alloca
, but if you force them then the alloca
will happen in the callers' context (i.e. the stack won't be released until the caller returns)alloca
transitioned from a non-portable feature/hack to a Standardised extension, but some negative perception may persistmalloc
's explicit controlmalloc
encourages thinking about the deallocation - if that's managed through a wrapper function (e.g. WonderfulObject_DestructorFree(ptr)
), then the function provides a point for implementation clean up operations (like closing file descriptors, freeing internal pointers or doing some logging) without explicit changes to client code: sometimes it's a nice model to adopt consistently
WonderfulObject* p = WonderfulObject_AllocConstructor();
- that's possible when the "constructor" is a function returning malloc
-ed memory (as the memory remains allocated after the function returns the value to be stored in p
), but not if the "constructor" uses alloca
WonderfulObject_AllocConstructor
could achieve this, but "macros are evil" in that they can conflict with each other and non-macro code and create unintended substitutions and consequent difficult-to-diagnose problemsfree
operations can be detected by ValGrind, Purify etc. but missing "destructor" calls can't always be detected at all - one very tenuous benefit in terms of enforcement of intended usage; some alloca()
implementations (such as GCC's) use an inlined macro for alloca()
, so runtime substitution of a memory-usage diagnostic library isn't possible the way it is for malloc
/realloc
/free
(e.g. electric fence)On many systems alloca() cannot be used inside the list of arguments of a function call, because the stack space reserved by alloca() would appear on the stack in the middle of the space for the function arguments.
I know this question is tagged C, but as a C++ programmer I thought I'd use C++ to illustrate the potential utility of alloca
: the code below (and here at ideone) creates a vector tracking differently sized polymorphic types that are stack allocated (with lifetime tied to function return) rather than heap allocated.
#include <alloca.h>
#include <iostream>
#include <vector>
struct Base
{
virtual ~Base() { }
virtual int to_int() const = 0;
};
struct Integer : Base
{
Integer(int n) : n_(n) { }
int to_int() const { return n_; }
int n_;
};
struct Double : Base
{
Double(double n) : n_(n) { }
int to_int() const { return -n_; }
double n_;
};
inline Base* factory(double d) __attribute__((always_inline));
inline Base* factory(double d)
{
if ((double)(int)d != d)
return new (alloca(sizeof(Double))) Double(d);
else
return new (alloca(sizeof(Integer))) Integer(d);
}
int main()
{
std::vector<Base*> numbers;
numbers.push_back(factory(29.3));
numbers.push_back(factory(29));
numbers.push_back(factory(7.1));
numbers.push_back(factory(2));
numbers.push_back(factory(231.0));
for (std::vector<Base*>::const_iterator i = numbers.begin();
i != numbers.end(); ++i)
{
std::cout << *i << ' ' << (*i)->to_int() << '\n';
(*i)->~Base(); // optionally / else Undefined Behaviour iff the
// program depends on side effects of destructor
}
}
Can also be thought of as the number of ways of choosing pairs of nodes n choose 2 = n(n-1)/2. True if only any pair can have only one edge. Multiply by 2 otherwise
Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)
SQL*Plus
and login as SYSTEM
. You should know what password you’ve used during the installation of Oracle DB XE.alter system set processes=150 scope=spfile;
in SQL*PlusFrom here:
Still not sure the answer, but a possible workaround is
import * as Chart from 'chart.js';
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
You can use importlib to import modules where you want to import a module from a folder using a string like so:
import importlib
scriptName = 'Snake'
script = importlib.import_module('Scripts\\.%s' % scriptName)
This example has a main.py which is the above code then a folder called Scripts and then you can call whatever you need from this folder by changing the scriptName
variable. You can then use script
to reference to this module. such as if I have a function called Hello()
in the Snake module you can run this function by doing so:
script.Hello()
I have tested this in Python 3.6
cordova achieve this. I still can not figure out how cordova did. It does not even go through shouldInterceptRequest.
Later I found out that the key to load any file from local is: myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
And when you want to access any http resource, the webview will do checking with OPTIONS method, which you can grant the access through WebViewClient.shouldInterceptRequest by return a response, and for the following GET/POST method, you can just return null.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
A modified version of above to make it more dynamic.
Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
On Error GoTo Failed
Dim WinHttpReq As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URL, False, Username, Password
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Dim oStream As Object: Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
oStream.Close
DownloadFileB = Len(Dir(DownloadPath)) > 0
Exit Function
End If
Failed:
DownloadFileB = False
End Function
When I want class with full functionality, e.g. there are many methods and variables, I use singleton;
If I want class with only one or two methods in it, e.g. MailService class, which has only 1 method SendMail() I use static class and method.
No, == between Integer, Long etc will check for reference equality - i.e.
Integer x = ...;
Integer y = ...;
System.out.println(x == y);
this will check whether x
and y
refer to the same object rather than equal objects.
So
Integer x = new Integer(10);
Integer y = new Integer(10);
System.out.println(x == y);
is guaranteed to print false
. Interning of "small" autoboxed values can lead to tricky results:
Integer x = 10;
Integer y = 10;
System.out.println(x == y);
This will print true
, due to the rules of boxing (JLS section 5.1.7). It's still reference equality being used, but the references genuinely are equal.
If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.
Personally I'd use:
if (x.intValue() == y.intValue())
or
if (x.equals(y))
As you say, for any comparison between a wrapper type (Integer
, Long
etc) and a numeric type (int
, long
etc) the wrapper type value is unboxed and the test is applied to the primitive values involved.
This occurs as part of binary numeric promotion (JLS section 5.6.2). Look at each individual operator's documentation to see whether it's applied. For example, from the docs for ==
and !=
(JLS 15.21.1):
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).
and for <
, <=
, >
and >=
(JLS 15.20.1)
The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.
Note how none of this is considered as part of the situation where neither type is a numeric type.
You could also repeat "0", prepend it to str(n)
and get the rightmost width slice. Quick and dirty little expression.
def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
.content .right{
overflow: auto;
background-color: red;
}
+1 for Merkuro, but if the size of the float changes your fixed margin will fail.
If u use above CSS on the right div
it will nicely change size with changing size on the left float. It is a bit more flexible like that.
Check the fiddle here: http://jsfiddle.net/9ZHBK/144/
For git mv
the
manual page
says
The index is updated after successful completion, […]
So, at first, you have to update the index on your own
(by using git add mobile.css
). However
git status
will still show two different files
$ git status
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# new file: mobile.css
#
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: iphone.css
#
You can get a different output by running
git commit --dry-run -a
, which results in what you
expect:
Tanascius@H181 /d/temp/blo (master)
$ git commit --dry-run -a
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# renamed: iphone.css -> mobile.css
#
I can't tell you exactly why we see these differences
between git status
and
git commit --dry-run -a
, but
here is a hint from
Linus:
git really doesn't even care about the whole "rename detection" internally, and any commits you have done with renames are totally independent of the heuristics we then use to show the renames.
A dry-run
uses the real renaming mechanisms, while a
git status
probably doesn't.
id="hiddenBtn"
and type="submit"
that do the submittype="button"
set onclick
of the current button call a function
look like below:
function foo() {
// do something before submit
...
// trigger click event of the hidden button
$('#hinddenBtn').trigger("click");
}
At first you must consider that if your activity which I called A extends another activity (B) and in both of
them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.
For some time I was really annoyed by the fact that matplotlib doesn't generate colormaps with random colors, as this is a common need for segmentation and clustering tasks.
By just generating random colors we may end with some that are too bright or too dark, making visualization difficult. Also, usually we need the first or last color to be black, representing the background or outliers. So I've wrote a small function for my everyday work
Here's the behavior of it:
new_cmap = rand_cmap(100, type='bright', first_color_black=True, last_color_black=False, verbose=True)
Than you just use new_cmap as your colormap on matplotlib:
ax.scatter(X,Y, c=label, cmap=new_cmap, vmin=0, vmax=num_labels)
The code is here:
def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True):
"""
Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks
:param nlabels: Number of labels (size of colormap)
:param type: 'bright' for strong colors, 'soft' for pastel colors
:param first_color_black: Option to use first color as black, True or False
:param last_color_black: Option to use last color as black, True or False
:param verbose: Prints the number of labels and shows the colormap. True or False
:return: colormap for matplotlib
"""
from matplotlib.colors import LinearSegmentedColormap
import colorsys
import numpy as np
if type not in ('bright', 'soft'):
print ('Please choose "bright" or "soft" for type')
return
if verbose:
print('Number of labels: ' + str(nlabels))
# Generate color map for bright colors, based on hsv
if type == 'bright':
randHSVcolors = [(np.random.uniform(low=0.0, high=1),
np.random.uniform(low=0.2, high=1),
np.random.uniform(low=0.9, high=1)) for i in xrange(nlabels)]
# Convert HSV list to RGB
randRGBcolors = []
for HSVcolor in randHSVcolors:
randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Generate soft pastel colors, by limiting the RGB spectrum
if type == 'soft':
low = 0.6
high = 0.95
randRGBcolors = [(np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high)) for i in xrange(nlabels)]
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Display colorbar
if verbose:
from matplotlib import colors, colorbar
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))
bounds = np.linspace(0, nlabels, nlabels + 1)
norm = colors.BoundaryNorm(bounds, nlabels)
cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,
boundaries=bounds, format='%1i', orientation=u'horizontal')
return random_colormap
It's also on github: https://github.com/delestro/rand_cmap
Explicit Merge: Creates a new merge commit. (This is what you will get if you used --no-ff
.)
Fast Forward Merge: Forward rapidly, without creating a new commit:
Rebase: Establish a new base level:
Squash: Crush or squeeze (something) with force so that it becomes flat:
You can just say
callback();
Alternately you can use the call
method if you want to adjust the value of this
within the callback.
callback.call( newValueForThis);
Inside the function this
would be whatever newValueForThis
is.
Did you check the gsl
package in your system. Try with this:
ldconfig-p | grep gsl
If gsl
is installed, it will display the configuration path. If it is not in the standard path /usr/lib/
then you need to do the following in bash:
export PATH=$PATH:/your/path/to/gsl-config
If gsl
is not installed, simply do
sudo apt-get install libgsl0ldbl
sudo apt-get install gsl-bin libgsl0-dev
I had a problem with the mvabund
package and this fixed the error
Cheers!
This is a for loop, but maintains the object reference in the loop just like a forEach() but you can break out.
var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
if(el === 1) break;
}
As others recommend, you can use Oracle SQL Developer. You can point to the location of the script to run it, as described. A slightly simpler method, though, is to just use drag-and-drop:
Seems like serialize is the one I'm going to use for 2 reasons:
Someone pointed out that unserialize is faster than json_decode and a 'read' case sounds more probable than a 'write' case.
I've had trouble with json_encode when having strings with invalid UTF-8 characters. When that happens the string ends up being empty causing loss of information.
foreach my $arg (@ARGV) {
print $arg, "\n";
}
will print each argument.
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault
is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault
returns the key you can combine these into a single line:
a.setdefault("somekey",[]).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict
methods, in particular the get()
method, and do some experiments to get comfortable with this.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
I think the officially preferred way is now to use Less, and either dynamically override the bootstrap.css (using less.js), or recompile bootstrap.css (using Node or the Less compiler).
From the Bootstrap docs, here's how to override bootstrap.css styles dynamically:
Download the latest Less.js and include the path to it (and Bootstrap) in the
<head>
.<link rel="stylesheet/less" href="/path/to/bootstrap.less"> <script src="/path/to/less.js"></script>
To recompile the .less files, just save them and reload your page. Less.js compiles them and stores them in local storage.
Or if you prefer to statically compile a new bootstrap.css with your custom styles (for production environments):
Install the LESS command line tool via Node and run the following command:
$ lessc ./less/bootstrap.less > bootstrap.css
Since Server.MapPath()
does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:
string AppContext.BaseDirectory { get;}
You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \
and not /
like they are in mvc.
Ex:
System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");
returns true- positing that this is a sound path in your example
You need the :not()
selector:
$('div[class^="first-"]:not(.first-bar)')
or, alternatively, the .not()
method:
$('div[class^="first-"]').not('.first-bar');
The accepted answer is awesome, it properly explains the difference between string vs text (mostly the limit size in the database, but there are a few other gotchas), but I wanted to point out a small issue that got me through it as that answer didn't completely do it for me.
The max size :limit => 1 to 4294967296 didn't work exactly as put, I needed to go -1 from that max size. I'm storing large JSON blobs and they might be crazy huge sometimes.
Here's my migration with the larger value in place with the value MySQL doesn't complain about.
Note the 5 at the end of the limit instead of 6
class ChangeUserSyncRecordDetailsToText < ActiveRecord::Migration[5.1]
def up
change_column :user_sync_records, :details, :text, :limit => 4294967295
end
def down
change_column :user_sync_records, :details, :string, :limit => 1000
end
end
I wouldn't call the class the same (aside from casing) as the constant ... I would have at a minimum one class of "Settings", or "Values", or "Constants", where all the constants would live. If I have a large number of them, I'd group them up in logical constant classes (UserSettings, AppSettings, etc.)
"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.
You can use JavaScript/Canvas to do the job but it is still experimental.
It's also very possible that typing show create table <table_name>
in the hive cli will give you the exact location of your hive table.
You could use the xpath :
//div[@class="measure-tab" and .//span[contains(., "someText")]]
Input :
<root>
<div class="measure-tab">
<td> someText</td>
</div>
<div class="measure-tab">
<div>
<div2>
<span>someText2</span>
</div2>
</div>
</div>
</root>
Output :
Element='<div class="measure-tab">
<div>
<div2>
<span>someText2</span>
</div2>
</div>
</div>'
I had to solve the same issue and this is what I used as solution.
To use this solution the source and destination table must be identical, and the must have an id unique and autoincrement in first table (so that the same id is never reused).
Lets say table1 and table2 have this structure
|id|field1|field2
You can make those two query :
INSERT INTO table2 SELECT * FROM table1 WHERE
DELETE FROM table1 WHERE table1.id in (SELECT table2.id FROM table2)
If one needs to create a table (with an empty structure) just to EXCHANGE PARTITION, it is best to use the "..FOR EXCHANGE.." clause. It's available only from Oracle version 12.2 onwards though.
CREATE TABLE t1_temp FOR EXCHANGE WITH TABLE t1;
This addresses 'ORA-14097' during the 'exchange partition' seamlessly if table structures are not exactly copied by normal CTAS operation. I have seen Oracle missing some of the "DEFAULT" column and "HIDDEN" columns definitions from the original table.
ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION
Use svn log
command to find out which revisions are available:
svn log
Which prints:
------------------------------------------------------------------------
r762 | machines | 2012-12-02 13:00:16 -0500 (Sun, 02 Dec 2012) | 2 lines
------------------------------------------------------------------------
r761 | machines | 2012-12-02 12:59:40 -0500 (Sun, 02 Dec 2012) | 2 lines
Note the number r761
. Here is the command description:
svn export http://url-to-your-file@761 /tmp/filename
I used this command specifically:
svn export svn+ssh://[email protected]/home1/oct/calc/calcFeatures.m@761 calcFeatures.m
Which causes calcFeatures.m revision 761 to be checked out to the current directory.
select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));
The ::int
conversion follows the principle of rounding.
If you want a different result such as rounding down, you can use the corresponding math function such as floor
.
If the goal simply is to list all computer objects with an empty description attribute try this
import-module activedirectory
$domain = "domain.example.com"
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }
You need to include the appropriate header
#include <stdio.h>
If you're not sure which header a standard function is defined in, the function's man page will state this.
There is also bind_rows(x, ...)
in dplyr
.
> system.time({ df.Base <- do.call("rbind", listOfDataFrames) })
user system elapsed
0.08 0.00 0.07
>
> system.time({ df.dplyr <- as.data.frame(bind_rows(listOfDataFrames)) })
user system elapsed
0.01 0.00 0.02
>
> identical(df.Base, df.dplyr)
[1] TRUE
Selected answer and some others are all good. I just want give a more SQL pure explanation. It comes to same solution that there is no (valid) database owner.
Database owner account dbo
which is mentioned in error is always created with database. So it seems strange that it doesn't exist but you can check with two selects (or one but let's keep it simple).
SELECT [name],[sid]
FROM [DB_NAME].[sys].[database_principals]
WHERE [name] = 'dbo'
which shows SID of dbo
user in DB_NAME database and
SELECT [name],[sid]
FROM [sys].[syslogins]
to show all logins (and their SIDs) for this SQL server instance. Notice it didn't write any db_name prefix, that's because every database has same information in that view.
So in case of error above there will not be login with SID that is assigned to database dbo user.
As explained above that usually happens when restoring database from another computer (where database and dbo user were created by different login). And you can fix it by changing ownership to existing login.
Why don't you use PowerShell?
Stop-Process -Name notepad
And if you are in a batch file:
powershell -Command "Stop-Process -Name notepad"
powershell -Command "Stop-Process -Id 4232"
There is a much easier way to compile and run C code using GCC, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.Moreover you could update the config in settings.json using different C compilers as you want, the default config for C is as below:
"code-runner.executorMap": {
"c": "gcc $fullFileName && ./a.out"
}
I usually create these two helper functions when using date inputs:
// date is expected to be a date object (e.g., new Date())
const dateToInput = date =>
`${date.getFullYear()
}-${('0' + (date.getMonth() + 1)).slice(-2)
}-${('0' + date.getDate()).slice(-2)
}`;
// str is expected in yyyy-mm-dd format (e.g., "2017-03-14")
const inputToDate = str => new Date(str.split('-'));
You can then set the date input value as:
$('#datePicker').val(dateToInput(new Date()));
And retrieve the selected value like so
const dateVal = inputToDate($('#datePicker').val())
I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:
<Directory "/Applications/MAMP/bin/mamp">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
You need to change: AllowOverride None To: AllowOverride All
One trick I found helpful for large data use cases is to reduce the volume of the data by reducing float precision to 32-bit. It's not applicable in all cases, but in many applications 64-bit precision is overkill and the 2x memory savings are worth it. To make an obvious point even more obvious:
>>> df = pd.DataFrame(np.random.randn(int(1e8), 5))
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100000000 entries, 0 to 99999999
Data columns (total 5 columns):
...
dtypes: float64(5)
memory usage: 3.7 GB
>>> df.astype(np.float32).info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100000000 entries, 0 to 99999999
Data columns (total 5 columns):
...
dtypes: float32(5)
memory usage: 1.9 GB
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
I have just installed mongodb 3.4 with homebrew.(brew install mongodb) It looks for /data/db by default.
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
Just came up with this solution, no VBA needed;
Find the last occurance of "_" in my example;
=IFERROR(FIND(CHAR(1);SUBSTITUTE(A1;"_";CHAR(1);LEN(A1)-LEN(SUBSTITUTE(A1;"_";"")));0)
Explained inside out;
SUBSTITUTE(A1;"_";"") => replace "_" by spaces
LEN( *above* ) => count the chars
LEN(A1)- *above* => indicates amount of chars replaced (= occurrences of "_")
SUBSTITUTE(A1;"_";CHAR(1); *above* ) => replace the Nth occurence of "_" by CHAR(1) (Nth = amount of chars replaced = the last one)
FIND(CHAR(1); *above* ) => Find the CHAR(1), being the last (replaced) occurance of "_" in our case
IFERROR( *above* ;"0") => in case no chars were found, return "0"
Hope this was helpful.
If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.
String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}
--parents
is copying the directory structure, so you should get rid of that.
The way you've written this, the find
executes, and the output is put onto the command line such that cp
can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like
$ find . -name \*.xls -exec cp {} newDir \;
in which cp
is executed for each filename that find
finds, and passed the filename correctly. Here's more info on this technique.
Instead of all the above, you could use zsh and simply type
$ cp **/*.xls target_directory
zsh
can expand wildcards to include subdirectories and makes this sort of thing very easy.
Use Let's Encrypt via Greenlock.js
I noticed that none of these answers show that adding a Intermediate Root CA to the chain, here are some zero-config examples to play with to see that:
Snippet:
var options = {
// this is the private key only
key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))
// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))
// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};
var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
var insecureServer = http.createServer();
server.listen(80, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
This is one of those things that's often easier if you don't try to do it directly through connect or express, but let the native https
module handle it and then use that to serve you connect / express app.
Also, if you use server.on('request', app)
instead of passing the app when creating the server, it gives you the opportunity to pass the server
instance to some initializer function that creates the connect / express app (if you want to do websockets over ssl on the same server, for example).
Here is example for list of Objects
Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));
So i just found a solution for that: In the hover animation do this:
animation: hover 1s infinite alternate ease-in-out,splash 1;
Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild
Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).
Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.
Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.
Publish to File System
The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.
This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:
<Target Name="PublishToFileSystem"
DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
<Error Condition="'$(PublishDestination)'==''"
Text="The PublishDestination property must be set to the intended publishing destination." />
<MakeDir Condition="!Exists($(PublishDestination))"
Directories="$(PublishDestination)" />
<ItemGroup>
<PublishFiles Include="$(_PackageTempDir)\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PublishFiles)"
DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="True" />
</Target>
This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.
The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.
We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).
To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):
msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem
The package "tictoc" gives you a very simple way of measuring execution time. The documentation is in: https://cran.fhcrc.org/web/packages/tictoc/tictoc.pdf.
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
toc()
To save the elapsed time into a variable you can do:
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
exectime <- toc()
exectime <- exectime$toc - exectime$tic
var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
SlectedList.push($(this).val());
});
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder
, but it does what you asked.
Better technique (although still not ideal):
StringBuilder
.StringBuilder
when you're done.This will turn an O(n²) solution into O(n).
To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:
MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );
MSDN references:
from datetime import datetime
datetime.strptime(date_string, "%Y-%m-%d")
..this raises a ValueError
if it receives an incompatible format.
..if you're dealing with dates and times a lot (in the sense of datetime objects, as opposed to unix timestamp floats), it's a good idea to look into the pytz module, and for storage/db, store everything in UTC.
<head>
<style>
#circle{
width:200px;
height:200px;
border-radius:100px;
background-color:red;
}
</style>
</head>
<body>
<div id="circle"></div>
</body>
simple and novice :)
You can do some pretty neat stuff once you understand that you can play with inheritance with this. However first let's understand something from this doc on background:
With CSS3, you can apply multiple backgrounds to elements. These are layered atop one another with the first background you provide on top and the last background listed in the back. Only the last background can include a background color.
So when one do:
background: red;
He is setting the background-color to red because red is the last value listed.
When one do:
background: linear-gradient(to right, grey 50%, yellow 2%) red;
Red is the background color once again BUT you will see a gradient.
.box{_x000D_
border-radius: 50%;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: linear-gradient(to right, grey 50%, yellow 2%) red;_x000D_
}_x000D_
_x000D_
.box::before{_x000D_
content: "";_x000D_
display: block;_x000D_
margin-left: 50%;_x000D_
height: 50%;_x000D_
border-radius: 0 100% 100% 0 / 50%;_x000D_
transform: translateX(70px) translateY(-26px) rotate(325deg);_x000D_
background: inherit;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
Now the same thing with background-color:
.box{_x000D_
border-radius: 50%;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: linear-gradient(to right, grey 50%, yellow 2%) red;_x000D_
}_x000D_
_x000D_
.box::before{_x000D_
content: "";_x000D_
display: block;_x000D_
margin-left: 50%;_x000D_
height: 50%;_x000D_
border-radius: 0 100% 100% 0 / 50%;_x000D_
transform: translateX(70px) translateY(-26px) rotate(325deg);_x000D_
background-color: inherit;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
The reason this happens is because when we are doing this :
background: linear-gradient(to right, grey 50%, yellow 2%) #red;
The last number sets the background-color.
Then in the before we are inheriting from background (then we get the gradient) or background color, then we get red.
You can use the FromStr
trait's from_str
method, which is implemented for i32
:
let my_num = i32::from_str("9").unwrap_or(0);
I had this issue today, and for me the problem was that I had allocated too much memory:
-Xmx1024M -XX:MaxPermSize=1024m
Once I reduced the PermGen space, everything worked fine:
-Xmx1024M -XX:MaxPermSize=512m
I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.
From https://stackoverflow.com/a/2434094/848072. You need a default constructor for T class.
import java.lang.reflect.ParameterizedType;
class Foo {
public bar() {
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
Class type = (Class) superClass.getActualTypeArguments()[0];
try {
T t = type.newInstance();
//Do whatever with t
} catch (Exception e) {
// Oops, no default constructor
throw new RuntimeException(e);
}
}
}
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r')
plt.gca().add_patch(circle1)
A quick condensed version of the accepted answer, to quickly plug a circle into an existing plot. Refer to the accepted answer and other answers to understand the details.
By the way:
gca()
means Get Current AxisJust to add this in, I ran into this same issue, but the supplied answers did not work. I fixed it by taking the exception's suggestion and adding to the application.properties file...
spring.jackson.serialization.fail-on-empty-beans=false
I'm using Spring Boot v1.3 with Hibernate 4.3
It now serializes the entire object and nested objects.
EDIT: 2018
Since this still gets comments I'll clarify here. This absolutely only hides the error. The performance implications are there. At the time, I needed something to deliver and work on it later (which I did via not using spring anymore). So yes, listen to someone else if you really want to solve the issue. If you just want it gone for now go ahead and use this answer. It's a terrible idea, but heck, might work for you. For the record, never had a crash or issue again after this. But it is probably the source of what ended up being a SQL performance nightmare.
In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.
See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.
In short, you'll need something like:
List<Conversation> actors = jdbcTemplate.query(
SELECT_ALL_CONVERSATIONS_SQL_FULL,
new Object[] {userId, dateFrom, dateTo},
new RowMapper<Conversation>() {
public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
Conversation c = new Conversation();
c.setId(rs.getLong(1));
c.setRoom(rs.getString(2));
[...]
return c;
}
});
This method uses the WindowOrWorkerGlobalScope.setInterval
(https://developer.mozilla.org/en-US/doc)
method to track the ready states of the document & see if the <body>
element exists.
// Function > Loader Screen Script
(function LoaderScreenScript(window = window, document = window.document, undefined = window.undefined || void 0) {
// Initialization > (Processing Time, Condition, Timeout, Loader (...))
let processingTime = 0,
condition = function() {
// Return
return document.body
},
timeout = function() {
// Return
return (processingTime * 1e3) / 2
},
loaderScreenFontSize = typeof window.loaderScreenFontSize != 'undefined' ? window.loaderScreenFontSize : 14,
loaderScreenMargin = typeof window.loaderScreenMargin != 'undefined' ? window.loaderScreenMargin : 10,
loaderScreenMessage = typeof window.loaderScreenMessage != 'undefined' ? window.loaderScreenMessage : 'Loading, please wait…',
loaderScreenOpacity = typeof window.loaderScreenOpacity != 'undefined' ? window.loaderScreenOpacity : .75,
loaderScreenTransition = typeof window.loaderScreenTransition != 'undefined' ? window.loaderScreenTransition : .675,
loaderScreenWidth = typeof window.loaderScreenWidth != 'undefined' ? window.loaderScreenWidth : 7.5;
// Function > Update
function update() {
// Set Timeout
setTimeout(function() {
// Initialization > (Data, Metadata)
var data = document.createElement('loader-screen-element'),
metadata = setInterval(function() {
/* Logic
[if:else if:else statement]
*/
if (document.readyState == 'complete') {
// Alpha
alpha();
// Test
test()
}
});
// Insertion
document.body.appendChild(data);
// Style > <body> > Overflow
document.body.style = ('overflow: hidden !important; pointer-events: none !important; user-drag: none !important; user-select: none !important;' + (document.body.getAttribute('style') || ' ')).trim();
// Modification > Data
// Inner HTML
data.innerHTML =
'<style media=all type=text/css>' +
'body::selection {' +
'background-color: transparent !important;' +
'text-shadow: none !important' +
'} ' +
'@keyframes rotate {' +
'0% { transform: rotate(0) }' +
'to { transform: rotate(360deg) }' +
'}' +
'</style>' +
"<div style='animation: rotate 1s ease-in-out 0s infinite backwards; border: " + loaderScreenWidth + "px solid rgba(0, 0, 0, " + loaderScreenOpacity + "); border-top-color: rgba(0, 51, 255, " + loaderScreenOpacity + "); border-radius: 50%; height: 75px; margin: 0 auto; margin-bottom: " + loaderScreenMargin + "px; width: 75px'> </div>" +
"<small style='color: rgba(127, 127, 127, .675); font-family: \"Open Sans\", \"Calibri Light\", Calibri, sans-serif; font-size: " + loaderScreenFontSize + "px !important; margin: 0 auto; margin-top: " + loaderScreenMargin + "px; text-align: center'> " + loaderScreenMessage + " </small>";
// Style
data.style = 'align-items: center; background-color: rgba(255, 255, 255, .98); display: flex; flex-direction: column; height: ' + innerHeight + 'px; justify-content: center; left: 0; margin: auto; max-height: 100% !important; max-width: 100% !important; min-height: 100vh; min-width: 100vh; position: fixed; top: 0; transition: ' + loaderScreenTransition + 's ease-in-out; width: ' + innerWidth + 'px; z-index: 2147483647';
// Function
// Alpha
function alpha() {
// Clear Interval
clearInterval(metadata)
};
// Test
function test() {
// Style > Data
// Background Color
data.style.backgroundColor = 'transparent';
// Opacity
data.style.opacity = 0;
// Set Timeout
setTimeout(function() {
// Deletion
data.remove();
// Modification > <body> > Style
document.body.style = document.body.getAttribute('style').replace('overflow: hidden !important;', '').replace('pointer-events: none !important;', '').replace('user-drag: none !important;', '').replace('user-select: none !important;', '');
(document.body.getAttribute('style') || '').trim() || document.body.removeAttribute('style')
}, ((+getComputedStyle(data).getPropertyValue('animation-delay').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('animation-duration').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('transition-delay').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('transition-duration').replace(/[a-zA-Z]/g, '').trim()) * 1e3) + 100);
}
}, timeout())
};
/* Logic
[if:else if:else statement]
*/
if (condition())
// Update
update();
else {
// Initialization > Data
var data = setInterval(function() {
/* Logic
[if:else if:else statement]
*/
if (condition()) {
// Update > Processing Time
processingTime += 1;
// Update
update();
// Metadata
metadata()
}
});
// Function > Metadata
function metadata() {
// Clear Interval
clearInterval(data);
/* Logic
[if:else if:else statement]
> Deletion
*/
if ('data' in window && typeof data == 'undefined')
delete window.data
}
}
})(window, window.document, window.undefined || void 0)
This pre-loading screen was made by Lapys @ https://github.com/LapysDev
This error can be caused by trying to end a response more than once. As other answers already mentioned, there are various methods that will end a response (like Response.End
, or Response.Redirect
). If you call more than one in a row, you'll get this error.
I came across this error when I tried to use Response.End
after using Response.TransmitFile
which seems to end the response too.
if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there
If you write it as the following in SQL server then there would be no danger of wiping the database table unless all of the values in that table happen to actually be between those values:
DELETE FROM [dbo].[TableName] WHERE [TableName].[IdField] BETWEEN 79 AND 296
It seems as the Chrome debugger loads source files into memory and wont let them go despite of browser cache updates, i.e. it has its own cache apart from the browser cache that is not in sync. At least, this is the case when working with source mapped files (I am debugging typescript sources). After successfully refreshing browser cache and validating that by browsing directly to the source file, you download the updated file, but as soon as you reopen the file in the debugger it will keep returning the old file no matter the version from the ordinary browser cache. Very anoying indeed.
I would consider this a bug in chrome. I use version Version 46.0.2490.71 m.
The only thing that helps, is restarting chrome (close down all chrome browsers).
Also DevExpress have Charts (see DevExpress.Com).
$date = mysql_real_escape_string($_POST['intake_date']);
1. If your MySQL column is DATE
type:
$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
2. If your MySQL column is DATETIME
type:
$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));
You haven't got to work strototime()
, because it will not work with dash -
separators, it will try to do a subtraction.
Update, the way your date is formatted you can't use strtotime()
, use this code instead:
$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;
Output:
2009-07-02 00:07:00
IPython has profiles for configuration, located at ~/.ipython/profile_*
. The default profile is called profile_default
. Within this folder there are two primary configuration files:
ipython_config.py
ipython_kernel_config.py
Add the inline option for matplotlib to ipython_kernel_config.py
:
c = get_config()
# ... Any other configurables you want to set
c.InteractiveShellApp.matplotlib = "inline"
Usage of %pylab
to get inline plotting is discouraged.
It introduces all sorts of gunk into your namespace that you just don't need.
%matplotlib
on the other hand enables inline plotting without injecting your namespace. You'll need to do explicit calls to get matplotlib and numpy imported.
import matplotlib.pyplot as plt
import numpy as np
The small price of typing out your imports explicitly should be completely overcome by the fact that you now have reproducible code.
write.csv([enter name of dataframe here],file = file.choose(new = T))
After running above script this window will open :
Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.
I'm on node 10 and child process 1.0.2
. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.
const process = spawn("python", ["services/request.py", "https://www.google.com"])
return new Promise((resolve, reject) =>{
process.stdout.on("data", data =>{
resolve(data.toString()); // <------------ by default converts to utf-8
})
process.stderr.on("data", reject)
})
import urllib.request
import sys
def karl_morrison_is_a_pedant():
response = urllib.request.urlopen(sys.argv[1])
html = response.read()
print(html)
sys.stdout.flush()
karl_morrison_is_a_pedant()
p.s. not a contrived example since node's http module doesn't load a few requests I need to make
Make another div and add both 'dummy' and 'img-container' inside the div
Do HTML and CSS like follows
html , body {height:100%;}_x000D_
.responsive-container { height:100%; display:table; text-align:center; width:100%;}_x000D_
.inner-container {display:table-cell; vertical-align:middle;}
_x000D_
<div class="responsive-container">_x000D_
<div class="inner-container">_x000D_
<div class="dummy">Sample</div>_x000D_
<div class="img-container">_x000D_
Image tag_x000D_
</div>_x000D_
</div> _x000D_
</div>
_x000D_
Instead of 100% for the 'responsive-container' you can give the height that you want.,
You can use in swift 4 or 5
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let current_date_time = dateFormatter.string(from: date)
print("before add time-->",current_date_time)
//adding 5 miniuts
let addminutes = date.addingTimeInterval(5*60)
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let after_add_time = dateFormatter.string(from: addminutes)
print("after add time-->",after_add_time)
output:
before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15
Agree @Drixson Oseña: You should not write localhost/xampp/...., else write for e.g: localhost/mw-config/index.php
try as below
@ContextConfiguration (locations = "classpath*:/spring/applicationContext*.xml")
this will load all 3 of your application context xml file.
You can use it by using the StackTrace
and then you can get reflective types from that.
StackTrace stackTrace = new StackTrace(); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);
Basically I use Fiddler or Postman for testing API's.
In fiddler, in request header you need to specify instead of xml, html you need to change it to json.
Eg: Accept: application/json
. That should do the job.
This solution worked best for me. It uses jQuery and the iframe's ".load" event.
A list of all addresses is stored in a fact ansible_all_ipv4_addresses
, a default address in ansible_default_ipv4.address
.
---
- hosts: localhost
connection: local
tasks:
- debug: var=ansible_all_ipv4_addresses
- debug: var=ansible_default_ipv4.address
Then there are addresses assigned to each network interface... In such cases you can display all the facts and find the one that has the value you want to use.
hive> show partitions table_name;
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
For me the issue seems to have been caused by power failure. Restarting the server computer solved it.
You can use plain javascript Object class to achieve it, Object class has keys function which takes 1 argument as input as follows,
Object.keys(obj).length === 0
You can achieve it in 3 ways, 1) Current controller scope 2) Filter 3) $rootScope
1) First way is current controller scope,
$scope.isObjEmpty = function(obj){ return Object.keys(obj).length === 0; }
Then you can call the function from the view:
ng-show="!isObjEmpty(obj)" if you want to show and hide dom dynamically & ng-if="!isObjEmpty(obj)" if you want to remove or add dom dynamically.
2) The second way is a custom filter. Following code should work for the object & Array,
angular.module('angularApp')
.filter('isEmpty', [function () {
return function (obj) {
if (obj == undefined || obj == null || obj == '')
return true;
if (angular.isObject(obj))
return Object.keys(obj).length != 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
};
}]);
<div ng-hide="items | isEmpty"> Your content's goes here </div>
3) The third way is $rootScope, create a plain javascript function and add it in $rootScope server it will accessible default in all scopes and UI.
function isObjEmpty (obj){ return Object.keys(obj).length === 0; }
$rootScope.isObjEmpty = isObjEmpty ;
Add a inline wrapper.
<div style='display:flex'>
<form>
<p>Read this sentence</p>
<input type='submit' value='or push this button' />
</form>
<div>
<p>Message here</p>
</div>
I had the same issue. Running exec sp_updatestats
did work sometimes, but not always. I decided to use the NOLOCK
statement in my queries to speed up the queries.
Just add NOLOCK
after your FROM clause, e.g.:
SELECT clicks.entryURL, clicks.entryTime, sessions.userID
FROM sessions, clicks WITH (NOLOCK)
WHERE sessions.sessionID = clicks.sessionID AND clicks.entryTime > DATEADD(day, -1, GETDATE())
Read the full article here.
For MSVC you can use the linker.
link.exe /dump /linenumbers /disasm /out:foo.dis foo.dll
foo.pdb needs to be available to get symbols
you can use iframe within your modal form so when u open the iframe window it open inside your your modal form . i hope you are rendering to some pdf opener with some url , if u have the pdf contents simply add the contents in a div in the modal form .
What about Console.Readline();
?
I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;
It works and it's cross browser compatible.
Check out the code below, you probably get a better explanation:
jQuery('.close a, .bg', '#message').on('click', function() {_x000D_
jQuery('#message').fadeOut();_x000D_
return false;_x000D_
});
_x000D_
html, body {_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#message {_x000D_
height: 100%;_x000D_
left: 0;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#message .container {_x000D_
height: 60%;_x000D_
left: 50%;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
z-index: 10;_x000D_
width: 60%;_x000D_
}_x000D_
_x000D_
#message .container .text {_x000D_
background: #fff;_x000D_
height: 100%;_x000D_
left: -50%;_x000D_
position: absolute;_x000D_
top: -50%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#message .bg {_x000D_
background: rgba(0, 0, 0, 0.5);_x000D_
height: 100%;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
z-index: 9;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
<div class="container">_x000D_
<div class="text">_x000D_
<h2>Warning</h2>_x000D_
<p>The message</p>_x000D_
<p class="close"><a href="#">Close Window</a></p>_x000D_
</div>_x000D_
</div>_x000D_
<div class="bg"></div>_x000D_
</div>
_x000D_
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
AppDomain.UnhandledException Event
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.
public App()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.
For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.
So I did some speed comparisons to get the fastest way. List comprehensions are indeed very fast. The only way to get close is to avoid bytecode getting exectuded during construction of the list. My first attempt was the following method, which would appear to be faster in principle:
l = [[]]
for _ in range(n): l.extend(map(list,l))
(produces a list of length 2**n, of course) This construction is twice as slow as the list comprehension, according to timeit, for both short and long (a million) lists.
My second attempt was to use starmap to call the list constructor for me, There is one construction, which appears to run the list constructor at top speed, but still is slower, but only by a tiny amount:
from itertools import starmap
l = list(starmap(list,[()]*(1<<n)))
Interesting enough the execution time suggests that it is the final list call that is makes the starmap solution slow, since its execution time is almost exactly equal to the speed of:
l = list([] for _ in range(1<<n))
My third attempt came when I realized that list(()) also produces a list, so I tried the apperently simple:
l = list(map(list, [()]*(1<<n)))
but this was slower than the starmap call.
Conclusion: for the speed maniacs: Do use the list comprehension. Only call functions, if you have to. Use builtins.
This is a variant of the list comprehension answer given by @psun.
By switching the output value, you can actually extract the matching pattern from the list comprehension (something not possible with the any()
approach by @Lauritz-v-Thaulow)
extensionsToCheck = ['.pdf', '.doc', '.xls']
url_string = 'http://.../foo.doc'
print [extension for extension in extensionsToCheck if(extension in url_string)]
['.doc']`
You can furthermore insert a regular expression if you want to collect additional information once the matched pattern is known (this could be useful when the list of allowed patterns is too long to write into a single regex pattern)
print [re.search(r'(\w+)'+extension, url_string).group(0) for extension in extensionsToCheck if(extension in url_string)]
['foo.doc']
$> mysql -u root -p -e 'Select user from mysql.user' > allUsersOnDatabase.txt
Executing this command on linux prompt will first ask for the password of mysql root user, on providing correct password it will print all the database users to the text file.
var i = [NaN, 1,2,3];
var j = i.map(i =>{ return isNaN(i) ? 0 : i});
console.log(j)
_x000D_
What about the following?
T sign(T x) {
if(x==0) return 0;
return x/Math.abs(x);
}
Should work for every type T...
Alternatively, one can define abs(x) as Math.sqrt(x*x), and if that is also cheating, implement your own square root function...
ThreadLocal in Java had been introduced on JDK 1.2 but was later generified in JDK 1.5 to introduce type safety on ThreadLocal variable.
ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two thread can not see each others ThreadLocal variable.
Each thread holds an exclusive copy of ThreadLocal variable which becomes eligible to Garbage collection after thread finished or died, normally or due to any Exception, Given those ThreadLocal variable doesn't have any other live references.
ThreadLocal variables in Java are generally private static fields in Classes and maintain its state inside Thread.
Read more: ThreadLocal in Java - Example Program and Tutorial
The closest equivalent are the Windows Scheduled Tasks (Control Panel -> Scheduled Tasks), though they are a far, far cry from cron.
The biggest difference (to me) is that they require a user to be logged into the Windows box, and a user account (with password and all), which makes things a nightmare if your local security policy requires password changes periodically. I also think it is less flexible than cron as far as setting intervals for items to run.
Try using capturing groups:
title = re.search('<title>(.*)</title>', html, re.IGNORECASE).group(1)
The following list contains links to the the enhancements pages in the Java SE 7.
Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
Requesting and Customizing Applet Decoration in Dragg able Applets
Embedding JNLP File in Applet Tag
Deploying without Codebase
Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
Binary Literals
Strings in switch Statements
The try-with-resources Statement
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
Underscores in Numeric Literals
Type Inference for Generic Instance Creation
Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
Java Virtual Machine Support for Non-Java Languages
Garbage-First Collector
Java HotSpot Virtual Machine Performance Enhancements
JDBC
In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...
Operating off the assumption that we have a file named jsonConfigFile.json
with the following content from your post:
{
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]@{}
(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
ForEach-Object { $json[$_.Name] = $_.Value }
$json.Stuffs
will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type
key's value associated with the Clean Toilet
key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.
in JQuery you can use: in class for Select Option:
$('.className').each(function(){
className.push($("option:selected",this).val().substr(1));
});
in class for text Value:
$('.className').each(function(){
className.push($(this).val().substr(1));
});
in ID for text Value:
$("#id").val().substr(1)
For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Keep in mind that you'll need a timeout on your JSONP request to catch failures.
This is a bit late, but I think you could use the --limit or -l
command to limit the pattern to more specific hosts. (version 2.3.2.0)
You could have
- hosts: all (or group)
tasks:
- some_task
and then ansible-playbook playbook.yml -l some_more_strict_host_or_pattern
and use the --list-hosts
flag to see on which hosts this configuration would be applied.
To create a video, you could use opencv,
#load your frames
frames = ...
#create a video writer
writer = cvCreateVideoWriter(filename, -1, fps, frame_size, is_color=1)
#and write your frames in a loop if you want
cvWriteFrame(writer, frames[i])
if (typeof jQuery == 'undefined') {
// or if ( ! window.jQuery)
// or if ( ! 'jQuery' in window)
// or if ( ! window.hasOwnProperty('jQuery'))
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/libs/jquery.js';
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
After you attempt to include Google's copy from the CDN.
In HTML5, you don't need to set the type
attribute.
You can also use...
window.jQuery || document.write('<script src="/libs/jquery.js"><\/script>');
I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.
protected void Page_Load(object sender, EventArgs e)
Calendar1.SelectedDate = DateTime.Today;
}
the previous code did NOT highlight the selection, although it set the SelectedDate to today.
However, to select and highlight the following code will work properly.
protected void Page_Load(object sender, EventArgs e)
{
DateTime today = DateTime.Today;
Calendar1.TodaysDate = today;
Calendar1.SelectedDate = Calendar1.TodaysDate;
}
check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx
I was able to get around the Mac Sierra OS issue by duplicating the file, dragging the new file onto my desktop, open in preview, then click the export option (in the File menu) , then the option to save it without “alpha” comes up
I was able to solve "ORA-00604: error" by Droping with purge.
DROP TABLE tablename PURGE
Your code is correct. I tested:
r = requests.get("http://www.google.com")
print(r.content)
And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!
If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:
# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
In this case curl will send your defined cookie along with the cookies from the file.
If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).
The utma utmc, utmz
are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.
Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt
) instead of relative one.
Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.
curl_setopt($ch, CURLOPT_VERBOSE, true);
As mentioned this occurs when using RubyGems 1.6.0 with Ruby on Rails version earlier than version 3. My app is using Ruby on Rails 2.3.3 vendored into the /vendor of the project.
No doubt an upgrade of Ruby on Rails to a newer 2.3.X version may also fix this issue. However, this problem prevents you running Rake to unvendor Ruby on Rails and upgrade it.
Adding require 'thread' to the top of environment.rb did not fix the issue for me. Adding require 'thread' to /vendor/rails/activesupport/lib/active_support.rb did fix the problem.
To activate "test" profile write in your build.gradle:
test.doFirst {
systemProperty 'spring.profiles.active', 'test'
activeProfiles = 'test'
}
The following simple steps help me:
First, initialize the repository to work with Git
, so that any file changes are tracked:
git init
Then, check that the remote repository that you want to associate with the alias origin
exists, if not create it in git
first.
$ git ls-remote https://github.com/repo-owner/repo-name.git/
If it exists, associate it with the remote "origin":
git remote add origin https://github.com:/repo-owner/repo-name.git
and check to which URL, the remote "origin" belongs to by using git remote -v
:
$ git remote -v
origin https://github.com:/repo-owner/repo-name.git (fetch)
origin https://github.com:/repo-owner/repo-name.git (push)
Next, verify if your origin is properly aliased as follows:
$ cat ./.git/config
:
[remote "origin"]
url = https://github.com:/repo-owner/repo-name.git
fetch = +refs/heads/*:refs/remotes/origin/*
:
You need to see this section [remote "origin"]
. You can consider to use GitHub Desktop available for both Windows and MacOS, which help me to automatically populate the missing section/s in ~./git/config
file OR you can manually add it, not great, but hey it works!
[Optional]
You might also want to change the origin
alias to make it more intuitive, especially if you are working with multiple origin
:
git remote rename origin mynewalias
or even remove it:
git remote rm origin
Finally, on your first push, if you want master
in that repository to be your default upstream. you may want to add the -u
parameter
git add .
git commit -m 'First commit'
git push -u origin master
Update:
Separate the event and property bindings:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You could also use
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.
Old answer, before they fixed a bug in beta.1:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
See also How can I get new selection in "select" in Angular 2?
Just follow the convention being used for by project/team.
for those looking for a DESC ... this seems to work --sort=-
ty for the formatting, new to this ...my eyes are loosing some of it's bloodshot
git for-each-ref --format='%(color:cyan)%(authordate:format:%m/%d/%Y %I:%M %p) %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=-authordate refs/remotes
further ref: https://stackoverflow.com/a/5188364/10643471
Python doesn't really have either concept.
It uses duck typing, which removed the need for interfaces (at least for the computer :-))
Python <= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract.
Python >= 2.6: Abstract base classes do exist (http://docs.python.org/library/abc.html). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.
i found mine here:
~/android-sdks/platforms/android-23/data/res/drawable...
In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -
public String rpad(String inStr, int finalLength)
{
return (inStr + " " // typically a sufficient length spaces string.
).substring(0, finalLength);
}
similarly you can have a lpad()
as well
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
The FileInputStream
class works directly with the underlying file system. If the file in question is not physically present there, it will fail to open it. The getResourceAsStream()
method works differently. It tries to locate and load the resource using the ClassLoader
of the class it is called on. This enables it to find, for example, resources embedded into jar
files.
You can use the Android NDK, but answers should note that the Android NDK app is not free to use and there's no clear open source route to programming Android on Android in an increasingly Android-driven market that began as open source, with Android developer support or the extensiveness of the NDK app, meaning you're looking at abandoning Android as any kind of first steps programming platform without payments.
Note: I consider subscription requests as payments under duress and this is a freemium context which continues to go undefeated by the open source community.
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
Yes, it does. From the AdMob page:
The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.
Multiplies 10000 and stores as BIGINT, like "Currency" in Visual Basic and Office. See https://msdn.microsoft.com/en-us/library/office/gg264338.aspx
My goal was to avoid any hacky methods that assume something (e.g. setTimeout) and I ended up implementing the accepted solution with a bit of RxJS flavour on top:
private ngUnsubscribe = new Subject();
private tabSetInitialized = new Subject();
public tabSet: TabsetComponent;
@ViewChild('tabSet') set setTabSet(tabset: TabsetComponent) {
if (!!tabSet) {
this.tabSet = tabSet;
this.tabSetInitialized.next();
}
}
ngOnInit() {
combineLatest(
this.route.queryParams,
this.tabSetInitialized
).pipe(
takeUntil(this.ngUnsubscribe)
).subscribe(([queryParams, isTabSetInitialized]) => {
let tab = [undefined, 'translate', 'versions'].indexOf(queryParams['view']);
this.tabSet.tabs[tab > -1 ? tab : 0].active = true;
});
}
My scenario: I wanted to fire an action on a @ViewChild
element depending on the router queryParams
. Due to a wrapping *ngIf
being false until the HTTP request returns the data, the initialization of the @ViewChild
element happens with a delay.
How does it work: combineLatest
emits a value for the first time only when each of the provided Observables emit the first value since the moment combineLatest
was subscribed to. My Subject tabSetInitialized
emits a value when the @ViewChild
element is being set. Therewith, I delay the execution of the code under subscribe
until the *ngIf
turns positive and the @ViewChild
gets initialized.
Of course don't forget to unsubscribe on ngOnDestroy, I do it using the ngUnsubscribe
Subject:
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
declare @date datetime; set @date = null
--declare @date datetime; set @date = '2015-01-01'
select coalesce( convert( varchar(10), @date, 103 ), '')
I had the same problem, and I was using the following plugin for tests:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<useFile>true</useFile>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.
After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:
<parallel>methods</parallel>
<threadCount>10</threadCount>
Hope that this helps someone out!
In your sendMail()
function, add an ajax call to your backend, where you can implement this on the server side.
var inputs = $('input, select, textarea').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
Please use the attributes from the System.Web.Http namespace on your WebAPI actions:
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public string Auth(string username, string password)
{...}
The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc
. The classes in the System.Web.Http
namespace are for WebAPI.
For Windows 10, I needed to add /f option in order to shutdown the pc without any question and wait time.
//This did not work for me
Process.Start("shutdown", "/s /t 0");
//But this worked
Process.Start("shutdown", "/s /f /t 0");
As josh527
said, handler.removeCallbacksAndMessages(null);
can work.
But why?
If you have a look at the source code, you can understand it more clearly.
There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):
Handler.java (leave some overload method)
/**
* Remove any pending posts of Runnable <var>r</var> with Object
* <var>token</var> that are in the message queue. If <var>token</var> is null,
* all callbacks will be removed.
*/
public final void removeCallbacks(Runnable r, Object token)
{
mQueue.removeMessages(this, r, token);
}
/**
* Remove any pending posts of messages with code 'what' and whose obj is
* 'object' that are in the message queue. If <var>object</var> is null,
* all messages will be removed.
*/
public final void removeMessages(int what, Object object) {
mQueue.removeMessages(this, what, object);
}
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
public final void removeCallbacksAndMessages(Object token) {
mQueue.removeCallbacksAndMessages(this, token);
}
MessageQueue.java do the real work:
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
void removeMessages(Handler h, Runnable r, Object object) {
if (h == null || r == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.callback == r
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.callback == r
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
void removeCallbacksAndMessages(Handler h, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
import 'dart:math';
generateFactorsOfN(N){
//determine lowest bound divisor range
final lowerBoundCheck = sqrt(N).toInt();
var factors = Set<int>(); //stores factors
/**
* Lets take 16:
* 4 = sqrt(16)
* start from 1 ... 4 inclusive
* check mod 16 % 1 == 0? set[1, (16 / 1)]
* check mod 16 % 2 == 0? set[1, (16 / 1) , 2 , (16 / 2)]
* check mod 16 % 3 == 0? set[1, (16 / 1) , 2 , (16 / 2)] -> unchanged
* check mod 16 % 4 == 0? set[1, (16 / 1) , 2 , (16 / 2), 4, (16 / 4)]
*
* ******************* set is used to remove duplicate
* ******************* case 4 and (16 / 4) both equal to 4
* return factor set<int>.. this isn't ordered
*/
for(var divisor = 1; divisor <= lowerBoundCheck; divisor++){
if(N % divisor == 0){
factors.add(divisor);
factors.add(N ~/ divisor); // ~/ integer division
}
}
return factors;
}
I have a method, the internals of which are wrapped in a MySqlTransaction.
The deadlock issue showed up for me when I ran the same method in parallel with itself.
There was not an issue running a single instance of the method.
When I removed MySqlTransaction, I was able to run the method in parallel with itself with no issues.
Just sharing my experience, I'm not advocating anything.
It's possible to pass args to npm run
since npm 2 (2014). The syntax is as follows:
npm run <command> [-- <args>]
Note the --
separator, used to separate the params passed to npm
command itself, and the params passed to your script.
With the example package.json
:
"scripts": {
"grunt": "grunt",
"server": "node server.js"
}
here's how to pass the params to those scripts:
npm run grunt -- task:target // invokes `grunt task:target`
npm run server -- --port=1337 // invokes `node server.js --port=1337`
Note: If your param does not start with -
or --
, then having an explicit --
separator is not needed; but it's better to do it anyway for clarity.
npm run grunt task:target // invokes `grunt task:target`
Note below the difference in behavior (test.js
has console.log(process.argv)
): the params which start with -
or --
are passed to npm
and not to the script, and are silently swallowed there.
$ npm run test foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar']
$ npm run test -foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js']
$ npm run test --foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js']
$ npm run test -- foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar']
$ npm run test -- -foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '-foobar']
$ npm run test -- --foobar
['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '--foobar']
The difference is clearer when you use a param actually used by npm:
$ npm test --help // this is disguised `npm --help test`
npm test [-- <args>]
aliases: tst, t
To get the parameter value, see this question. For reading named parameters, it's probably best to use a parsing library like yargs or minimist; nodejs exposes process.argv
globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).
Edit 2013.10.03: It's not currently possible directly. But there's a related GitHub issue opened on npm
to implement the behavior you're asking for. Seems the consensus is to have this implemented, but it depends on another issue being solved before.
Original answer (2013.01): As a some kind of workaround (though not very handy), you can do as follows:
Say your package name from package.json
is myPackage
and you have also
"scripts": {
"start": "node ./script.js server"
}
Then add in package.json
:
"config": {
"myPort": "8080"
}
And in your script.js
:
// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080
That way, by default npm start
will use 8080. You can however configure it (the value will be stored by npm
in its internal storage):
npm config set myPackage:myPort 9090
Then, when invoking npm start
, 9090 will be used (the default from package.json
gets overridden).
you can use startActivityForResult()
If anyone looking for a solution with (.less) try below. Open your main or common less file and use like below.
@import (css) url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
body{
font-family: "Open Sans", sans-serif;
}
For Windows 8 users:
After trying every solution given here, with no success, I found this:
Go to Device Manager
Browse my computer for drivers -> Let me pick from a list of device drivers on my computer
Choose Android Device and then Android ADB Interface.
Now I have my devices listed at adb devices
.
git merge
you can follow below steps
origin/master
branch to feature
branch# step1: change branch to master, and pull to update all commits
$ git checkout master
$ git pull
# step2: change branch to target, and pull to update commits
$ git checkout feature
$ git pull
# step3: merge master to feature(?? current is feature branch)
$ git merge master
feature
branch to origin/master
branch
origin/master
is the remote master branch, whilemaster
is the local master branch
$ git checkout master
$ git pull origin/master
$ git merge feature
$ git push origin/master
I hope this helps. I'm just doing the trick of float
ing the buttons to the right.
This way the Prev
button is left of the Next
button, but the Next
comes first in the HTML structure:
.f {_x000D_
float: right;_x000D_
}_x000D_
.clr {_x000D_
clear: both;_x000D_
}
_x000D_
<form action="action" method="get">_x000D_
<input type="text" name="abc">_x000D_
<div id="buttons">_x000D_
<input type="submit" class="f" name="next" value="Next">_x000D_
<input type="submit" class="f" name="prev" value="Prev">_x000D_
<div class="clr"></div><!-- This div prevents later elements from floating with the buttons. Keeps them 'inside' div#buttons -->_x000D_
</div>_x000D_
</form>
_x000D_
Benefits over other suggestions: no JavaScript code, accessible, and both buttons remain type="submit"
.
The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.
It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib
folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.
Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart()
method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig
annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?
you don't need to declare Map groovy internally recognizes it
def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']
// print the values..
println "First Name: ${personDetails.firstName}"
println "Last Name: ${personDetails.lastName}"
Simple Steps, follow them and i guess it will solve your problem
Include these Css in your page,
.progress {
position: relative;
height: 2px;
display: block;
width: 100%;
background-color: white;
border-radius: 2px;
background-clip: padding-box;
/*margin: 0.5rem 0 1rem 0;*/
overflow: hidden;
}
.progress .indeterminate {
background-color:black; }
.progress .indeterminate:before {
content: '';
position: absolute;
background-color: #2C67B1;
top: 0;
left: 0;
bottom: 0;
will-change: left, right;
-webkit-animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite; }
.progress .indeterminate:after {
content: '';
position: absolute;
background-color: #2C67B1;
top: 0;
left: 0;
bottom: 0;
will-change: left, right;
-webkit-animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
-webkit-animation-delay: 1.15s;
animation-delay: 1.15s; }
@-webkit-keyframes indeterminate {
0% {
left: -35%;
right: 100%; }
60% {
left: 100%;
right: -90%; }
100% {
left: 100%;
right: -90%; } }
@keyframes indeterminate {
0% {
left: -35%;
right: 100%; }
60% {
left: 100%;
right: -90%; }
100% {
left: 100%;
right: -90%; } }
@-webkit-keyframes indeterminate-short {
0% {
left: -200%;
right: 100%; }
60% {
left: 107%;
right: -8%; }
100% {
left: 107%;
right: -8%; } }
@keyframes indeterminate-short {
0% {
left: -200%;
right: 100%; }
60% {
left: 107%;
right: -8%; }
100% {
left: 107%;
right: -8%; } }
Then include the progress bar your body tag,
<div class="progress" id="PreLoaderBar">
<div class="indeterminate"></div>
</div>
then it will start as your page loads, and now what you have to do is just hide this when the page loads,or set the visibility to none, or hidden, using javascript,
document.onreadystatechange = function () {
if (document.readyState === "complete") {
console.log(document.readyState);
document.getElementById("PreLoaderBar").style.display = "none";
}
}
Let me Know if you face any problems and also, you can add any type of progress bar you can easily find them, for this example i have used a indeterminate progress bar.
Here is code to get line number and column position
function getLineNumber(tArea) {
return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}
function getCursorPos() {
var me = $("textarea[name='documenttext']")[0];
var el = $(me).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
var ret = pos - prevLine(me);
alert(ret);
return ret;
}
function prevLine(me) {
var lineArr = me.value.substr(0, me.selectionStart).split("\n");
var numChars = 0;
for (var i = 0; i < lineArr.length-1; i++) {
numChars += lineArr[i].length+1;
}
return numChars;
}
tArea is the text area DOM element
Use the vector
constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:
int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);
or
test(std::vector<int>(x, x + sizeof x / sizeof x[0]));
where sizeof x / sizeof x[0]
is obviously 3
in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0]
points one element beyond the last element.
I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).
Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.
These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".
So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.
So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.
Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.
Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.
I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
Creating a site wrapper div inside the body and applying the overflow->x:hidden to the wrapper INSTEAD of the body or html fixed the issue.
This worked for me after also adding position: relative
to the wrapper.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
For those who on a mac with the same issue and installed npm via homebrew:
brew uninstall npm
then
brew install npm
Works for me on osx (10.9.1)
EDIT: You may need to brew update
before installing npm. You can also do a brew upgrade
after updating homebrew. Also it might be helpful to run brew doctor
if you run into any other issues.
Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named "Sheet1" in the currently opened workbook.
Dim wb as Workbook
Dim ws as Worksheet
Set wb = ActiveWorkbook
For Each ws in wb.Worksheets
if ws.Name = "Sheet1" then
'Do something here
End if
Next
After checking out my branch in Egit, I switched to the Java View, then used File-->Import, Git-->Projects from Git, then selected the top level maven directory. This was with Eclipse Kepler.
_, err := os.Stat(file)
if err == nil {
log.Printf("file %s exists", file)
} else if os.IsNotExist(err) {
log.Printf("file %s not exists", file)
} else {
log.Printf("file %s stat error: %v", file, err)
}
Your condition id !== 0
will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block
is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null
error.
Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.
window.onload = function loadContIcons() {
var elem = document.createElement("img");
elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
elem.setAttribute("class", "up_icon");
var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
if (container !== null) {
container.appendChild(elem);
} else console.log("aaaaa");
var elem1 = document.createElement("img");
elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
elem1.setAttribute("class", "down_icon");
container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
if (container !== null) {
container.appendChild(elem1);
} else console.log("aaaaa");
}
Ingnoring the duplicated unique constraint isn't a solution?
INSERT IGNORE INTO tblSoftwareTitles...
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package
VistaDB is the only alternative if you going to run your website at shared hosting (almost all of them won't let you run your websites under Full Trust mode) and also if you need simple x-copy deployment enabled website.
I ran into this issue as well. I had sync'd my code earlier in the day so it made no sense that it suddenly gave this Git error. Restarting Visual Studio did not make any difference. After reviewing the above answers and not finding any clear solution, I decided to try syncing outside of Visual Studio using TortoiseGit which I already had installed. This worked. I was then able to sync within Visual Studio normally. If you don't already have TortoiseGit, you may download it (free) from tortoisegit.org.
Interestingly, when I replaced this:
$("body").trigger("click")
With this:
jQuery("body").trigger("click")
It works!
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
Your application (Eclipse) needs more memory and JVM is not allocating enough.You can increase the amount of memory JVM allocates by following the answers given here
This is a good function:
public function getFriendlyURL($string) {
setlocale(LC_CTYPE, 'en_US.UTF8');
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
$string = preg_replace('~[^\-\pL\pN\s]+~u', '-', $string);
$string = str_replace(' ', '-', $string);
$string = trim($string, "-");
$string = strtolower($string);
return $string;
}
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
Working on Motorola cell phones operating system, we hijacked memory allocation library to observe all memory allocations. It helped to find a lot of problems with memory allocations. Since prevention is better then curing, I would recommend to use static analysis tool like Klockwork or PC-Lint
This should solve it:
Don't run it though addslashes()
; if you're in the context of the HTML page, the HTML parser can still see the </script>
tag, even mid-string, and assume it's the end of the JavaScript:
<?php
$value = 'XXX</script><script>alert(document.cookie);</script>';
?>
<script type="text/javascript">
var foo = <?= json_encode($value) ?>; // Use this
var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!
</script>
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
Make a connection and open it.
con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();
Write the select query:
string sql = "select * from Pending_Tasks";
Create a command object:
OracleCommand cmd = new OracleCommand(sql, con);
Execute the command and put the result in a object to read it.
OracleDataReader r = cmd.ExecuteReader();
now start reading from it.
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
Add this too using Oracle.ManagedDataAccess.Client;
The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip
All what you must do is:
Enable the module:
LoadModule remoteip_module modules/mod_remoteip.so
Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):
RemoteIPHeader X-Forwarded-For
See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.
I think you should use reflection. Something like this:
private T ConvertDictionaryTo<T>(IDictionary<string, object> dictionary) where T : new()
{
Type type = typeof (T);
T ret = new T();
foreach (var keyValue in dictionary)
{
type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value, null);
}
return ret;
}
It takes your dictionary and loops through it and sets the values. You should make it better but it's a start. You should call it like this:
SomeClass someClass = ConvertDictionaryTo<SomeClass>(a);
I did this-
sudo mysql -p
then i gave password for my root account(password that we use for sudo)then it asked to enter password and i gave password for mysql terminal(new password).
I recommend using the following snippet as it works in all python versions (requires six
):
from six.moves import reload_module
reload_module(module)
I have abandoned using mysqli. It is simply too unstable. I've had queries that crash PHP using mysqli but work just fine with the mysql package. Also mysqli crashes on LONGTEXT columns. This bug has been raised in various forms since at least 2005 and remains broken. I'd honestly like to use prepared statements but mysqli just isn't reliable enough (and noone seems to bother fixing it). If you really want prepared statements go with PDO.
Today, I was testing this with iOS 9 Beta and found the solution.
To solve it, go to:
The query can be written slightly simpler, like this:
DECLARE @T INT = 2
SELECT CASE
WHEN @T < 1 THEN 'less than one'
WHEN @T = 1 THEN 'one'
ELSE 'greater than one'
END T
What about calculating the MD5 (or other) hash of sequential integers, then taking the first 8 characters.
i.e
MD5(1) = c4ca4238a0b923820dcc509a6f75849b => c4ca4238
MD5(2) = c81e728d9d4c2f636f067f89cc14862c => c81e728d
MD5(3) = eccbc87e4b5ce2fe28308fd9f2a7baf3 => eccbc87e
etc.
caveat: I have no idea how many you could allocate before a collision (but it would be a known and constant value).
edit: This is now an old answer, but I saw it again with time on my hands, so, from observation...
Chance of all numbers = 2.35%
Chance of all letters = 0.05%
First collision when MD5(82945) = "7b763dcb..." (same result as MD5(25302))
Use following formula:
=CONCATENATE(LOWER(MID(A1,1,1)),LOWER( B1))
for
Josh Smith = jsmith
note that A1 contains name and B1 contains surname
Oracle: Just felt to do it in different way. Disadvantage: It doesn't perform full index scan. But still gives the result and can use this in substring.
select employee_name
from employees
where lpad(employee_name,1) ='A'
OR lpad(employee_name,1) = 'B'
order by employee_name
We can use LEFT in SQL Server instead of lpad . Still suggest not a good idea to use this method.
They are use together to create a new child process. First, calling fork
creates a copy of the current process (the child process). Then, exec
is called from within the child process to "replace" the copy of the parent process with the new process.
The process goes something like this:
child = fork(); //Fork returns a PID for the parent process, or 0 for the child, or -1 for Fail
if (child < 0) {
std::cout << "Failed to fork GUI process...Exiting" << std::endl;
exit (-1);
} else if (child == 0) { // This is the Child Process
// Call one of the "exec" functions to create the child process
execvp (argv[0], const_cast<char**>(argv));
} else { // This is the Parent Process
//Continue executing parent process
}
1.Check the Environment variables (must be set for System and not for user):
ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server
ORACLE_SID = XE
2.Check if you have the right definition in listener.ora
XE =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
)
DEFAULT_SERVICE_LISTENER = (XE)
3.Restart the service (Services > OracleServiceXE)
After that you may see a new service called OracleXETNSListenerXE.
There is already an old OracleXETNSListener.
I started both and then I was able to make a successful connection.
Edit:
If everything is running but you still can't connect, check if there is no error: ORA-12557: TNS:protocol adapter not loadable.
To correct the error go back to the Environment variables and this time edit the one called: Path. Be sure that C:\oraclexe\app\oracle\product\11.2.0\server\bin is somewhere at the beginning, definitely before any other path pointing to a different version of the Oracle DB.
Ok, there are a bunch of ways you can do that. Yes, you can use plain old JS. Just try:
let dt1 = new Date()
let dt2 = new Date()
Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
.plusYears(6)
.plusMonths(12)
.plusHours(2)
.plusMinutes(42)
.plusSeconds(12);
// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.
You could use Enumerable.SequenceEqual
. This works for any IEnumerable<T>
, not just arrays.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
These are two different modes in which your computer can operate. Prior to this, when computers were like a big room, if something crashes – it halts the whole computer. So computer architects decide to change it. Modern microprocessors implement in hardware at least 2 different states.
User mode:
Kernel mode:
How the switch occurs.
The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.
http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode
http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html
You can find source code of any .jar file online, import the same project in your IDE with basic setups. Make necessary changes in .java file and compile it for .class files.
Once compilation is done You need to extract the jar file, replace the old .class file with new one.
And use below command for reconstruct .jar file
Jar cf test.jar *
Note : I have done so many time this changes in our project, hope you will find it useful.
Try this
public static void main(String[] args)
{
String original = "ABCDEFGHIJKLMNOPQ";
String tobeChecked = "GHi";
System.out.println(containsString(original, tobeChecked, true));
System.out.println(containsString(original, tobeChecked, false));
}
public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
if (caseSensitive)
{
return original.contains(tobeChecked);
}
else
{
return original.toLowerCase().contains(tobeChecked.toLowerCase());
}
}
function fetch_comments($ticket_id){
$this->db->select('tbl_tickets_replies.comments,
tbl_users.username,tbl_roles.role_name');
$this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
$this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
$this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
return $this->db->get('tbl_tickets_replies');
}