You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:
pip install some-package.whl
If you have problem to install the wheel read this answer
i have just added (overflow:scroll;) in (div3) with fixed height.
see the fiddle:- http://jsfiddle.net/fMs67/10/
If you want the sum of all bars to be equal unity, weight each bin by the total number of values:
weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)
Hope that helps, although the thread is quite old...
Note for Python 2.x: add casting to float()
for one of the operators of the division as otherwise you would end up with zeros due to integer division
If you are grouping by some other value, then instead of what you have,
write it as
Sum(CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END) as SumSomeProduct
If, otoh, you want to group By
the internal expression, (col3*col4)
then
write the group By
to match the expression w/o the SUM
...
Select Sum(Case When col1 > col2 Then col3*col4 Else 0 End) as SumSomeProduct
From ...
Group By Case When col1 > col2 Then col3*col4 Else 0 End
Finally, if you want to group By the actual aggregate
Select SumSomeProduct, Count(*), <other aggregate functions>
From (Select <other columns you are grouping By>,
Sum(Case When col1 > col2
Then col3*col4 Else 0 End) as SumSomeProduct
From Table
Group By <Other Columns> ) As Z
Group by SumSomeProduct
It's very easy to declare and initialize an array. For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:
a)
int[] a = new int[5];
or
b)
int[] a = {1, 2, 3, 4, 5};
so the basic pattern is for initialization and declaration by method a) is:
datatype[] arrayname = new datatype[requiredarraysize];
datatype
should be in lower case.
So the basic pattern is for initialization and declaration by method a is:
If it's a string array:
String[] a = {"as", "asd", "ssd"};
If it's a character array:
char[] a = {'a', 's', 'w'};
For float double, the format of array will be same as integer.
For example:
double[] a = {1.2, 1.3, 12.3};
but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.
But when you do it by "method b" you will not have to enter the values manually.
There are plenty of descriptive answers here so I'm not going to repeat what has already been said. What I would like to add is the following code demonstrating all the permutations I can think of. The code is quite long due to the number of combinations. Feel free to drop it into MSTest and see the output for yourself (the output is included at the bottom).
This evidence supports Jon Skeet's answer.
Code:
[TestMethod]
public void StringEqualsMethodVsOperator()
{
string s1 = new StringBuilder("string").ToString();
string s2 = new StringBuilder("string").ToString();
Debug.WriteLine("string a = \"string\";");
Debug.WriteLine("string b = \"string\";");
TryAllStringComparisons(s1, s2);
s1 = null;
s2 = null;
Debug.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", 20)));
Debug.WriteLine(string.Empty);
Debug.WriteLine("string a = null;");
Debug.WriteLine("string b = null;");
TryAllStringComparisons(s1, s2);
}
private void TryAllStringComparisons(string s1, string s2)
{
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- string.Equals --");
Debug.WriteLine(string.Empty);
Try((a, b) => string.Equals(a, b), s1, s2);
Try((a, b) => string.Equals((object)a, b), s1, s2);
Try((a, b) => string.Equals(a, (object)b), s1, s2);
Try((a, b) => string.Equals((object)a, (object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- object.Equals --");
Debug.WriteLine(string.Empty);
Try((a, b) => object.Equals(a, b), s1, s2);
Try((a, b) => object.Equals((object)a, b), s1, s2);
Try((a, b) => object.Equals(a, (object)b), s1, s2);
Try((a, b) => object.Equals((object)a, (object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- a.Equals(b) --");
Debug.WriteLine(string.Empty);
Try((a, b) => a.Equals(b), s1, s2);
Try((a, b) => a.Equals((object)b), s1, s2);
Try((a, b) => ((object)a).Equals(b), s1, s2);
Try((a, b) => ((object)a).Equals((object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- a == b --");
Debug.WriteLine(string.Empty);
Try((a, b) => a == b, s1, s2);
#pragma warning disable 252
Try((a, b) => (object)a == b, s1, s2);
#pragma warning restore 252
#pragma warning disable 253
Try((a, b) => a == (object)b, s1, s2);
#pragma warning restore 253
Try((a, b) => (object)a == (object)b, s1, s2);
}
public void Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, T1 in1, T2 in2)
{
T3 out1;
Try(tryFunc, e => { }, in1, in2, out out1);
}
public bool Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, Action<Exception> catchFunc, T1 in1, T2 in2, out T3 out1)
{
bool success = true;
out1 = default(T3);
try
{
out1 = tryFunc.Compile()(in1, in2);
Debug.WriteLine("{0}: {1}", tryFunc.Body.ToString(), out1);
}
catch (Exception ex)
{
Debug.WriteLine("{0}: {1} - {2}", tryFunc.Body.ToString(), ex.GetType().ToString(), ex.Message);
success = false;
catchFunc(ex);
}
return success;
}
Output:
string a = "string";
string b = "string";
-- string.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- object.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- a.Equals(b) --
a.Equals(b): True
a.Equals(Convert(b)): True
Convert(a).Equals(b): True
Convert(a).Equals(Convert(b)): True
-- a == b --
(a == b): True
(Convert(a) == b): False
(a == Convert(b)): False
(Convert(a) == Convert(b)): False
--------------------
string a = null;
string b = null;
-- string.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- object.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- a.Equals(b) --
a.Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
a.Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
-- a == b --
(a == b): True
(Convert(a) == b): True
(a == Convert(b)): True
(Convert(a) == Convert(b)): True
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.
SQL Server has a PIVOT command that might be what you are looking for.
select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;
If the columns are not constant, you'll have to combine this with some dynamic SQL.
DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);
select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);
SELECT @sql =
'SELECT *
FROM TAG
PIVOT
(
MAX(Value)
FOR TagID IN( ' + @columns + ' )) as TagTime;';
execute(@sql);
I assume you have updated ADT with version 22 and R.java file is not getting generated.
If this is the case, then here is the solution:
Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.
I've just solved these exact errors myself. The key it seems is that your project.properties
file in your appcompat library project should use whatever the highest version of the API that your particular appcompat project has been written for (in your case it looks like v21). Easiest way I've found to tell is to look for the highest 'values-v**' folder inside the res folder (eg. values-v21
).
To clarify, in addition to the instructions at Support Library Setup, your appcompat/project.properties
file should have in it: target=android-21
(mine came with 19 instead).
Also ensure that you have the 'SDK Platform' to match that version installed (eg for v21 install Android 5.0 SDK Platform).
Alternatively if you don't want to use the appcompat at all, (I think) all you need to do is right click your project > Properties > Android > Library > Remove the reference to the appcompat. The errors will still show up for the appcompat project, but shouldn't affect your project after that.
If someone is still looking for an answer, for me the problem was in routes/web.php file. Example:
Route::get('/', function () {
return view('welcome');
});
It is also Route, so yeah...Just remove it if not needed and you are good to go! You should also follow answers provided from above.
You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.
var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
You don't need to pass this
, there already is the event
object passed by default automatically, which contains event.target
which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event
object, it's already there. Try it out. And event.target
will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event
is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent
:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething()
will see event
and event.target
as per usual!
No need to pass this
everywhere, and you can keep your function signatures free from wiring information and simplify things.
One of the answers is that x:name is to be used inside different program languages such as c# and name is to be used for the framework. Honestly that is what it sounds like to me.
Here is an alternative tr based solution that doesn't use echo, expressed as a one-liner.
for v in $(tr ',' '\n' <<< "$var") ; do something_with "$v" ; done
It feels tidier without echo but that is just my personal preference.
You need to alias the subquery. Thus, your statement should be:
Select Z.id
From (
Select id, time
From dbo.tablea
Union All
Select id, time
From dbo.tableb
) As Z
Group By Z.id
The modular crypt format for bcrypt consists of
$2$
, $2a$
or $2y$
identifying the hashing algorithm and format$
.
, /
, 0
–9
, A
–Z
, a
–z
that is different to the standard Base 64 Encoding alphabet) consisting of:
Thus the total length is 59 or 60 bytes respectively.
As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARY
or BINARY(60)
(see The _bin and binary Collations for information about the difference).
CHAR
is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A
is treated as equal to a
. See The _bin
and binary
Collations for more information.
div.abc.xyz {
/* rules go here */
}
... or simply:
.abc.xyz {
/* rules go here */
}
I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/
edit: I am now using msys2. Msys2 uses pacman
from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)
You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.
I'm going to answer my own question.
Therefore, the following works for me
$qb->select('c')
->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
->where('c.username = :username');
or
$qb->select('c')
->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
->where('c.username = :username');
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
The simple way is to create table as textfile and move the file to the appropriate location
CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;
Copy the file to the HDFS Location where table is created.
Hope this helps!!!
A ternary will suffice. change:
gotdata = dlist[1]
to
gotdata = dlist[1] if len(dlist) > 1 else 'null'
this is a shorter way of expressing
if len(dlist) > 1:
gotdata = dlist[1]
else:
gotdata = 'null'
Unload and reload the project, in Visual Studio:
Fixed!
I found this solution to work the best (easiest), having run into the problem multiple times.
Use kebab-case
for all package, folder and file names.
You should imagine that any folder or file might be extracted to its own package some day. Packages cannot contain uppercase letters.
New packages must not have uppercase letters in the name. https://docs.npmjs.com/files/package.json#name
Therefore, camelCase
should never be used. This leaves snake_case
and kebab-case
.
kebab-case
is by far the most common convention today. The only use of underscores is for internal node packages, and this is simply a convention from the early days.
I could not find the relevant answer for my requirement which I figured it out. So, this answer is for checkbox with text like below where you want to resize the checkbox drawable and text separately.
You need two PNGs cb_checked.png and cb_unchechecked.png add them to drawable folder
Now create cb_bg_checked.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cb_checked"
android:height="22dp" <!-- This is the size of your checkbox -->
android:width="22dp" <!-- This is the size of your checkbox -->
android:right="6dp" <!-- This is the padding between cb and text -->
tools:targetApi="m"
tools:ignore="UnusedAttribute" />
</layer-list>
And, cb_bg_unchecked.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<item android:drawable="@drawable/cb_unchechecked"
android:height="22dp" <!-- This is the size of your checkbox -->
android:width="22dp" <!-- This is the size of your checkbox -->
android:right="6dp" <!-- This is the padding between cb and text -->
tools:targetApi="m"
tools:ignore="UnusedAttribute" />
</layer-list>
Then create a selector XML checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cb_bg_checked" android:state_checked="true"/>
<item android:drawable="@drawable/cb_bg_unchecked" android:state_checked="false"/>
</selector>
Now define it your layout.xml like this
<CheckBox
android:id="@+id/checkbox_with_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:button="@drawable/checkbox"
android:text="This is text"
android:textColor="@color/white"
android:textSize="14dp" /> <!-- Here you can resize text -->
No, you can not.
You can call a function
from a stored procedure
and debug a stored procedure
(this will step into the function
)
First install dblink
Then, you would do something like:
INSERT INTO t2 select * from
dblink('host=1.2.3.4
user=*****
password=******
dbname=D1', 'select * t1') tt(
id int,
col_1 character varying,
col_2 character varying,
col_3 int,
col_4 varchar
);
You can use .filter()
method of the Array
object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
Some old browsers like IE8 doesn't support .filter()
method of the Array
object, if you are using jQuery you can use .filter()
method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
Instead of using new Date()
you should use:
var timestamp = Date.parse('foo');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
}
Date.parse()
returns a timestamp, an integer representing the number of milliseconds since 01/Jan/1970. It will return NaN
if it cannot parse the supplied date string.
I realize this is a bit late, but I've had success with annotating a timestamp column with
@Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
This should also work with CURRENT_DATE
and CURRENT_TIME
. I'm using JPA/Hibernate with Oracle, so YMMV.
Open Visual Studio then select File
-> New
-> Project
Select Visual C#
-> Class library
Compile Project Or Build the solution, to create Dll File
Go to the class library folder (Debug Folder)
A JSON object is simply a javascript object, so with Javascript being a prototype based language, all you have to do is address it using the dot notation.
mything.NewField = 'foo';
Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:
http://localhost:8085/projectname/
Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
SHA1 is a one way hash. So you can not really revert it.
That's why applications use it to store the hash of the password and not the password itself.
Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.
Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.
Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.
In his blog he shows a table that tells us the probability of collisions for a given input set.
As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.
A simple java program will show us what his table shows:
public class Main {
public static void main(String[] args) {
char[] inputValue = new char[10];
Map<Integer, String> hashValues = new HashMap<Integer, String>();
int collisionCount = 0;
for (int i = 0; i < 77163; i++) {
String asString = nextValue(inputValue);
int hashCode = asString.hashCode();
String collisionString = hashValues.put(hashCode, asString);
if (collisionString != null) {
collisionCount++;
System.out.println("Collision: " + asString + " <-> " + collisionString);
}
}
System.out.println("Collision count: " + collisionCount);
}
private static String nextValue(char[] inputValue) {
nextValue(inputValue, 0);
int endIndex = 0;
for (int i = 0; i < inputValue.length; i++) {
if (inputValue[i] == 0) {
endIndex = i;
break;
}
}
return new String(inputValue, 0, endIndex);
}
private static void nextValue(char[] inputValue, int index) {
boolean increaseNextIndex = inputValue[index] == 'z';
if (inputValue[index] == 0 || increaseNextIndex) {
inputValue[index] = 'A';
} else {
inputValue[index] += 1;
}
if (increaseNextIndex) {
nextValue(inputValue, index + 1);
}
}
}
My output end with:
Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135
It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A
and z
.
Let's take the last reported collision and check
System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());
My output is
86390
86390
Conclusion:
If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.
And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.
What about using a tabular inside \author{}
, just like in IEEE macros:
\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c}
I. M. Author & M. Y. Coauthor \\
My Department & Coauthor Department \\
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle
\end{document}
This will produce two columns authors with any documentclass
.
Results:
Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. ::
works a lot like the filesystem directory separator '/
', when searching your path for a program you'd like to run. Consider:
/path/to/executable
This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...
::std::cout
...is equally explicit in the C++ namespace "tree".
Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH
environment variable, so if PATH=/usr/bin:/usr/local/bin
, and you were "in" /tmp
, then...
X11/xterm
...would happily run /tmp/X11/xterm
if found, else /usr/bin/X11/xterm
, else /usr/local/bin/X11/xterm
. Similarly, say you were in a namespace called X
, and had a "using namespace Y
" in effect, then...
std::cout
...could be found in any of ::X::std::cout
, ::std::cout
, ::Y::std::cout
, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout
is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std
", nor anything called "cout
", so in practice using only std::cout
is fine.
Noteworthy differences:
1) shells tend to use the first match using the ordering in PATH
, whereas C++ gives a compiler error when you've been ambiguous.
2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put .
in the PATH
.
3) C++ always searches the global namespace (like having /
implicitly your PATH
).
Using absolute ::abc::def::...
"paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.
As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std::
that are less "unique" than cout
, that programmers might use for something completely different in their code (e.g. merge
, includes
, fill
, generate
, exchange
, queue
, toupper
, max
). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespace
s: the worst thing you can do in this space is allow using namespace
s in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.
So, a leading ::
is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....
The situation:
You are on your branch, let's say master
and you have your commit on any other branch. You have to pick only one file from that particular commit.
The approach:
Step 1: Checkout on the required branch.
git checkout master
Step 2: Make sure you have copied the required commit hash.
git checkout commit_hash path\to\file
Step 3: You now have the changes of the required file on your desired branch. You just need to add and commit them.
git add path\to\file
git commit -m "Your commit message"
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
sample code show custom dialog in kotlin:
fun showDlgFurtherDetails(context: Context,title: String?, details: String?) {
val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(false)
dialog.setContentView(R.layout.dlg_further_details)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
val lblService = dialog.findViewById(R.id.lblService) as TextView
val lblDetails = dialog.findViewById(R.id.lblDetails) as TextView
val imgCloseDlg = dialog.findViewById(R.id.imgCloseDlg) as ImageView
lblService.text = title
lblDetails.text = details
lblDetails.movementMethod = ScrollingMovementMethod()
lblDetails.isScrollbarFadingEnabled = false
imgCloseDlg.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}
For me, disk space was low, and files that couldn't be written were expected to be present later. Other answers mentioned missing files (or misnamed/improperly referenced-by-name files)--but the root cause was lack of disk space.
For a quick solution, I usually do like this.
This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox1.Text <> "" Then
If IsDate(TextBox1.Text) Then
TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
Else
MsgBox "Please enter a valid date!"
Cancel = True
End If
End If
End Sub
However, I think what Sid developed is a much better approach - a full fledged date picker control.
The cc and cxx is located inside /Applications/Xcode.app
. This should find the right paths
export CXX=`xcrun -find c++`
export CC=`xcrun -find cc`
I'm not sure if WhatsApp really stores it's stuff in a sqlite database stored in the private app space but it may be worth a try to do the same I suggested here. You will need root access for this.
I just solve this error while using capybara in ror project by adding:
Capybara.ignore_elements = true
to features/support/env.rb
.
You could also use plain Javascript window.innerWidth
to compare width.
But use jQuery's .resize()
fired automatically for you:
$( window ).resize(function() {
// your code...
});
Quick and easy:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Or, if you want a jQuery plugin:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
To open a URL with the default browser, you can execute:
rundll32 url.dll,FileProtocolHandler https://www.google.com
I had issues with URL parameters with the other solutions. However, this one seemed to work correctly.
You can use interp
function from scipy, it extrapolates left and right values as constant beyond the range:
>>> from scipy import interp, arange, exp
>>> x = arange(0,10)
>>> y = exp(-x/3.0)
>>> interp([9,10], x, y)
array([ 0.04978707, 0.04978707])
You can write a wrapper around an interpolation function which takes care of linear extrapolation. For example:
from scipy.interpolate import interp1d
from scipy import arange, array, exp
def extrap1d(interpolator):
xs = interpolator.x
ys = interpolator.y
def pointwise(x):
if x < xs[0]:
return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
elif x > xs[-1]:
return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
else:
return interpolator(x)
def ufunclike(xs):
return array(list(map(pointwise, array(xs))))
return ufunclike
extrap1d
takes an interpolation function and returns a function which can also extrapolate. And you can use it like this:
x = arange(0,10)
y = exp(-x/3.0)
f_i = interp1d(x, y)
f_x = extrap1d(f_i)
print f_x([9,10])
Output:
[ 0.04978707 0.03009069]
It means that zero or more String objects (or a single array of them) may be passed as the argument(s) for that method.
See the "Arbitrary Number of Arguments" section here: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs
In your example, you could call it as any of the following:
myMethod(); // Likely useless, but possible
myMethod("one", "two", "three");
myMethod("solo");
myMethod(new String[]{"a", "b", "c"});
Important Note: The argument(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.
Important Note 2: The argument that gets the ...
must be the last in the method signature. So, myMethod(int i, String... strings)
is okay, but myMethod(String... strings, int i)
is not okay.
Thanks to Vash for the clarifications in his comment.
Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.
#left{
float: left;
margin-right: 40px;
}
#right{
float: left;
}
int
variables can't be null
If a null
is to be converted to int
, then it is the converter which decides whether to set 0
, throw exception, or set another value (like Integer.MIN_VALUE
). Try to plug your own converter.
I'd create the array and then append the object literals to it.
var myColumnDefs = [];
for ( var i=0 ; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}
Every time a new device is opened par() will reset, so another option is simply do dev.off()
and continue.
You could also do this is plain in html with a meta tag:
<html>
<head>
<meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>
Would this do?
var selected = [];
$('div#checkboxes input[type=checkbox]').each(function() {
if ($(this).is(":checked")) {
selected.push($(this).attr('name'));
}
});
The newest version of the Anaconda installer for Windows will also install a windows launcher for "Anaconda Prompt" and "Anaconda Powershell Prompt". If you use one of those instead of the regular windows cmd shell, the conda
command, python etc. should be available by default in this shell.
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
It's very similar to
char array[] = {'O', 'n', 'e', ' ', /*etc*/ ' ', 'm', 'u', 's', 'i', 'c', '\0'};
but gives you read-only memory.
For a discussion of the difference between a char[]
and a char *
, see comp.lang.c FAQ 1.32.
It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.
In MySQL Workbench:
Left-hand side navigator > Management > Client Connections
It gives you the option to kill queries and connections.
Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here
I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect
function simpleObjInspect(oObj, key, tabLvl)
{
key = key || "";
tabLvl = tabLvl || 1;
var tabs = "";
for(var i = 1; i < tabLvl; i++){
tabs += "\t";
}
var keyTypeStr = " (" + typeof key + ")";
if (tabLvl == 1) {
keyTypeStr = "(self)";
}
var s = tabs + key + keyTypeStr + " : ";
if (typeof oObj == "object" && oObj !== null) {
s += typeof oObj + "\n";
for (var k in oObj) {
if (oObj.hasOwnProperty(k)) {
s += simpleObjInspect(oObj[k], k, tabLvl + 1);
}
}
} else {
s += "" + oObj + " (" + typeof oObj + ") \n";
}
return s;
}
Usage
alert(simpleObjInspect(anyObject));
or
console.log(simpleObjInspect(anyObject));
The above solution did not work for me. Instead I simply removed the hash(#) from the last line of the logging.properties file, to make it work.
# To see debug messages in TldLocationsCache, uncomment the following line:
org.apache.jasper.compiler.TldLocationsCache.level = FINE
The next step is to add the jars that Tomcat 7 is looking for in catalina.properties files just after the following line
org.apache.catalina.startup.TldConfig.jarsToSkip=
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
Check this out with IsNullOrEmpty and IsNullOrwhiteSpace
string sTestes = "I like sweat peaches";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 5000000; i++)
{
for (int z = 0; z < 500; z++)
{
var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
}
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
Console.ReadLine();
You'll see that IsNullOrWhiteSpace is much slower :/
You are using a local path. Is that really what you want? If it is, you need to use the file:///
prefix:
file:///H:/media/css/static/img/sprites/buttons-v3-10.png
obviously, this will work only on your local computer.
Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://
, https://
) pages has been widely disabled due to security reasons.
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
A browser isn't going to show you white space reliably. I recommend the Linux 'od' command to see what's really in there. Comforming XML parsers will respect all of the methods you listed.
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
The plugin Media File Manager advanced is amazing and allow you to create folders and subfolders very easily and move files with a simple drag & drop.
Check it at: http://wordpress.org/plugins/media-file-manager-advanced/
You may use a implementation of Callable such that
public class MyAsyncCallable<V> implements Callable<V> {
CallbackInterface ci;
public MyAsyncCallable(CallbackInterface ci) {
this.ci = ci;
}
public V call() throws Exception {
System.out.println("Call of MyCallable invoked");
System.out.println("Result = " + this.ci.doSomething(10, 20));
return (V) "Good job";
}
}
where CallbackInterface is something very basic like
public interface CallbackInterface {
public int doSomething(int a, int b);
}
and now the main class will look like this
ExecutorService ex = Executors.newFixedThreadPool(2);
MyAsyncCallable<String> mac = new MyAsyncCallable<String>((a, b) -> a + b);
ex.submit(mac);
Why would you pass a parameter to a stored procedure that doesn't use it?
It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).
C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).
private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;
public string Name{ // This is a readonly property.
get {
return _name;
}
}
public bool Enabled{ // This is a read- and writeable property.
get{
return _enabled;
}
set{
_enabled = value;
}
}
If someone says you can't because only Windows can control the non-client area, they're wrong!
That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.
However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome
class to adjust the non-client area like you want. Here you can get to start with.
In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.
I'm sorry for not posting a clear example, but later I will for sure.
Given you're looking for a simple formula, this is probably the simplest way to do it, assuming that the Earth is a sphere with a circumference of 40075 km.
Length in meters of 1° of latitude = always 111.32 km
Length in meters of 1° of longitude = 40075 km * cos( latitude ) / 360
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
Since the question is about what is the fastest method, I thought I'd throw up add some perf metrics.
TL;DR The winner, by a wide margin, is the +
operator, and please never use regex
ascii
is a package on linux you could download.
for example
sudo apt-get install ascii
ascii
Usage: ascii [-dxohv] [-t] [char-alias...]
-t = one-line output -d = Decimal table -o = octal table -x = hex table
-h = This help screen -v = version information
Prints all aliases of an ASCII character. Args may be chars, C \-escapes,
English names, ^-escapes, ASCII mnemonics, or numerics in decimal/octal/hex.`
This code can help you with C/C++ escape codes like \x0A
Expanding on the answer by @gordon, here's an example of readable syntax and argument passing with shell/command module (these differ from the git module in that there are required but free-form arguments, as noted by @ander)
- name: "release tarball is generated" local_action: module: shell _raw_params: git archive --format zip --output release.zip HEAD chdir: "files/clones/webhooks"
I would do it like this:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)
In case you have some more complex formula it will be handy
You can use double quotes if ANSI SQL mode is enabled
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
"key" TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
or the proprietary back tick escaping otherwise. (Where to find the `
character on various keyboard layouts is covered in this answer)
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
Any algorithm implemented using recursion can also be implemented using iteration.
For example, the Tower of Hanoi problem is more easily solved using recursion as opposed to iteration.
or with sed:
test -z $(echo "2000" | sed s/[0-9]//g) && echo "integer" || echo "no integer"
# integer
test -z $(echo "ab12" | sed s/[0-9]//g) && echo "integer" || echo "no integer"
# no integer
The api is fairly easy to use.
// Lookup the dns, if the ip exists.
if (!ip.isEmpty()) {
InetAddress inetAddress = InetAddress.getByName(ip);
dns = inetAddress.getCanonicalHostName();
}
Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.
If you are looking this from 2009, and you don't like AbstractSingletonFactoryGenerators, here are a few other options.
Remember, arrays are "copied" when assigned, or in this case, returned, so you are practically getting the same array every time. (See copy-on-write behaviour of arrays in PHP.)
function FRUITS_ARRAY(){
return array('chicken', 'mushroom', 'dirt');
}
function FRUITS_ARRAY(){
static $array = array('chicken', 'mushroom', 'dirt');
return $array;
}
function WHAT_ANIMAL( $key ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $array[ $key ];
}
function ANIMAL( $key = null ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $key !== null ? $array[ $key ] : $array;
}
os.path.realpath(__file__)
will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.
This will work:
override func viewDidLoad() {
super.viewDidLoad()
// Swift block syntax (iOS 10+)
let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print("Done!") }
// Swift >=3 selector syntax
let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
// Swift 2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
// Swift <2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
// must be internal or public.
@objc func update() {
// Something cool
}
For Swift 4, the method of which you want to get the selector must be exposed to Objective-C, thus @objc
attribute must be added to the method declaration.
To make part of your text underlined and colored
in your strings.xml
<string name="text_with_colored_underline">put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><u></string>
then in the activity
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));
and for clickable links:
<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>
and in your activity:
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
you just need to type . ~/.bash_profile
refer: https://superuser.com/questions/46139/what-does-source-do
You can use IN operator as below
select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbars="vertical"/>
You'll want to use...
alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('key_b'));
In addition to Doug Kavendek answer. One could use the following approach to get closer to tz_database.
var shapeFile = new ShapeFile(shapeFilePath); var shapeIndex = shapeFile.GetShapeIndexContainingPoint(new PointD(long, lat), 0D); var attrValues = shapeFile.GetAttributeFieldValues(shapeIndex); var timeZoneId = attrValues[0];
P.S. Can't insert all the links :( So please use search.
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
One possible idea is to write separate constructor function
//Something is the structure we work with
type Something struct {
Text string
DefaultText string
}
// NewSomething create new instance of Something
func NewSomething(text string) Something {
something := Something{}
something.Text = text
something.DefaultText = "default text"
return something
}
Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";
int main()
{
size_t wcsChars = wcslen( wcsString);
size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Wide chars in wcsString: %u\n", wcsChars);
printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
NULL, 0, NULL, NULL);
printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
sizeRequired-1);
}
And the output:
Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18
Here's a list of the environment variables. I think you might want CURRENT_VARIANT
. See also BUILD_VARIANTS
.
Using the first for
-loop you manually enumerate through the array by increasing an index to the length of the array, then getting the value at the current index manually.
The latter syntax is added in Java 5 and enumerates an array by using an Iterator
instance under the hoods. You then have only access to the object (not the index) and you won't be able to adjust the array while enumerating.
It's convenient when you just want to perform some actions on all objects in an array.
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
local_action
runs the command on the local server, not on the servers you specify in hosts
parameter.
Change your "Execute the script" task to
- name: Execute the script
command: sh /home/test_user/test.sh
and it should do it.
You don't need to repeat sudo in the command line because you have defined it already in the playbook.
According to Ansible Intro to Playbooks user
parameter was renamed to remote_user
in Ansible 1.4 so you should change it, too
remote_user: test_user
So, the playbook will become:
---
- name: Transfer and execute a script.
hosts: server
remote_user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
- name: Execute the script
command: sh /home/test_user/test.sh
use this
System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")
This is an addendum to @endy-tjahjono's solution.
I ended up not being able to get the value of uploadme from the scope. Even though uploadme in the HTML was visibly updated by the directive, I could still not access its value by $scope.uploadme. I was able to set its value from the scope, though. Mysterious, right..?
As it turned out, a child scope was created by the directive, and the child scope had its own uploadme.
The solution was to use an object rather than a primitive to hold the value of uploadme.
In the controller I have:
$scope.uploadme = {};
$scope.uploadme.src = "";
and in the HTML:
<input type="file" fileread="uploadme.src"/>
<input type="text" ng-model="uploadme.src"/>
There are no changes to the directive.
Now, it all works like expected. I can grab the value of uploadme.src from my controller using $scope.uploadme.
You need to wrap this in script tags:
<script type='text/javascript'> ... your code ... </script>
That being said, it's important WHEN you execute this code. If you put this in the page BEFORE the HTML elements that it is hooking into then the script will run BEFORE the HTML is actually rendered in the page, so it will fail.
It is common practice to wrap this type of code in a "document ready" block, like so:
<script type='text/javascript'>
$(document).ready(function() {
... your code...
}}
</script>
This ensures that the entire page has rendered in the browser BEFORE your code is executed. It is also a best practice to put the code in the <head>
section of your page.
I've recently found even more interesting way to create any ValueNode
or ContainerNode
(Jackson v2.3).
ObjectNode node = JsonNodeFactory.instance.objectNode();
Start Search....Lock...Select all files listed and delete..fixed
0600 is what mine is set at (and it's working)
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>
).
Text areas are resizable by default. If you want to disable that, just use the resize css rule:
#signin textarea {
resize: none;
}
A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input>
tags as well.
<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>
This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
System.out.println(s);
}
Also check if the resource-name contains any illegal characters (for me it was a "-" in my-image)
In case it helps anyone, the C# equivalent of ZloiAdun's answer is:
element.SendKeys(Keys.Control + "a");
element.SendKeys("55");
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Task Manager
Skype...
appsRestart WampServer
and it should work
If anyone has problems with using a custom dateformat for java.sql.Date, this is the simplest solution:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(java.sql.Date.class, new DateSerializer());
mapper.registerModule(module);
(This SO-answer saved me a lot of trouble: https://stackoverflow.com/a/35212795/3149048 )
Jackson uses the SqlDateSerializer by default for java.sql.Date, but currently, this serializer doesn't take the dateformat into account, see this issue: https://github.com/FasterXML/jackson-databind/issues/1407 . The workaround is to register a different serializer for java.sql.Date as shown in the code example.
here is the solution for your query returning only one row for each date in that table here in the solution 'tony' will occur twice as two different start dates are there for it
SELECT * FROM
(
SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC ) RNM
FROM TABLE T1
)
WHERE RNM=1
L
: long i = 12345678910L;
.BTW: it doesn't have to be an upper case L, but lower case is confused with 1
many times :).
Since the third version of Swift you can do the following:
let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)
simialr to what Sunkas advised.
a bit late to this, but yes rabbitmq has a build in tracer that allows you to see the incomming messages in a log. When enabled, you can just tail -f /var/tmp/rabbitmq-tracing/.log
(on mac) to watch the messages.
the detailed discription is here http://www.mikeobrien.net/blog/tracing-rabbitmq-messages
I don't have Express Management Studio on this machine, so I'm going based on memory. I think you need to set the column as "IDENTITY", and there should be a [+] under properties where you can expand, and set auto-increment to true.
Which class ? Do you mean the Joda DateTime class ? If so, you can simply call getMillis()
on each, and perform the appropriate subtraction/scaling.
I would recommend Joda for date/time work, btw, due to it's useful and intuitive API, and its thread-safety for formatting/parsing options.
Your syntax is wrong... The correct coding is:
<?php
mysql_connect("localhost","root","");
mysql_select_db("form1");
$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");
while($rows = mysql_fetch_array($query))
{
$rows = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment']
echo $rows.'</br>'.$address.'</br>'.$email.'</br>'.$subject.'</br>'.$comment;
}
?>
Sometimes diff
is the utility you need, but sometimes join
is more appropriate. The files need to be pre-sorted or, if you are using a shell which supports process substitution such as bash, ksh or zsh, you can do the sort on the fly.
join -v 1 <(sort file1) <(sort file2)
I did a little research through trial and error method. Found out that all the values that are available in keyboard are eligible to be a file or directory except '/' in *nux machine.
I used touch command to create file for following characters and it created a file.
(Comma separated values below)
'!', '@', '#', '$', "'", '%', '^', '&', '*', '(', ')', ' ', '"', '\', '-', ',', '[', ']', '{', '}', '`', '~', '>', '<', '=', '+', ';', ':', '|'
It failed only when I tried creating '/' (because it's root directory) and filename container /
because it file separator.
And it changed the modified time of current dir .
when I did touch .
. However, file.log is possible.
And of course, a-z
, A-Z
, 0-9
, -
(hypen), _
(underscore) should work.
So, by the above reasoning we know that a file name or directory name can contain anything except /
forward slash. So, our regex will be derived by what will not be present in the file name/directory name.
/(?:(?P<dir>(?:[/]?)(?:[^\/]+/)+)(?P<filename>[^/]+))/
root
directoryA directory can start with /
when it is absolute path and directory name when it's relative. Hence, look for /
with zero or one occurrence.
/(?P<filepath>(?P<root>[/]?)(?P<rest_of_the_path>.+))/
Next, a directory and its child is always separated by /
. And a directory name can be anything except /
. Let's match /var/ first then.
/(?P<filepath>(?P<first_directory>(?P<root>[/]?)[^\/]+/)(?P<rest_of_the_path>.+))/
Next, let's match all directories
/(?P<filepath>(?P<dir>(?P<root>[/]?)(?P<single_dir>[^\/]+/)+)(?P<rest_of_the_path>.+))/
Here, single_dir is yz/
because, first it matched var/
, then it found next occurrence of same pattern i.e. log/
, then it found the next occurrence of same pattern yz/
. So, it showed the last occurrence of pattern.
Now, we know that we're never going to use the groups like single_dir, filepath, root. Hence let's clean that up.
Let's keep them as groups however don't capture those groups.
And rest_of_the_path is just the filename! So, rename it. And a file will not have /
in its name, so it's better to keep [^/]
/(?:(?P<dir>(?:[/]?)(?:[^\/]+/)+)(?P<filename>[^/]+))/
This brings us to the final result. Of course, there are several other ways you can do it. I am just mentioning one of the ways here.
^
means string starts with
(?P<dir>pattern)
means capture group by group name. We have two groups with group name dir
and file
(?:pattern)
means don't consider this group or non-capturing group.
?
means match zero or one.
+
means match one or more
[^\/]
means matches any char except forward slash (/
)
[/]?
means if it is absolute path then it can start with / otherwise it won't. So, match zero or one occurrence of /
.
[^\/]+/
means one or more characters which aren't forward slash (/
) which is followed by a forward slash (/
). This will match var/
or xyz/
. One directory at a time.
From memset()
:
memset(myarray, 0, sizeof(myarray));
You can use sizeof(myarray)
if the size of myarray
is known at compile-time. Otherwise, if you are using a dynamically-sized array, such as obtained via malloc
or new
, you will need to keep track of the length.
Non of the above solved my problem, you can check pod version using two commands
pod --version
gem which cocoapods
In my case pod --version
always showed "1.5.0" while gem which cocopods
shows
Library/Ruby/Gems/2.3.0/gems/cocoapods-1.9.0/lib/cocoapods.rb
. I tried every thing but unable to update version showed from pod --version
. sudo gem install cocopods
result in installing latest version but pod --version
always showing previous version. Finally I tried these commands
sudo gem update
sudo gem uninstall cocoapods
sudo gem install cocopods
pod setup``pod install
catch for me was sudo gem update. Hopefully it will help any body else.
It would be easier to recreate the data frame. This would also interpret the columns types from scratch.
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
Pay attention: you cannot install arbitrary versions of tensorflow, they have to correspond to your python installation, which isn't conveyed by most of the answers here. This is also true for the current wheels like https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl (from this answer above). For this example, the cp35-cp35m hints that it is for Python 3.5.x
A huge list of different wheels/compatibilities can be found here on github. By using this, you can downgrade to almost every availale version in combination with the respective for python. For example:
pip install tensorflow==2.0.0
(note that previous to installing Python 3.7.8 alongside version 3.8.3 in my case, you would get
ERROR: Could not find a version that satisfies the requirement tensorflow==2.0.0 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0, 2.3.0rc0, 2.3.0rc1)
ERROR: No matching distribution found for tensorflow==2.0.0
this also holds true for other non-compatible combinations.)
This should also be useful for legacy CPU without AVX support or GPUs with a compute capability that's too low.
If you only need the most recent releases (which it doesn't sound like in your question) a list of urls for the current wheel packages is available on this tensorflow page. That's from this SO-answer.
Note: This link to a list of different versions didn't work for me.
You can create your own extension method to do this:
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
}
And then call:
mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component's template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
It's also well explained in the official docs: Component interaction.
NSAssert() calls to validate method parameters is pretty handy for tracking down and avoiding passing nils as well.
as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle
.
the built-in method for that in the Fragment
class is setArguments(Bundle)
and getArguments()
.
basically, what you do is set up a bundle with all your Parcelable
items and send them on.
in turn, your Fragment will get those items in it's onCreate
and do it's magic to them.
the way shown in the DialogFragment
link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.
You can use (int) if any issue occurs!! It will work fine.
IF you want to select object with minimum or maximum property value. another way is to use Implementing IComparable.
public struct Money : IComparable<Money>
{
public Money(decimal value) : this() { Value = value; }
public decimal Value { get; private set; }
public int CompareTo(Money other) { return Value.CompareTo(other.Value); }
}
Max Implementation will be.
var amounts = new List<Money> { new Money(20), new Money(10) };
Money maxAmount = amounts.Max();
Min Implementation will be.
var amounts = new List<Money> { new Money(20), new Money(10) };
Money maxAmount = amounts.Min();
In this way, you can compare any object and get the Max and Min while returning the object type.
Hope This will help someone.
I run into the same problem and wrote a little shared-memory utility class to work around it.
I'm using multiprocessing.RawArray
(lockfree), and also the access to the arrays is not synchronized at all (lockfree), be careful not to shoot your own feet.
With the solution I get speedups by a factor of approx 3 on a quad-core i7.
Here's the code: Feel free to use and improve it, and please report back any bugs.
'''
Created on 14.05.2013
@author: martin
'''
import multiprocessing
import ctypes
import numpy as np
class SharedNumpyMemManagerError(Exception):
pass
'''
Singleton Pattern
'''
class SharedNumpyMemManager:
_initSize = 1024
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SharedNumpyMemManager, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.lock = multiprocessing.Lock()
self.cur = 0
self.cnt = 0
self.shared_arrays = [None] * SharedNumpyMemManager._initSize
def __createArray(self, dimensions, ctype=ctypes.c_double):
self.lock.acquire()
# double size if necessary
if (self.cnt >= len(self.shared_arrays)):
self.shared_arrays = self.shared_arrays + [None] * len(self.shared_arrays)
# next handle
self.__getNextFreeHdl()
# create array in shared memory segment
shared_array_base = multiprocessing.RawArray(ctype, np.prod(dimensions))
# convert to numpy array vie ctypeslib
self.shared_arrays[self.cur] = np.ctypeslib.as_array(shared_array_base)
# do a reshape for correct dimensions
# Returns a masked array containing the same data, but with a new shape.
# The result is a view on the original array
self.shared_arrays[self.cur] = self.shared_arrays[self.cnt].reshape(dimensions)
# update cnt
self.cnt += 1
self.lock.release()
# return handle to the shared memory numpy array
return self.cur
def __getNextFreeHdl(self):
orgCur = self.cur
while self.shared_arrays[self.cur] is not None:
self.cur = (self.cur + 1) % len(self.shared_arrays)
if orgCur == self.cur:
raise SharedNumpyMemManagerError('Max Number of Shared Numpy Arrays Exceeded!')
def __freeArray(self, hdl):
self.lock.acquire()
# set reference to None
if self.shared_arrays[hdl] is not None: # consider multiple calls to free
self.shared_arrays[hdl] = None
self.cnt -= 1
self.lock.release()
def __getArray(self, i):
return self.shared_arrays[i]
@staticmethod
def getInstance():
if not SharedNumpyMemManager._instance:
SharedNumpyMemManager._instance = SharedNumpyMemManager()
return SharedNumpyMemManager._instance
@staticmethod
def createArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__createArray(*args, **kwargs)
@staticmethod
def getArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__getArray(*args, **kwargs)
@staticmethod
def freeArray(*args, **kwargs):
return SharedNumpyMemManager.getInstance().__freeArray(*args, **kwargs)
# Init Singleton on module load
SharedNumpyMemManager.getInstance()
if __name__ == '__main__':
import timeit
N_PROC = 8
INNER_LOOP = 10000
N = 1000
def propagate(t):
i, shm_hdl, evidence = t
a = SharedNumpyMemManager.getArray(shm_hdl)
for j in range(INNER_LOOP):
a[i] = i
class Parallel_Dummy_PF:
def __init__(self, N):
self.N = N
self.arrayHdl = SharedNumpyMemManager.createArray(self.N, ctype=ctypes.c_double)
self.pool = multiprocessing.Pool(processes=N_PROC)
def update_par(self, evidence):
self.pool.map(propagate, zip(range(self.N), [self.arrayHdl] * self.N, [evidence] * self.N))
def update_seq(self, evidence):
for i in range(self.N):
propagate((i, self.arrayHdl, evidence))
def getArray(self):
return SharedNumpyMemManager.getArray(self.arrayHdl)
def parallelExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_par(5)
print(pf.getArray())
def sequentialExec():
pf = Parallel_Dummy_PF(N)
print(pf.getArray())
pf.update_seq(5)
print(pf.getArray())
t1 = timeit.Timer("sequentialExec()", "from __main__ import sequentialExec")
t2 = timeit.Timer("parallelExec()", "from __main__ import parallelExec")
print("Sequential: ", t1.timeit(number=1))
print("Parallel: ", t2.timeit(number=1))
The best answer resides in the Angular GitHub discussion (Changing route doesn't scroll to top in the new page).
Maybe you want go to top only in root router changes (not in children, because you can load routes with lazy load in f.e. a tabset)
app.component.html
<router-outlet (deactivate)="onDeactivate()"></router-outlet>
app.component.ts
onDeactivate() {
document.body.scrollTop = 0;
// Alternatively, you can scroll to top by using this other call:
// window.scrollTo(0, 0)
}
Full credits to JoniJnm (original post)
For some weird reason "Java SE Development Kit 8u151" gives this trouble. Just install, "Java SE Development Kit 8u152" from the following link-
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
It should work then.
I provided a couple of reasonably interesting answers to this question:
Nlog - Generating Header Section for a log file
Adding a Header:
The question wanted to know how to add a header to the log file. Using config entries like this allow you to define the header format separately from the format of the rest of the log entries. Use a single logger, perhaps called "headerlogger" to log a single message at the start of the application and you get your header:
Define the header and file layouts:
<variable name="HeaderLayout" value="This is the header. Start time = ${longdate} Machine = ${machinename} Product version = ${gdc:item=version}"/>
<variable name="FileLayout" value="${longdate} | ${logger} | ${level} | ${message}" />
Define the targets using the layouts:
<target name="fileHeader" xsi:type="File" fileName="xxx.log" layout="${HeaderLayout}" />
<target name="file" xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />
Define the loggers:
<rules>
<logger name="headerlogger" minlevel="Trace" writeTo="fileHeader" final="true" />
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
Write the header, probably early in the program:
GlobalDiagnosticsContext.Set("version", "01.00.00.25");
LogManager.GetLogger("headerlogger").Info("It doesn't matter what this is because the header format does not include the message, although it could");
This is largely just another version of the "Treating exceptions differently" idea.
Log each log level with a different layout
Similarly, the poster wanted to know how to change the format per logging level. It wasn't clear to me what the end goal was (and whether it could be achieved in a "better" way), but I was able to provide a configuration that did what he asked:
<variable name="TraceLayout" value="This is a TRACE - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="DebugLayout" value="This is a DEBUG - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="InfoLayout" value="This is an INFO - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="WarnLayout" value="This is a WARN - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="ErrorLayout" value="This is an ERROR - ${longdate} | ${logger} | ${level} | ${message}"/>
<variable name="FatalLayout" value="This is a FATAL - ${longdate} | ${logger} | ${level} | ${message}"/>
<targets>
<target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace">
<target xsi:type="File" fileName="xxx.log" layout="${TraceLayout}" />
</target>
<target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug">
<target xsi:type="File" fileName="xxx.log" layout="${DebugLayout}" />
</target>
<target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info">
<target xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />
</target>
<target name="fileAsWarn" xsi:type="FilteringWrapper" condition="level==LogLevel.Warn">
<target xsi:type="File" fileName="xxx.log" layout="${WarnLayout}" />
</target>
<target name="fileAsError" xsi:type="FilteringWrapper" condition="level==LogLevel.Error">
<target xsi:type="File" fileName="xxx.log" layout="${ErrorLayout}" />
</target>
<target name="fileAsFatal" xsi:type="FilteringWrapper" condition="level==LogLevel.Fatal">
<target xsi:type="File" fileName="xxx.log" layout="${FatalLayout}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="fileAsTrace,fileAsDebug,fileAsInfo,fileAsWarn,fileAsError,fileAsFatal" />
<logger name="*" minlevel="Info" writeTo="dbg" />
</rules>
Again, very similar to Treating exceptions differently.
Putting your content behind a captcha would mean that robots would find it difficult to access your content. However, humans would be inconvenienced so that may be undesirable.
You will have to provide the entire user dn
in SECURITY_PRINCIPAL
like this
env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test");
Based on the example here: http://drupal.org/node/550488
The following will probably work in .htaccess
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch (\.js|\.html)$>
ExpiresActive Off
</FilesMatch>
</IfModule>
It's all about what you really want to do, but in times to come and right now, the best way is avoid browser detection and check for features. like Canvas, Audio, WebSockets, etc through simple javascript calls or in your CSS, for me your best approach is use a tool like ModernizR:
Unlike with the traditional—but highly unreliable—method of doing “UA sniffing,” which is detecting a browser by its (user-configurable)
navigator.userAgent
property, Modernizr does actual feature detection to reliably discern what the various browsers can and cannot do.
If using CSS, you can do this:
.no-js .glossy,
.no-cssgradients .glossy {
background: url("images/glossybutton.png");
}
.cssgradients .glossy {
background-image: linear-gradient(top, #555, #333);
}
as it will load and append all features as a class name in the <html>
element and you will be able to do as you wish in terms of CSS.
And you can even load files upon features, for example, load a polyfill js and css if the browser does not have native support
Modernizr.load([
// Presentational polyfills
{
// Logical list of things we would normally need
test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
// Modernizr.load loads css and javascript by default
nope : ['presentational-polyfill.js', 'presentational.css']
},
// Functional polyfills
{
// This just has to be truthy
test : Modernizr.websockets && window.JSON,
// socket-io.js and json2.js
nope : 'functional-polyfills.js',
// You can also give arrays of resources to load.
both : [ 'app.js', 'extra.js' ],
complete : function () {
// Run this after everything in this group has downloaded
// and executed, as well everything in all previous groups
myApp.init();
}
},
// Run your analytics after you've already kicked off all the rest
// of your app.
'post-analytics.js'
]);
a simple example of requesting features from javascript:
However, if you do end up using rm instead of git rm. You can skip the git add and directly commit the changes using:
git commit -a
In latest git just 4 operation is needed to remove the git submodule.
.gitmodules
git add .gitmodules
git rm --cached <path_to_submodule>
git commit -m "Removed submodule xxx"
I think there is no out-of-the-box support for that in VS Code.
You can install a plugin to give you similar functionality. Eg.:
https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints
Or the more famous:
https://marketplace.visualstudio.com/items?itemName=xyz.local-history
Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore
file also solves this problem).
I wrote a generic solution in C# loosely based on @Mehrdad Afshari answer:
void Example(List<MyObject> actualObjects)
{
List<TreeNode<MyObject>> treeRoots = actualObjects.BuildTree(obj => obj.ID, obj => obj.ParentID, -1);
}
public class TreeNode<T>
{
public TreeNode(T value)
{
Value = value;
Children = new List<TreeNode<T>>();
}
public T Value { get; private set; }
public List<TreeNode<T>> Children { get; private set; }
}
public static class TreeExtensions
{
public static List<TreeNode<TValue>> BuildTree<TKey, TValue>(this IEnumerable<TValue> objects, Func<TValue, TKey> keySelector, Func<TValue, TKey> parentKeySelector, TKey defaultKey = default(TKey))
{
var roots = new List<TreeNode<TValue>>();
var allNodes = objects.Select(overrideValue => new TreeNode<TValue>(overrideValue)).ToArray();
var nodesByRowId = allNodes.ToDictionary(node => keySelector(node.Value));
foreach (var currentNode in allNodes)
{
TKey parentKey = parentKeySelector(currentNode.Value);
if (Equals(parentKey, defaultKey))
{
roots.Add(currentNode);
}
else
{
nodesByRowId[parentKey].Children.Add(currentNode);
}
}
return roots;
}
}
Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek
method. I would recommend reading this cool article:
I am not 100% sure what the conditions are for this, but for me the above didn't work directly, thought it got close. I think it was because I needed "id" for my view by in the model it was called "ObjectID".
I had a model with a variety of pieces of information. I just needed the id.
Before the above I created a new System.Web.Routing.RouteValueDictionary object and added the needed id.
(System.Web.Routing.)RouteValueDictionary RouteInfo = new RouteValueDictionary();
RouteInfo.Add("id", ObjectID);
return RedirectToAction("details", RouteInfo);
(Note: the MVC project in question I didn't create, so I don't know where all the right "fiddly" bits are.)
$q="SELECT * FROM projects WHERE YEAR(date) = 2012 AND MONTH(date) = 1;
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof
is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof
.
Third, C doesn't have references so your usage of &
in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t
type) as a separate argument, and use sizeof
at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc()
, and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
There are already a lot of answers but here is another approach if you're in the Rails world:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
For those having a portable SDK edition on windows, simply add the 2 following path to your system.
F:\ADT_SDK\sdk\platforms
F:\ADT_SDK\sdk\platform-tools
This worked for me.
You can take the SelectedItem
and cast it back to your class
and access its properties
.
MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);
Edit You can try using DataTextField and DataValueField, I used it with DataSource.
ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";
I got a creative solution I think you are looking for
$('#clear').click(function() {_x000D_
$('#input-outer input').val('');_x000D_
});
_x000D_
body {_x000D_
font-family: "Tahoma";_x000D_
}_x000D_
#input-outer {_x000D_
height: 2em;_x000D_
width: 15em;_x000D_
border: 1px #e7e7e7 solid;_x000D_
border-radius: 20px;_x000D_
}_x000D_
#input-outer input {_x000D_
height: 2em;_x000D_
width: 80%;_x000D_
border: 0px;_x000D_
outline: none;_x000D_
margin: 0 0 0 10px;_x000D_
border-radius: 20px;_x000D_
color: #666;_x000D_
}_x000D_
#clear {_x000D_
position: relative;_x000D_
float: right;_x000D_
height: 20px;_x000D_
width: 20px;_x000D_
top: 5px;_x000D_
right: 5px;_x000D_
border-radius: 20px;_x000D_
background: #f1f1f1;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
}_x000D_
#clear:hover {_x000D_
background: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
<input type="text">_x000D_
<div id="clear">_x000D_
X_x000D_
</div>_x000D_
</div>
_x000D_
Download the code from github into the node_modules directory
var moduleName = require("<name of directory>")
that should do it.
if the module has dependancies and has a package.json, open the module and enter npm install.
Hope this helps
Get all the checked checkbox value in an array - one liner
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
<input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
<input class="custom-control-input inp" type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
<input class="custom-control-input inp" Checked type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
Well, the code that renders the button enabled/disabled:
if(name.getText().equals("")) {
loginbt.setEnabled(false);
}else {
loginbt.setEnabled(true);
}
must be written in javax.swing.event.ChangeListener
and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?
Also note that despite errors being hidden, any custom error handler (set with set_error_handler
) will still be executed!
If you want use Services in Ubuntu(Upstart): Node as a service in Ubuntu 11.04 with upstart, monit and forever.js
AngularJS directives ng-show, ng-hide allows to display and hide a row:
<tr ng-show="rw.isExpanded">
</tr>
A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. ng-hide performs the same task but requires inverse condition.
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
Maybe in your data source add a column which does a sumif over all rows.
Not sure what your data looks like but something like =(sumif([column holding pivot row heads),[current row head value in row], probability column)>.2).
This will give you a True when the pivot table will show >20%.
Then add a filter on your pivot table on this column for TRUE values
Selecting from sysusers will get you information about users on the selected database, not logins on the server.
Or you could add this to the html of the element you want to remove the border radius from (this way you wouldn't be removing it from all buttons / elements):
style="border-radius:0px; -webkit-border-radius:0px; -moz-border-radius:0px;"
Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position
On High Sierra
which python
shows the default python but if you downloaded and installed the latest version from python.org you can find it by:
which python3.6
which on my machine shows
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
After attempting a few of these solutions and not having any success, this is what worked for me:
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
You can use the asp:Table in your web form and build it via code:
http://msdn.microsoft.com/en-us/library/7bewx260.aspx
Also, check out asp.net for tutorials and such.
Note: If your issue is, "innodb index is marked as corrupted"! Then, the simple solution can be, just remove the indexes and add them again. That can solve pretty quickly without losing any records nor restarting or moving table contents into a temporary table and back.
You could use Gson library
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);
If you are fortunate enough to be running Python 3.4+, you can use pathlib
:
>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')
To stick to ==
without consideration of the other type, the following is also possible.
type(a) == type(None)
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
GitHub solution solved the problem for me by adding
If you are trying to load the image at your form_load, it's a better idea to use the code
pictureBox1.LoadAsync(@"http://google.com/test.png");
not only loading from web but also no lag in your form loading.
This will only ever hit document.cookie ONE time. Every subsequent request will be instant.
(function(){
var cookies;
function readCookie(name,c,C,i){
if(cookies){ return cookies[name]; }
c = document.cookie.split('; ');
cookies = {};
for(i=c.length-1; i>=0; i--){
C = c[i].split('=');
cookies[C[0]] = C[1];
}
return cookies[name];
}
window.readCookie = readCookie; // or expose it however you want
})();
I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach
which is browser dependent (even then you're not saving that much)
Your own example slightly compressed to 120 bytes
:
function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}
You can get it to 110 bytes
if you make it a 1-letter function name, 90 bytes
if you drop the encodeURIComponent
.
I've gotten it down to 73 bytes
, but to be fair it's 82 bytes
when named readCookie
and 102 bytes
when then adding encodeURIComponent
:
function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}
Safest and cheapest way I found is:
<?php
$b = array_values($a);
This has also the benefit to reindex the array.
This will not work as expected on associative array (hash), but neither most of previous answer.
yes
and no
, where no
is the default value.standalone="yes"
means that the XML processor must use the DTD for validation only. In that case it will not be used for:
standalone="yes"
may add validity constraints if the document uses an external DTD. When the document contains things that would require modification of the XML, such as default values for attributes, and standalone="yes"
is used then the document is invalid.standalone="yes"
may help to optimize performance of document processing.Source: The standalone pseudo-attribute is only relevant if a DTD is used
A good place to start is the sample application provided on the developer docs.
Take a look at other IME's to see what you should be aiming for. Some (like the official one) are open source.
I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.
(My use-case was slightly different, I wanted to get all digits in the number.)
The string approach gave:
10000002 function calls in 1.113 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 1.113 0.000 1.113 0.000 sandbox.py:1(get_digits_str)
1 0.000 0.000 0.000 0.000 cProfile.py:133(__exit__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
While the modular arithmetic approach gave:
10000002 function calls in 1.102 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 1.102 0.000 1.102 0.000 sandbox.py:6(get_digits_mod)
1 0.000 0.000 0.000 0.000 cProfile.py:133(__exit__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
There were 10^7 tests run with a max number size less than 10^28.
Code used for reference:
def get_digits_str(num):
for n_str in str(num):
yield int(n_str)
def get_digits_mod(num, radix=10):
remaining = num
yield remaining % radix
while remaining := remaining // radix:
yield remaining % radix
if __name__ == '__main__':
import cProfile
import random
random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]
with cProfile.Profile() as str_profiler:
for rand_num in random_inputs:
get_digits_str(rand_num)
str_profiler.print_stats(sort='cumtime')
with cProfile.Profile() as mod_profiler:
for rand_num in random_inputs:
get_digits_mod(rand_num)
mod_profiler.print_stats(sort='cumtime')
For me, the menu item Inspect Devices wasn't available (not shown at all). But, simply browsing to chrome://inspect/#devices showed me my device and I was able to use the port forward etc. I have no idea why the menu item is not displayed.
Phone: Android Galaxy S4
OS: Mac OS X
During explorative development, and to focus the SQL debugging logging on the specific method I want to check, I decorate that method with the following logger statements:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.DEBUG);
entityManager.find(Customer.class, customerID);
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.INFO);
If Your .htaccess have anything like this ... AddHandler application/x-httpd-php53 .php .php5 .php4 .php3 then comment it and try again refreshing this worked for me...
Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?
If your sample YAML is in some.yml
, then this:
require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect
gives me
{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}