I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.
First, if I'm understanding your question, you want to store your object into a String and then later to be able to read it again and re-create the Object.
Personally, when I need to do that I use ObjectOutputStream. However, there is a mandatory condition. The object you want to convert to a String and then back to an Object must be a Serializable object, and also all its attributes.
Let's Consider ReadWriteObject
, the object to manipulate and ReadWriteTest
the manipulator.
Here is how I would do it:
public class ReadWriteObject implements Serializable {
/** Serial Version UID */
private static final long serialVersionUID = 8008750006656191706L;
private int age;
private String firstName;
private String lastName;
/**
* @param age
* @param firstName
* @param lastName
*/
public ReadWriteObject(int age, String firstName, String lastName) {
super();
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ReadWriteObject [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
public class ReadWriteTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Create Object to write and then to read
// This object must be Serializable, and all its subobjects as well
ReadWriteObject inputObject = new ReadWriteObject(18, "John", "Doe");
// Read Write Object test
// Write Object into a Byte Array
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(inputObject);
byte[] rawData = baos.toByteArray();
String rawString = new String(rawData);
System.out.println(rawString);
// Read Object from the Byte Array
byte[] byteArrayFromString = rawString.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayFromString);
ObjectInputStream ois = new ObjectInputStream(bais);
Object outputObject = ois.readObject();
System.out.println(outputObject);
}
}
The Standard Output is similar to that (actually, I can't copy/paste it) :
¬í ?sr ?*com.ajoumady.stackoverflow.ReadWriteObjecto$˲é¦LÚ ?I ?ageL ?firstNamet ?Ljava/lang/String;L ?lastNameq ~ ?xp ?t ?John ?Doe
ReadWriteObject [age=18, firstName=John, lastName=Doe]
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The easiest way is to use the strconv.Atoi()
function.
Note that there are many other ways. For example fmt.Sscan()
and strconv.ParseInt()
which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi()
:
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
Here's an example using the mentioned functions (try it on the Go Playground):
flag.Parse()
s := flag.Arg(0)
if i, err := strconv.Atoi(s); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
var i int
if _, err := fmt.Sscan(s, &i); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}
Output (if called with argument "123"
):
i=123, type: int
i=123, type: int64
i=123, type: int
There is also a handy fmt.Sscanf()
which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string
.
This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123"
where you have a prefix "id:"
and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:
s := "id:00123"
var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
fmt.Println(i) // Outputs 123
}
First of all you use here two strings: "" marks a string it may be ""
-empty "s"
- string of lenght 1 or "aaa"
string of lenght 3, while '' marks chars . In order to be able to do String str = "a" + "aaa" + 'a'
you must use method Character.toString(char c) as @Thomas Keene said so an example would be String str = "a" + "aaa" + Character.toString('a')
Well, what about something like this:
PS3="Select database or <Q> to quit: "
select DB in db1 db2 db3; do
[ "${REPLY^*}" = 'Q' ] && break
echo "Should backup $DB..."
done
I think they using \n
anyway even couse it not visible, or maybe they using \r
. So just replace \n
or \r
with <br/>
Or you can make a simple function like this:
// Provided 'c' is only a numeric character
int parseInt (char c) {
return c - '0';
}
RegEx is the way to go in most cases.
In some cases, it may be faster to specify more elements or the specific element to perform the replace on:
$(document).ready(function () {
$('.myclass').each(function () {
$('img').each(function () {
$(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
})
})
});
This does the replace once on each string, but it does it using a more specific selector.
Just wanted to share a solution for unsigned long aswell.
unsigned long ToUInt(char* str)
{
unsigned long mult = 1;
unsigned long re = 0;
int len = strlen(str);
for(int i = len -1 ; i >= 0 ; i--)
{
re = re + ((int)str[i] -48)*mult;
mult = mult*10;
}
return re;
}
1) To answer your question:
String s="Java";
System.out.println(s.length());
You can use the fgets()
function to read a string or use scanf("%[^\n]s",name);
so string reading will terminate upon encountering a newline character.
Try something like this. The first row builds your URL and the rest check if it contains the word "car".
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'car') !== false) {
echo 'Car exists.';
} else {
echo 'No cars.';
}
For integers from 1 to 100 with no preceding 0 try:
^[1-9]$|^[1-9][0-9]$|^(100)$
For integers from 0 to 100 with no preceding 0 try:
^[0-9]$|^[1-9][0-9]$|^(100)$
Regards
You can also use the Uri class.
new Uri("file:///Users/smcho/filegen_from_directory/AIRPassthrough").Segments.Last()
You may prefer to use this class if you want to get some other segment, or if you want to do the same thing with a web address.
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":
String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")
Remove newlines only from the end of the line:
String.replaceAll("[\n\r]$", "")
Remove newlines only from the beginning of the line:
String.replaceAll("^[\n\r]", "")
You have to first escape the backslash because it's a literal (yielding \\
), and then escape it again because of the regular expression (yielding \\\\
). So, Try:
s.replaceAll("'", "\\\\'");
output:
You\'ll be totally awesome, I\'m really terrible
>>> string = '1abc'
>>> string[0].isdigit()
True
This is a generic Comparator
for any kind of Comparable
object, not just String
:
package util;
import java.util.Comparator;
/**
* The Default Comparator for classes implementing Comparable.
*
* @param <E> the type of the comparable objects.
*
* @author Michael Belivanakis (michael.gr)
*/
public final class DefaultComparator<E extends Comparable<E>> implements Comparator<E>
{
@SuppressWarnings( "rawtypes" )
private static final DefaultComparator<?> INSTANCE = new DefaultComparator();
/**
* Get an instance of DefaultComparator for any type of Comparable.
*
* @param <T> the type of Comparable of interest.
*
* @return an instance of DefaultComparator for comparing instances of the requested type.
*/
public static <T extends Comparable<T>> Comparator<T> getInstance()
{
@SuppressWarnings("unchecked")
Comparator<T> result = (Comparator<T>)INSTANCE;
return result;
}
private DefaultComparator()
{
}
@Override
public int compare( E o1, E o2 )
{
if( o1 == o2 )
return 0;
if( o1 == null )
return 1;
if( o2 == null )
return -1;
return o1.compareTo( o2 );
}
}
How to use with String
:
Comparator<String> stringComparator = DefaultComparator.getInstance();
test equals with an empty string and null in the same conditional:
if(!"".equals(str) && str != null) {
// do stuff.
}
Does not throws NullPointerException
if str is null, since Object.equals()
returns false if arg is null
.
the other construct str.equals("")
would throw the dreaded NullPointerException
. Some might consider bad form using a String literal as the object upon wich equals()
is called but it does the job.
Also check this answer: https://stackoverflow.com/a/531825/1532705
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
In addition to Will Dean's version, the following are common for whole buffer initialization:
char s[10] = {'\0'};
or
char s[10];
memset(s, '\0', sizeof(s));
or
char s[10];
strncpy(s, "", sizeof(s));
%W
and %w
allow you to create an Array of strings without using quotes and commas.
CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.
So, just as you use InterfaceName i = new ItsImplementation()
, you can use CharSequence cs = new String("string")
or simply CharSequence cs = "string";
Lets say you just want the first char from a part of $_POST, lets call it 'type'. And that $_POST['type'] is currently 'Control'. If in this case if you use $_POST['type'][0]
, or substr($_POST['type'], 0, 1)
you will get C
back.
However, if the client side were to modify the data they send you, from type
to type[]
for example, and then send 'Control' and 'Test' as the data for this array, $_POST['type'][0]
will now return Control
rather than C
whereas substr($_POST['type'], 0, 1)
will simply just fail.
So yes, there may be a problem with using $str[0]
, but that depends on the surrounding circumstance.
Check out Regular Expressions.
String s=null;
String is not initialized for null. if any string operation tried it can throw null pointer exception
String t="null";
It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.
String u="";
It is as empty string , It will not throw null pointer.
I was looking also a sorting fields that has letter prefix. Here is what i found out the solution. This might help who is looking for the same solution.
Field Values:
FL01,FL02,FL03,FL04,FL05,...FL100,...FL123456789
select SUBSTRING(field,3,9) as field from table order by SUBSTRING(field,3,10)*1 desc
SUBSTRING(field,3,9)
i put 9 because 9 is way enough for me to hold max 9 digits integer values.
So the result will be 123456789 123456788 123456787 ... 100 99 ... 2 1
For reference, the Base64 encoder's length formula is as follows:
As you said, a Base64 encoder given n
bytes of data will produce a string of 4n/3
Base64 characters. Put another way, every 3 bytes of data will result in 4 Base64 characters. EDIT: A comment correctly points out that my previous graphic did not account for padding; the correct formula is Ceiling(4n/3)
.
The Wikipedia article shows exactly how the ASCII string Man
encoded into the Base64 string TWFu
in its example. The input string is 3 bytes, or 24 bits, in size, so the formula correctly predicts the output will be 4 bytes (or 32 bits) long: TWFu
. The process encodes every 6 bits of data into one of the 64 Base64 characters, so the 24-bit input divided by 6 results in 4 Base64 characters.
You ask in a comment what the size of encoding 123456
would be. Keeping in mind that every every character of that string is 1 byte, or 8 bits, in size (assuming ASCII/UTF8 encoding), we are encoding 6 bytes, or 48 bits, of data. According to the equation, we expect the output length to be (6 bytes / 3 bytes) * 4 characters = 8 characters
.
Putting 123456
into a Base64 encoder creates MTIzNDU2
, which is 8 characters long, just as we expected.
Here's a very compact, but entirely correct version:
do while(isspace(*s)) s++; while(*d++ = *s++);
And here, just for my amusement, are code-golfed versions that aren't entirely correct, and get commenters upset.
If you can risk some undefined behavior, and never have empty strings, you can get rid of the body:
while(*(d+=!isspace(*s++)) = *s);
Heck, if by space you mean just space character:
while(*(d+=*s++!=' ')=*s);
Don't use that in production :)
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()
) during compilation - so when you write for example "hello world"
in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal"
) and second is constructed during runtime ie. with "new" keyword like new String("i am string literal")
, the ==
(equality) operator returns false, because both of them are different instances of the String
class.
Only right way is using .equals()
-> datos[0].equals(usuario)
. ==
says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
Do a little homework with the php online manual's string functions.
You'll want to use strlen
in a comparison setting, substr
to cut it if you need to, and the concatenation operator with "..."
or "…"
In Go 1.10+ there is strings.Builder
, here.
A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use.
It's almost the same with bytes.Buffer
.
package main
import (
"strings"
"fmt"
)
func main() {
// ZERO-VALUE:
//
// It's ready to use from the get-go.
// You don't need to initialize it.
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteString("a")
}
fmt.Println(sb.String())
}
Click to see this on the playground.
StringBuilder's methods are being implemented with the existing interfaces in mind. So that you can switch to the new Builder type easily in your code.
It can only grow or reset.
It has a copyCheck mechanism built-in that prevents accidentially copying it:
func (b *Builder) copyCheck() { ... }
In bytes.Buffer
, one can access the underlying bytes like this: (*Buffer).Bytes()
.
strings.Builder
prevents this problem.io.Reader
etc.bytes.Buffer.Reset()
rewinds and reuses the underlying buffer whereas the strings.Builder.Reset()
does not, it detaches the buffer.
Check out its source code for more details, here.
The Separator
you are using is a UI component. You would be better using a simple String sep = ", "
.
Print the Upper and Lower case alphabets in python using a built-in range function
def upperCaseAlphabets():
print("Upper Case Alphabets")
for i in range(65, 91):
print(chr(i), end=" ")
print()
def lowerCaseAlphabets():
print("Lower Case Alphabets")
for i in range(97, 123):
print(chr(i), end=" ")
upperCaseAlphabets();
lowerCaseAlphabets();
You can use regexp_substr(). Example:
create or replace type splitTable_Type is table of varchar2(100);
declare
l_split_table splitTable_Type;
begin
select
regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
bulk collect into
l_split_table
from dual
connect by
regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;
end;
The query iterates through the comma separated string, searches for the comma (,) and then splits the string by treating the comma as delimiter. It returns the string as a row, whenever it hits a delimiter.
level
in statement regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
refers to a pseudocolumn in Oracle which is used in a hierarchical query to identify the hierarchy level in numeric format: level in connect by
To split your String by comma(,) use str.split(",")
and for tab use str.split("\\t")
try {
BufferedReader in = new BufferedReader(
new FileReader("G:\\RoutePPAdvant2.txt"));
String str;
while ((str = in.readLine())!= null) {
String[] ar=str.split(",");
...
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
What you have seems to be a string
incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space
(U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
string junk = "déjÃ\xa0"; // Bad Unicode string
// Turn string back to bytes using the original, incorrect encoding.
byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);
// Use the correct encoding this time to convert back to a string.
string good = Encoding.UTF8.GetString(bytes);
Console.WriteLine(good);
}
}
Result:
déjà
import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)
and you shall see your result as
'askhnlaskdjalsdk
Found lines that only starts with 6 spaces and finished with:
cat my_file.txt | grep
-e '^ .*(\.c$|\.cpp$|\.h$|\.log$|\.out$)' # .c or .cpp or .h or .log or .out
-e '^ .*[0-9]\{5,9\}$' # numers between 5 and 9 digist
> nolog.txt
Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)
You can directly instanciate the BigDecimal with the String ;)
Example:
BigDecimal bigDecimalValue= new BigDecimal("0.5");
Another possible way:
open my $fh, '<', "filename";
read $fh, my $string, -s $fh;
close $fh;
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 faced a similar problem. I had a string which contained path to a folder in Windows e.g. C:\Users\
The problem is that \
is an escape character and so in order to use it in strings you need to add one more \
.
Incorrect: C:\Users\
Correct: C:\\\Users\\\
Use Data.List.Split
, which uses split
:
[me@localhost]$ ghci
Prelude> import Data.List.Split
Prelude Data.List.Split> let l = splitOn "," "1,2,3,4"
Prelude Data.List.Split> :t l
l :: [[Char]]
Prelude Data.List.Split> l
["1","2","3","4"]
Prelude Data.List.Split> let { convert :: [String] -> [Integer]; convert = map read }
Prelude Data.List.Split> let l2 = convert l
Prelude Data.List.Split> :t l2
l2 :: [Integer]
Prelude Data.List.Split> l2
[1,2,3,4]
import org.apache.commons.lang3.StringUtils;
...
StringUtils.substringBefore("Grigory Kislin", " ")
if "ABCD" in "xxxxABCDyyyy":
# whatever
Why not use gnu getopts? Here's a basic example (without safety checks):
#include <getopt.h>
#include <stdio.h>
int main(int argc, char** argv)
{
option long_options[] = {
{"foo", required_argument, 0, 0},
{0,0,0,0}
};
getopt_long(argc, argv, "f:", long_options, 0);
printf("%s\n", optarg);
}
For the following command:
$ ./a.out --foo=33
You will get
33
Using back ticks you can have multiline strings:
package main
import "fmt"
func main() {
message := `This is a
Multi-line Text String
Because it uses the raw-string back ticks
instead of quotes.
`
fmt.Printf("%s", message)
}
Instead of using either the double quote (“) or single quote symbols (‘), instead use back-ticks to define the start and end of the string. You can then wrap it across lines.
If you indent the string though, remember that the white space will count.
Please check the playground and do experiments with it.
We can use slice to do this:
val = "abc"
=> "abc"
val.slice!(0)
=> "a"
val
=> "bc"
Using slice!
we can delete any character by specifying its index.
I have to disagree one of the comments in one point:
[ "$x" == "valid" ] && echo "valid" || echo "invalid"
It's just it looks like one to, hmm, the uninitiated...
It uses common patterns as a language, in a way;
And after you learned the language.
It is a simple logical expression, with one special part: lazy evaluation of the logic operators.
[ "$x" == "valid" ] && echo "valid" || echo "invalid"
Each part is a logical expression; the first may be true or false, the other two are always true.
(
[ "$x" == "valid" ]
&&
echo "valid"
)
||
echo "invalid"
Now, when it is evaluated, the first is checked. If it is false, than the second operand of the logic and &&
after it is not relevant. The first is not true, so it can not be the first and the second be true, anyway.
Now, in this case is the the first side of the logic or ||
false, but it could be true if the other side - the third part - is true.
So the third part will be evaluated - mainly writing the message as a side effect. (It has the result 0
for true, which we do not use here)
The other cases are similar, but simpler - and - I promise! are - can be - easy to read!
(I don't have one, but I think being a UNIX veteran with grey beard helps a lot with this.)
@DanielVelkov answer is the proper one BUT using string literals is faster:
# Daniel's
%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# String literals - python 3
%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Remember that from version 3 exec
is a function!
so always use exec(mystring)
instead of exec mystring
.
int n;
bool isNumeric = int.TryParse("123", out n);
Update As of C# 7:
var isNumeric = int.TryParse("123", out int n);
or if you don't need the number you can discard the out parameter
var isNumeric = int.TryParse("123", out _);
The var s can be replaced by their respective types!
This is super old, but I figured I'd add my 2c. DATE_FORMAT
does indeed return a string, but I was looking for the CAST
function, in the situation that I already had a datetime string in the database and needed to pattern match against it:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
In this case, you'd use:
CAST(date_value AS char)
This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.
There is no explicit analogue - i think you are expected to use string concatenations(likely optimized as said before) or third-party class(i doubt that they are a lot more efficient - lists in python are dynamic-typed so no fast-working char[] for buffer as i assume). Stringbuilder-like classes are not premature optimization because of innate feature of strings in many languages(immutability) - that allows many optimizations(for example, referencing same buffer for slices/substrings). Stringbuilder/stringbuffer/stringstream-like classes work a lot faster than concatenating strings(producing many small temporary objects that still need allocations and garbage collection) and even string formatting printf-like tools, not needing of interpreting formatting pattern overhead that is pretty consuming for a lot of format calls.
If you only have a single newline in the input, just doing
std::cin.ignore();
will work fine. It reads and discards the next character from the input.
But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
See e.g. this reference of the ignore
function.
To be even more safe, do the second alternative above in a loop until gcount
returns zero.
Use;
^(19|[2-9][0-9])\d{2}$
for years 1900 - 9999.
No need to worry for 9999 and onwards - A.I. will be doing all programming by then !!! Hehehehe
You can test your regex at https://regex101.com/
Also more info about non-capturing groups ( mentioned in one the comments above ) here http://www.manifold.net/doc/radian/why_do_non-capture_groups_exist_.htm
XSLT 2.0 has upper-case()
and lower-case()
functions. In case of XSLT 1.0, you can use translate()
:
<xsl:value-of select="translate("xslt", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")" />
Similar to @Matthew_Plourde using gsub
However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:
cs <- c("foo_bar","bar_foo","apple","beer","so","a")
gsub('.{0,3}$', '', cs)
# [1] "foo_" "bar_" "ap" "b" "" ""
Difference is, {0,3}
quantifier indicates 0 to 3 matches, whereas {3}
requires exactly 3 matches otherwise no match is found in which case gsub
returns the original, unmodified string.
N.B. using {,3}
would be equivalent to {0,3}
, I simply prefer the latter notation.
See here for more information on regex quantifiers: https://www.regular-expressions.info/refrepeat.html
In spite of how old this question is and similar to this answer by technosaurus. I had a hard time finding a solution that was portable across most platforms (That I Use) as well as older versions of bash. I have also been frustrated with arrays, functions and use of prints, echos and temporary files to retrieve trivial variables. This works very well for me so far I thought I would share. My main testing environments are:
- GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
- GNU bash, version 3.2.57(1)-release (sparc-sun-solaris2.10)
lcs="abcdefghijklmnopqrstuvwxyz"
ucs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
input="Change Me To All Capitals"
for (( i=0; i<"${#input}"; i++ )) ; do :
for (( j=0; j<"${#lcs}"; j++ )) ; do :
if [[ "${input:$i:1}" == "${lcs:$j:1}" ]] ; then
input="${input/${input:$i:1}/${ucs:$j:1}}"
fi
done
done
Simple C-style for loop to iterate through the strings. For the line below if you have not seen anything like this before this is where I learned this. In this case the line checks if the char ${input:$i:1} (lower case) exists in input and if so replaces it with the given char ${ucs:$j:1} (upper case) and stores it back into input.
input="${input/${input:$i:1}/${ucs:$j:1}}"
You can use:
if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
//...
}
This works with any .NET version.
from random import randint
def shuffle_word(word):
newWord=""
for i in range(0,len(word)):
pos=randint(0,len(word)-1)
newWord += word[pos]
word = word[:pos]+word[pos+1:]
return newWord
word = "Sarajevo"
print(shuffle_word(word))
You can do in different ways.
str1 = "Hello"
str2 = "World"
str_list = ['Hello', 'World']
str_dict = {'str1': 'Hello', 'str2': 'World'}
# Concatenating With the + Operator
print(str1 + ' ' + str2) # Hello World
# String Formatting with the % Operator
print("%s %s" % (str1, str2)) # Hello World
# String Formatting with the { } Operators with str.format()
print("{}{}".format(str1, str2)) # Hello World
print("{0}{1}".format(str1, str2)) # Hello World
print("{str1} {str2}".format(str1=str_dict['str1'], str2=str_dict['str2'])) # Hello World
print("{str1} {str2}".format(**str_dict)) # Hello World
# Going From a List to a String in Python With .join()
print(' '.join(str_list)) # Hello World
# Python f'strings --> 3.6 onwards
print(f"{str1} {str2}") # Hello World
I created this little summary through following articles.
'' encloses single char
, while "" encloses a String
.
Change
y = 'hello';
-->
y = "hello";
in case someone got stuck with this and none of the answers above worked, below is what worked for me. Hope it helps.
var oldString = "\\r|\\n";
// None of these worked for me
// var newString = oldString(@"\\", @"\");
// var newString = oldString.Replace("\\\\", "\\");
// var newString = oldString.Replace("\\u5b89", "\u5b89");
// var newString = Regex.Replace(oldString , @"\\", @"\");
// This is what worked
var newString = Regex.Unescape(oldString);
// newString is now "\r|\n"
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
Do you mean like this?
import string
astr='a(b[c])d'
deleter=string.maketrans('()[]',' ')
print(astr.translate(deleter))
# a b c d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a
There is no need to set the delimiter by breaking it up in pieces like you have done.
Here is a complete program you can compile and run:
import java.util.Arrays;
public class SplitExample {
public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
public static void main(String[] args) {
String[] data = PLAYER.split("\\|\\|");
System.out.println(Arrays.toString(data));
}
}
If you want to use split with a pattern, you can use Pattern.compile
or Pattern.quote
.
To see compile
and quote
in action, here is an example using all three approaches:
import java.util.Arrays;
import java.util.regex.Pattern;
public class SplitExample {
public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
public static void main(String[] args) {
String[] data = PLAYER.split("\\|\\|");
System.out.println(Arrays.toString(data));
Pattern pattern = Pattern.compile("\\|\\|");
data = pattern.split(PLAYER);
System.out.println(Arrays.toString(data));
pattern = Pattern.compile(Pattern.quote("||"));
data = pattern.split(PLAYER);
System.out.println(Arrays.toString(data));
}
}
The use of patterns is recommended if you are going to split often using the same pattern. BTW the output is:
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
You could use a global variable:
declare globalvar='some string'
string ()
{
eval "$1='some other string'"
} # ---------- end of function string ----------
string globalvar
echo "'${globalvar}'"
This gives
'some other string'
I was intrigued by this, I ran this random word generator on a dictionary word list. Range: Integer.MIN_VALUE to Integer.MAX_VALUE
I got 15131 hits.
int[] arrInt = {-2146926310, -1885533740, -274140519,
-2145247212, -1845077092, -2143584283,
-2147483454, -2138225126, -2147375969};
for(int seed : arrInt){
System.out.print(randomString(seed) + " ");
}
Prints
the quick browny fox jumps over a lazy dog
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
The code removes all newlines from the string str
.
O(N) implementation best served without comments on SO and with comments in production.
unsigned shift=0;
for (unsigned i=0; i<length(str); ++i){
if (str[i] == '\n') {
++shift;
}else{
str[i-shift] = str[i];
}
}
str.resize(str.length() - shift);
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\b
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b
is located:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.
To convert a valid JSON string back, you can use the json_decode()
method.
To convert it back to an object use this method:
$jObj = json_decode($jsonString);
And to convert it to a associative array, set the second parameter to true
:
$jArr = json_decode($jsonString, true);
By the way to convert your mentioned string back to either of those, you should have a valid JSON string. To achieve it, you should do the following:
Coords
array, remove the two "
(double quote marks) from the start and end of the object.,
), so add commas between the objects in the Coords
array..And you will have a valid JSON String..
Here is your JSON String I converted to a valid one: http://pastebin.com/R16NVerw
That worked for me.
string address=senderAddress.Replace("'", "\\'");
We show up two functions that prints a SINGLE character to binary.
void printbinchar(char character)
{
char output[9];
itoa(character, output, 2);
printf("%s\n", output);
}
printbinchar(10) will write into the console
1010
itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".
The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.
void printbincharpad(char c)
{
for (int i = 7; i >= 0; --i)
{
putchar( (c & (1 << i)) ? '1' : '0' );
}
putchar('\n');
}
printbincharpad(10) will write into the console
00001010
Now i present a function that prints out an entire string (without last null character).
void printstringasbinary(char* s)
{
// A small 9 characters buffer we use to perform the conversion
char output[9];
// Until the first character pointed by s is not a null character
// that indicates end of string...
while (*s)
{
// Convert the first character of the string to binary using itoa.
// Characters in c are just 8 bit integers, at least, in noawdays computers.
itoa(*s, output, 2);
// print out our string and let's write a new line.
puts(output);
// we advance our string by one character,
// If our original string was "ABC" now we are pointing at "BC".
++s;
}
}
Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:
1000001
1000010
110001
When you say [:-1]
you are stripping the last element. Instead of slicing the string, you can apply startswith
and endswith
on the string object itself like this
if str1.startswith('"') and str1.endswith('"'):
So the whole program becomes like this
>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
... print "hi"
>>> else:
... print "condition fails"
...
hi
Even simpler, with a conditional expression, like this
>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
str = "aaaaabbbb"
newstr = str[-4:]
nchar(YOURSTRING)
you may need to convert to a character vector first;
nchar(as.character(YOURSTRING))
**
I hope this code is beneficial
**
String user = getResources().getString(R.string.muser);
You can also use Java's implicit conversion:
BigInteger m = new BigInteger(bytemsg);
String mStr = "" + m; // mStr now contains string representation of m.
For completeness, difflib
in the standard-library provides loads of sequence-comparison utilities. For instance find_longest_match
which finds the longest common substring when used on strings. Example use:
from difflib import SequenceMatcher
string1 = "apple pie available"
string2 = "come have some apple pies"
match = SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))
print(match) # -> Match(a=0, b=15, size=9)
print(string1[match.a: match.a + match.size]) # -> apple pie
print(string2[match.b: match.b + match.size]) # -> apple pie
This sets independent, best-fit column widths based on the max-metric used in other answers.
data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
padding = 2
col_widths = [max(len(w) for w in [r[cn] for r in data]) + padding for cn in range(len(data[0]))]
format_string = "{{:{}}}{{:{}}}{{:{}}}".format(*col_widths)
for row in data:
print(format_string.format(*row))
Currently there is still no native solution in Javascript for this behavior. Tagged templates are something related, but don't solve it.
Here there is a refactor of alex's solution with an object for replacements.
The solution uses arrow functions and a similar syntax for the placeholders as the native Javascript interpolation in template literals ({}
instead of %%
). Also there is no need to include delimiters (%
) in the names of the replacements.
There are two flavors (three with the update): descriptive, reduced, elegant reduced with groups.
Descriptive solution:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(
/{\w+}/g,
placeholderWithDelimiters => {
const placeholderWithoutDelimiters = placeholderWithDelimiters.substring(
1,
placeholderWithDelimiters.length - 1,
);
const stringReplacement = replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters;
return stringReplacement;
},
);
console.log(string);
_x000D_
Reduced solution:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(/{\w+}/g, placeholder =>
replacements[placeholder.substring(1, placeholder.length - 1)] || placeholder
);
console.log(string);
_x000D_
Elegant reduced solution with groups, as suggested by @Kade in the comments:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(
/{(\w+)}/g,
(placeholderWithDelimiters, placeholderWithoutDelimiters) =>
replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters
);
console.log(string);
_x000D_
Support empty string as a replacement, as suggested by @Jesper in the comments:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '',
};
const string = stringWithPlaceholders.replace(
/{(\w+)}/g,
(placeholderWithDelimiters, placeholderWithoutDelimiters) =>
replacements.hasOwnProperty(placeholderWithoutDelimiters) ?
replacements[placeholderWithoutDelimiters] : placeholderWithDelimiters
);
console.log(string);
_x000D_
Using compound ternary statements can be somewhat elegant for enums with few elements (one-liner). The expression only grows approximately linearly in length with the number of elements too.
Here's a good use case:
enum log_level {INFO, WARNING, ERROR};
...
void logger::write(const std::string log, const log_level l) {
...
std::string s = (l == INFO) ? "INFO" :
(l == WARNING) ? "WARNING" :
(l == ERROR) ? "ERROR" : "UNKNOWN";
...
}
...
Of course, it's just another switch/if statement block, but it's a single line statement. And as a matter of terseness vs. simplicity, it meets somewhere in the middle. As a constant expression, it can be easily made into an inline function as well.
In Java 11, we can use the Collection.toArray(generator)
method. The following code will create a new array of strings:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
You need to escape the dot if you want to split on a literal dot:
String extensionRemoved = filename.split("\\.")[0];
Otherwise you are splitting on the regex .
, which means "any character".
Note the double backslash needed to create a single backslash in the regex.
You're getting an ArrayIndexOutOfBoundsException
because your input string is just a dot, ie "."
, which is an edge case that produces an empty array when split on dot; split(regex)
removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.
To avoid getting an ArrayIndexOutOfBoundsException
for this edge case, use the overloaded version of split(regex, limit)
, which has a second parameter that is the size limit for the resulting array. When limit
is negative, the behaviour of removing trailing blanks from the resulting array is disabled:
".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]
ie, when filename
is just a dot "."
, calling filename.split("\\.", -1)[0]
will return a blank, but calling filename.split("\\.")[0]
will throw an ArrayIndexOutOfBoundsException
.
In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.
ResourceManager
shouldn't be needed unless you're loading from an external resource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:
Assuming a project namespace: UberSoft.WidgetPro
And your resx contains:
You can just use:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
You can use pandas.Series.map :
df['col'].map('str{}'.format)
It will apply the word "str" before all your values.
You can just do:
string myStr = "The quick brown fox jumps over the lazy dog";
string[] ssizes = myStr.Split(' ');
MSDN has more examples and references:
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
Output :
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
Explanation :
Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.
Hope this helps you.
If the file is text, and you want to get the text line by line, the easiest way is to use fgets().
char buffer[100];
FILE *fp = fopen("filename", "r"); // do not use "rb"
while (fgets(buffer, sizeof(buffer), fp)) {
... do something
}
fclose(fp);
Here's a recursive approach to it.
function pad(width, string, padding) {
return (width <= string.length) ? string : pad(width, padding + string, padding)
}
An example...
pad(5, 'hi', '0')
=> "000hi"
The best answer I can find, is in one of the comments here. Adding it to the answer so that someone won't miss the comment and should definitely try this out. It fixed the issue for me.
We need to map the solution folder to a drive using the "subst" command in command prompt- e.g., subst z:
And then open the solution from this drive (z in this case). This would shorten the path as much as possible and could solve the lengthy filename issue.
There's a bug here: currently cannot pass arguments to str.lstrip
and str.rstrip
:
http://github.com/pydata/pandas/issues/2411
EDIT: 2012-12-07 this works now on the dev branch:
In [8]: df['result'].str.lstrip('+-').str.rstrip('aAbBcC')
Out[8]:
1 52
2 62
3 44
4 30
5 110
Name: result
Is it also possible to access the management port in a similar way, e.g.:
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomServerPort;
@LocalManagementPort
int randomManagementPort;
RewriteCond %{HTTP:X-Forwarded-Proto} =https
I use the ffmpeg-python
binding. You can find more information here.
import ffmpeg
(
ffmpeg
.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
.output('movie.mp4')
.run()
)
@mixin box-shadow($args...) {
@each $pre in -webkit-, -moz-, -ms-, -o- {
#{$pre + box-shadow}: $args;
}
#{box-shadow}: #{$args};
}
And now you can reuse your box-shadow even smarter:
.myShadow {
@include box-shadow(2px 2px 5px #555, inset 0 0 0);
}
As of Angular Material v9, it now has a clipboard CDK
It can be used as simply as
<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>
I found a solution today which was to:
The problem with their documentation is that they do not specify a link to where you should get a copy of the entire font-awesome project to put into your project.
This just happen to me because in the php.ini the date.timezone was not set!
;date.timezone=Europe/Berlin
Using the php date() function triggered that warning.
To overrule the default strategy you can create a simple method in the class where you are wired your restTemplate:
protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder
.create()
.setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
.build()));
}
Note: Surely you need to handle exceptions since this method only throws them further!
Hope this helps you or someone else
enum class EnumClass : int //set size for enum
{
Zero, One, Two, Three, Four
};
union Union //This will allow us to convert
{
EnumClass ec;
int i;
};
int main()
{
using namespace std;
//convert from strongly typed enum to int
Union un2;
un2.ec = EnumClass::Three;
cout << "un2.i = " << un2.i << endl;
//convert from int to strongly typed enum
Union un;
un.i = 0;
if(un.ec == EnumClass::Zero) cout << "True" << endl;
return 0;
}
default value is chosen at runtime based on system configuration
Have a look at the documentation page
Default Heap Size
Unless the initial and maximum heap sizes are specified on the command line, they are calculated based on the amount of memory on the machine.
Client JVM Default Initial and Maximum Heap Sizes:
The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes (MB) and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte (GB).
Server JVM Default Initial and Maximum Heap Sizes:
On 32-bit JVMs, the default maximum heap size can be up to 1 GB if there is 4 GB or more of physical memory. On 64-bit JVMs, the default maximum heap size can be up to 32 GB if there is 128 GB or more of physical memory
What system configuration settings influence the default value?
You can specify the initial and maximum heap sizes using the flags -Xms (initial heap size) and -Xmx (maximum heap size). If you know how much heap your application needs to work well, you can set -Xms and -Xmx to the same value
Here's a stored procedure that will put the first word found into First Name, the last word into Last Name and everything in between into Middle Name.
create procedure [dbo].[import_ParseName]
(
@FullName nvarchar(max),
@FirstName nvarchar(255) output,
@MiddleName nvarchar(255) output,
@LastName nvarchar(255) output
)
as
begin
set @FirstName = ''
set @MiddleName = ''
set @LastName = ''
set @FullName = ltrim(rtrim(@FullName))
declare @ReverseFullName nvarchar(max)
set @ReverseFullName = reverse(@FullName)
declare @lengthOfFullName int
declare @endOfFirstName int
declare @beginningOfLastName int
set @lengthOfFullName = len(@FullName)
set @endOfFirstName = charindex(' ', @FullName)
set @beginningOfLastName = @lengthOfFullName - charindex(' ', @ReverseFullName) + 1
set @FirstName = case when @endOfFirstName <> 0
then substring(@FullName, 1, @endOfFirstName - 1)
else ''
end
set @MiddleName = case when (@endOfFirstName <> 0 and @beginningOfLastName <> 0 and @beginningOfLastName > @endOfFirstName)
then ltrim(rtrim(substring(@FullName, @endOfFirstName , @beginningOfLastName - @endOfFirstName)))
else ''
end
set @LastName = case when @beginningOfLastName <> 0
then substring(@FullName, @beginningOfLastName + 1 , @lengthOfFullName - @beginningOfLastName)
else ''
end
return
end
And here's me calling it.
DECLARE @FirstName nvarchar(255),
@MiddleName nvarchar(255),
@LastName nvarchar(255)
EXEC [dbo].[import_ParseName]
@FullName = N'Scott The Other Scott Kowalczyk',
@FirstName = @FirstName OUTPUT,
@MiddleName = @MiddleName OUTPUT,
@LastName = @LastName OUTPUT
print @FirstName
print @MiddleName
print @LastName
output:
Scott
The Other Scott
Kowalczyk
BLOB is for binary data (videos, images, documents, other)
CLOB is for large text data (text)
Maximum size on MySQL 2GB
Maximum size on Oracle 128TB
How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle
: FixedDialog
MinimizeBox
: false
MaximizeBox
: false
unnest
can be used as well.
It expands array to a set of rows and then simply checking a value exists or not is as simple as using IN
or NOT IN
.
e.g.
id => uuid
exception_list_ids => uuid[]
select * from table where id NOT IN (select unnest(exception_list_ids) from table2)
var dict = []; // create an empty array
dict.push({
key: "keyName",
value: "the value"
});
// repeat this last part as needed to add more key/value pairs
Basically, you're creating an object literal with 2 properties (called key
and value
) and inserting it (using push()
) into the array.
Edit: So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS object literal (aka map, aka hash, aka dictionary).
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key
and value
properties. Don't ask me why that structure was required, but it's the one that was asked for.
But, but, if what you want in a plain JS object - and not the structure OP asked for - see tcll's answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JS names. You can just do this:
// object literal with properties
var dict = {
key1: "value1",
key2: "value2"
// etc.
};
Or use regular dot-notation to set properties after creating an object:
// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.
You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:
var dict = {};
// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";
// but this will
dict["some invalid key (for multiple reasons)"] = "value1";
You also want bracket notation if your keys are dynamic:
dict[firstName + " " + lastName] = "some value";
Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g. a Date
object gets converted to its string representation:
dict[new Date] = "today's value";
console.log(dict);
// => {
// "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
// }
Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]"
which doesn't make for a non-unique key. So be wary of something like:
var objA = { a: 23 },
objB = { b: 42 };
dict[objA] = "value for objA";
dict[objB] = "value for objB";
console.log(dict);
// => { "[object Object]": "value for objB" }
Despite objA
and objB
being completely different and unique elements, they both have the same basic string representation: "[object Object]"
.
The reason Date
doesn't behave like this is that the Date
prototype has a custom toString
method which overrides the default string representation. And you can do the same:
// a simple constructor with a toString prototypal method
function Foo() {
this.myRandomNumber = Math.random() * 1000 | 0;
}
Foo.prototype.toString = function () {
return "Foo instance #" + this.myRandomNumber;
};
dict[new Foo] = "some value";
console.log(dict);
// => {
// "Foo instance #712": "some value"
// }
(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of toString
.)
So when trying to use objects as keys, JS will use the object's own toString
implementation, if any, or use the default string representation.
Optional parameters are kind of like a macro substitution from what I understand. They are not really optional from the method's point of view. An artifact of that is the behavior you see where you get different results if you cast to an interface.
I had the problem and was tinkering with different solutions mentioned here. Since I was running my project from Visual Studio, apparently, I needed to set the environment path inside Visual Studio and not the system path.
Adding a simple PYTHONHOME=PATH\TO\PYTHON\DIR in the project solution\properties\environment solved the problem.
If you're uncertain of the type of the variable (it could be a string of number characters), say it was a credit card number passed into the params, so it would originally be a string but you want to make sure it doesn't have any letter characters in it, I would use this method:
def is_number?(obj)
obj.to_s == obj.to_i.to_s
end
is_number? "123fh" # false
is_number? "12345" # true
@Benny points out an oversight of this method, keep this in mind:
is_number? "01" # false. oops!
You can do something like this:
public void putOverlay(Bitmap bitmap, Bitmap overlay) {
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(overlay, 0, 0, paint);
}
The idea is very simple: Once you associate a bitmap with a canvas, you can call any of the canvas' methods to draw over the bitmap.
This will work for bitmaps that have transparency. A bitmap will have transparency, if it has an alpha channel. Look at Bitmap.Config. You'd probably want to use ARGB_8888.
Important: Look at this Android sample for the different ways you can perform drawing. It will help you a lot.
Performance wise (memory-wise, to be exact), Bitmaps are the best objects to use, since they simply wrap a native bitmap. An ImageView is a subclass of View, and a BitmapDrawable holds a Bitmap inside, but it holds many other things as well. But this is an over-simplification. You can suggest a performance-specific scenario for a precise answer.
Swift 4, 5
To pin a view to a safe area anchor using constraints can be done anywhere in the view controller's lifecycle because they're queued by the API and handled after the view has been loaded into memory. However, getting safe-area values requires waiting toward the end of a view controller's lifecycle, like viewDidLayoutSubviews()
.
This plugs into any view controller:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let topSafeArea: CGFloat
let bottomSafeArea: CGFloat
if #available(iOS 11.0, *) {
topSafeArea = view.safeAreaInsets.top
bottomSafeArea = view.safeAreaInsets.bottom
} else {
topSafeArea = topLayoutGuide.length
bottomSafeArea = bottomLayoutGuide.length
}
// safe area values are now available to use
}
I prefer this method to getting it off of the window (when possible) because it’s how the API was designed and, more importantly, the values are updated during all view changes, like device orientation changes.
However, some custom presented view controllers cannot use the above method (I suspect because they are in transient container views). In such cases, you can get the values off of the root view controller, which will always be available anywhere in the current view controller's lifecycle.
anyLifecycleMethod()
guard let root = UIApplication.shared.keyWindow?.rootViewController else {
return
}
let topSafeArea: CGFloat
let bottomSafeArea: CGFloat
if #available(iOS 11.0, *) {
topSafeArea = root.view.safeAreaInsets.top
bottomSafeArea = root.view.safeAreaInsets.bottom
} else {
topSafeArea = root.topLayoutGuide.length
bottomSafeArea = root.bottomLayoutGuide.length
}
// safe area values are now available to use
}
I will just repeat what @Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.
import matplotlib
matplotlib.use('Agg')
Or one would get error
*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*
This will resolve all Display issue
For the latest version of Bitbucket (2016+), the download link can be found in the Download menu item.
Pre-2016
First method
In the Overview page of the repo, there is a link to download the project.
Second method
Go to Downloads -> Branches -> Download the branch that you want (as .zip, .gz or .bz2). There you'll find download links for all tags. The links will be in the format:
https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz
By tweaking it a little bit, you can also have access to any revision by changing the tag to the commit hash:
https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz
You can use:
double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;
You can do it by javascript on client side or using some regex validator on the textbox.
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
I think SetInterval
and SetTimeout
are different. SetInterval
executes the block according to the time set while, SetTimeout
executes the block of code once.
Try these set of codes after the timeout countdown seconds:
setInterval(function(e){
alert('Ugbana Kelvin');
}, 2000);
and then try
setTimeout(function(e){
alert('Ugbana Kelvin');
}, 2000);
You can see the differences for yourself.
Use
//find first element with "someAttr" attribute
document.querySelector('[someAttr]')
or
//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]')
to find elements by attribute. It's now supported in all relevant browsers (even IE8): http://caniuse.com/#search=queryselector
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
You can try:
select(data, matches("search_string"))
It is more general than contains
- you can use regex (e.g. "one_string|or_the_other"
).
For more examples, see: http://rpackages.ianhowson.com/cran/dplyr/man/select.html.
Here is an implementation which calculates both positive and negative factorials. It's fast and simple.
var factorial = function(n) {
return n > 1
? n * factorial(n - 1)
: n < 0
? n * factorial(n + 1)
: 1;
}
As of PowerShell version 3.0, the Get-Content cmdlet has a -Tail parameter that should help. See the technet library online help for Get-Content.
To add to @Christian's comment:
Replace all single or double quotes in a string:
s = "'asdfa sdfa'"
import re
re.sub("[\"\']", "", s)
you can change
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
at the component level in constructor like bellow
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
That should work via HTTPRewriteModule.
Example rewrite from www.example.com to example.com:
server {
server_name www.example.com;
rewrite ^ http://example.com$request_uri? permanent;
}
How about try some different mirrors? If you are in China, I highly recommend you try:
sudo pip install --index https://pypi.mirrors.ustc.edu.cn/simple/ opencv-contrib-python
If not, just replace the url address to some other mirrors you like! Good luck.
Could you try this out?
=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0)
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)
Note: Setting Hidden to False will make the row visible
I had a similar issue in Ubuntu 16.04 and what help me was that i installed php-mysql for php 7.2. I would recommend you run the following command if you have php 7.2 or install php mysql depending on your version of PHP. Make sure that you have installed the DBAL packege
apt-get install php7.2-mysql
systemctl restart apache2
If you know your format is PDF, then I don't see how the HTML tag can be useful... It definitely does not seem to work for me. The other pure LaTeX solutions obviously work just fine. But the whole point of Markdown is not to do LaTeX but to allow for multiple format compilation I believe, including HTML.
Therefore, with this in mind, what works for me is a variation of Nicolas Hamilton's answer to Color Text Stackoverflow question:
#############
## CENTER TXT
ctrFmt = function(x){
if(out_type == 'latex' || out_type == 'beamer')
paste0("\\begin{center}\n", x, "\n\\end{center}")
else if(out_type == 'html')
paste0("<center>\n", x, "\n</center>")
else
x
}
I put this inside my initial setup chunk.
Then I use it very easily in my .rmd
file:
`r ctrFmt("Centered text in html and pdf!")`
I would say not.
If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.
With not null set, then you can't insert a null value into the field as it'll throw an error.
Think of it as a fail safe mechanism to prevent nulls.
The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.
The jquery each
runs the inner loop; I needed the regular JavaScript for
on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.
This is only 5 main lines of code but wrapped onto multiple lines for display:
$.get("data.php", function(data){
for (var propTitle in data) {
$('<div></div>')
.addClass('heading')
.insertBefore('#contentHere')
.text(propTitle);
$(data[propTitle]).each(function(iRec, oRec) {
$('<div></div>')
.addClass(oRec.textType)
.attr('id', 'T'+oRec.textId)
.insertBefore('#contentHere')
.text(oRec.text);
});
}
});
Produces the output
(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")
<div class="heading">
justIn
</div>
<div id="T123" class="Greeting">
1Hello
</div>
<div id="T514" class="Question">
1What's up?
</div>
<div id="T122" class="Order">
1Come over here
</div>
<div class="heading">
recent
</div>
<div id="T1255" class="Greeting">
2Hello
</div>
<div id="T6564" class="Question">
2What's up?
</div>
<div id="T0192" class="Order">
2Come over here
</div>
<div class="heading">
old
</div>
<div id="T5213" class="Greeting">
3Hello
</div>
<div id="T9758" class="Question">
3What's up?
</div>
<div id="T7655" class="Order">
3Come over here
</div>
<div id="contentHere"></div>
Apply a style sheet
<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>
to get a "beautiful" looking set of data
More Info
The JSON data was used in the following way:
for each category (key name the array is held under):
for each object held inside an array:
In [44]: df['gdp'] = df['gdp'].shift(-1)
In [45]: df
Out[45]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
4 6 NaN 7
In [46]: df[:-1]
Out[46]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
I'll throw this out there and then duck. The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:
Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
' False otherwise.
Dim errorNum As Long
'***************************************************************************
' Open the file or determine that it doesn't exist.
On Error Resume Next:
Set wkBook = Workbooks.Open(fileName:=filePathName)
If Err.Number <> 0 Then
errorNum = Err.Number
'Error while attempting to open the file. Maybe it doesn't exist?
If Err.Number = 1004 Then
'***************************************************************************
'File doesn't exist.
'Better clear the error and point to the error handler before moving on.
Err.Clear
On Error GoTo OPENFILETEST_FAIL:
'[Clever code here to cope with non-existant file]
'...
'If the problem could not be resolved, invoke the error handler.
Err.Raise errorNum
Else
'No idea what the error is, but it's not due to a non-existant file
'Invoke the error handler.
Err.Clear
On Error GoTo OPENFILETEST_FAIL:
Err.Raise errorNum
End If
End If
'Either the file was successfully opened or the problem was resolved.
openFileTest = True
Exit Function
OPENFILETEST_FAIL:
errorNum = Err.Number
'Presumabley the problem is not a non-existant file, so it's
'some other error. Not sure what this would be, so...
If errorHandlingMethod < 2 Then
'The easy out is to clear the error, reset to the default error handler,
'and raise the error number again.
'This will immediately cause the code to terminate with VBA's standard
'run time error Message box:
errorNum = Err.Number
Err.Clear
On Error GoTo 0
Err.Raise errorNum
Exit Function
ElseIf errorHandlingMethod = 2 Then
'Easier debugging, generate a more informative message box, then terminate:
MsgBox "" _
& "Error while opening workbook." _
& "PathName: " & filePathName & vbCrLf _
& "Error " & errorNum & ": " & Err.Description & vbCrLf _
, vbExclamation _
, "Failure in function OpenFile(), IO Module"
End
Else
'The calling function is ok with a false result. That is the point
'of returning a boolean, after all.
openFileTest = False
Exit Function
End If
End Function 'openFileTest()
It's probably because size of a frame includes the size of the border.
A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).
Source: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
LD_LIBRARY_PATH
is searched when the program starts, LIBRARY_PATH
is searched at link time.
caveat from comments:
ld
(instead of gcc
or g++
), the LIBRARY_PATH
or LD_LIBRARY_PATH
environment variables are not read.gcc
or g++
, the LIBRARY_PATH
environment variable is read (see documentation "gcc
uses these directories when searching for ordinary libraries").Once you have the indexPath of your cell, you can do something like:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
In Xcode 4.6 and higher:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
You can set whatever your like as animation effect, of course.
In case you're inside a Sub of Function and you want to exit it, you can use :
Exit Sub
or
Exit Function
from the terminal u can simply say
expoort FLASK_APP=app_name.py
export FLASK_ENV=development
flask run
or in ur file
if __name__ == "__main__":
app.run(debug=True)
This is how I managed to do what I was trying to do:
[Test]
public void TransferHandlesDisconnect()
{
// ... set up config here
var methodTester = new Mock<Transfer>(configInfo);
methodTester.CallBase = true;
methodTester
.Setup(m =>
m.GetFile(
It.IsAny<IFileConnection>(),
It.IsAny<string>(),
It.IsAny<string>()
))
.Throws<System.IO.IOException>();
methodTester.Object.TransferFiles("foo1", "foo2");
Assert.IsTrue(methodTester.Object.Status == TransferStatus.TransferInterrupted);
}
If there is a problem with this method, I would like to know; the other answers suggest I am doing this wrong, but this was exactly what I was trying to do.
The compilation problem only occurs for me (gcc 4.3, ubuntu 8.10) if the three variables are global. The problem is that C doesn't work like a script languages, so you cannot take for granted that the initialization of u and t occur after the one of s. That's why you get a compilation error. Now, you cannot initialize t and y they way you did it before, that's why you will need a char*. The code that do the work is the following:
#include <stdio.h>
#include <stdlib.h>
#define STR "ABCD"
const char s[] = STR;
char* t;
char* u;
void init(){
t = malloc(sizeof(STR)-1);
t[0] = s[0];
t[1] = s[1];
t[2] = s[2];
t[3] = s[3];
u = malloc(sizeof(STR)-1);
u[0] = s[3];
u[1] = s[2];
u[2] = s[1];
u[3] = s[0];
}
int main(void) {
init();
puts(t);
puts(u);
return EXIT_SUCCESS;
}
I was using HttpClient and getting back response header with content-type of application/json
, I lost characters such as foreign languages or symbol that used unicode since HttpClient is default to ISO-8859-1. So, be explicit as possible as mentioned by @WesternGun to avoid any possible problem.
There is no way handle that due to server doesn't handle requested-header charset (method.setRequestHeader("accept-charset", "UTF-8");
) for me and I had to retrieve response data as draw bytes and convert it into String using UTF-8. So, it is recommended to be explicit and avoid assumption of default value.
A void*
pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc
returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.
Because this is javascript and dynamic you could define your own class that matches the File interface and use that instead.
I had to do just that with dropzone.js because I wanted to simulate a file upload and it works on File objects.
As per the online docs, there is a 64K row limit and you can work out the row size by using:
row length = 1
+ (sum of column lengths)
+ (number of NULL columns + delete_flag + 7)/8
+ (number of variable-length columns)
You need to keep in mind that the column lengths aren't a one-to-one mapping of their size. For example, CHAR(10) CHARACTER SET utf8
requires three bytes for each of the ten characters since that particular encoding has to account for the three-bytes-per-character property of utf8
(that's MySQL's utf8
encoding rather than "real" UTF-8, which can have up to four bytes).
But, if your row size is approaching 64K, you may want to examine the schema of your database. It's a rare table that needs to be that wide in a properly set up (3NF) database - it's possible, just not very common.
If you want to use more than that, you can use the BLOB
or TEXT
types. These do not count against the 64K limit of the row (other than a small administrative footprint) but you need to be aware of other problems that come from their use, such as not being able to sort using the entire text block beyond a certain number of characters (though this can be configured upwards), forcing temporary tables to be on disk rather than in memory, or having to configure client and server comms buffers to handle the sizes efficiently.
The sizes allowed are:
TINYTEXT 255 (+1 byte overhead)
TEXT 64K - 1 (+2 bytes overhead)
MEDIUMTEXT 16M - 1 (+3 bytes overhead)
LONGTEXT 4G - 1 (+4 bytes overhead)
You still have the byte/character mismatch (so that a MEDIUMTEXT utf8
column can store "only" about half a million characters, (16M-1)/3 = 5,592,405
) but it still greatly expands your range.
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.
Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority
attribute in the intent-filter
tag:
<receiver android:name="com.company.application.SMSBroadcastReceiver" >
<intent-filter android:priority="500">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app
I was able to resolve the shared issue by following below steps:
We recently added a field to an admin site we are working on - contact_type... easy right? Well, if you call the select "type" and try to send that through a jquery ajax call it fails with this error buried deep in jquery.js Don't do this:
$.ajax({
dataType: "json",
type: "POST",
url: "/some_function.php",
data: { contact_uid:contact_uid, type:type }
});
The problem is that type:type - I believe it is us naming the argument "type" - having a value variable named type isn't the problem. We changed this to:
$.ajax({
dataType: "json",
type: "POST",
url: "/some_function.php",
data: { contact_uid:contact_uid, contact_type:type }
});
And rewrote some_function.php accordingly - problem solved.
It depends on the product. A product could be implemented that (under the covers) converts all UPDATEs into a (transactionally wrapped) DELETE and INSERT. Provided the results are consistent with the UPDATE semantics.
I'm not saying I'm aware of any product that does this, but it's perfectly legal.
You can try the expand
option in Series.str.split('seperator', expand=True)
.
By default expand
is False
.
expand
: bool, defaultFalse
Expand the splitted strings into separate columns.
- If
True
, return DataFrame/MultiIndex expanding dimensionality.- If
False
, return Series/Index, containing lists of strings.
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Newer versions of JQuery mobile API (I guess its newer than 1.5) require adding 'back' button explicitly in header or bottom of each page.
So, try adding this in your page div tags:
data-add-back-btn="true"
data-back-btn-text="Back"
Example:
<div data-role="page" id="page2" data-add-back-btn="true" data-back-btn-text="Back">
My simple solution. IMHO it's the cleanest.
First create a application.yml
spring.main.allow-bean-definition-overriding: true
security:
oauth2:
client:
clientId: XXX
clientSecret: XXX
accessTokenUri: XXX
tokenName: access_token
grant-type: client_credentials
Create the main class: Main
@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll();
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
return new OAuth2RestTemplate(details);
}
}
Then Create the controller class: Controller
@RestController
class OfferController {
@Autowired
private OAuth2RestOperations restOperations;
@RequestMapping(value = "/<your url>"
, method = RequestMethod.GET
, produces = "application/json")
public String foo() {
ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
return responseEntity.getBody();
}
}
Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
</dependencies>
location.search https://developer.mozilla.org/en/DOM/window.location
although most use some kind of parsing routine to read query string parameters.
here's one http://safalra.com/web-design/javascript/parsing-query-strings/
The other answers are excellent and I just want to provide a straight forward answer to this. Just limiting to jQuery asynchronous calls
All ajax calls (including the $.get
or $.post
or $.ajax
) are asynchronous.
Considering your example
var outerScopeVar; //line 1
$.post('loldog', function(response) { //line 2
outerScopeVar = response;
});
alert(outerScopeVar); //line 3
The code execution starts from line 1, declares the variable and triggers and asynchronous call on line 2, (i.e., the post request) and it continues its execution from line 3, without waiting for the post request to complete its execution.
Lets say that the post request takes 10 seconds to complete, the value of outerScopeVar
will only be set after those 10 seconds.
To try out,
var outerScopeVar; //line 1
$.post('loldog', function(response) { //line 2, takes 10 seconds to complete
outerScopeVar = response;
});
alert("Lets wait for some time here! Waiting is fun"); //line 3
alert(outerScopeVar); //line 4
Now when you execute this, you would get an alert on line 3. Now wait for some time until you are sure the post request has returned some value. Then when you click OK, on the alert box, next alert would print the expected value, because you waited for it.
In real life scenario, the code becomes,
var outerScopeVar;
$.post('loldog', function(response) {
outerScopeVar = response;
alert(outerScopeVar);
});
All the code that depends on the asynchronous calls, is moved inside the asynchronous block, or by waiting on the asynchronous calls.
I believe for this typical case, i.e. to run something with a fixed interval, Timer
is more appropriate. Here is a simple example:
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
// If you want to modify a view in your Activity
MyActivity.this.runOnUiThread(new Runnable()
public void run(){
tv.append("Hello World");
});
}
}, 1000, 1000); // initial delay 1 second, interval 1 second
Using Timer
has few advantages:
schedule
function argumentsmyTimer.cancel()
myTimer.cancel()
before scheduling a new one (if myTimer is not null)To check if element is visible we need to use element.isDisplayed();
But if we need to check for presence of element anywhere in Dom we can use following method
public boolean isElementPresentCheckUsingJavaScriptExecutor(WebElement element) {
JavascriptExecutor jse=(JavascriptExecutor) driver;
try {
Object obj = jse.execute("return typeof(arguments[0]) != 'undefined' && arguments[0] != null;",
element);
if (obj.toString().contains("true")) {
System.out.println("isElementPresentCheckUsingJavaScriptExecutor: SUCCESS");
return true;
} else {
System.out.println("isElementPresentCheckUsingJavaScriptExecutor: FAIL");
}
} catch (NoSuchElementException e) {
System.out.println("isElementPresentCheckUsingJavaScriptExecutor: FAIL");
}
return false;
}
If you use jQuery, you can do something like that :
$(document).ready(function(){$("input.autocompleteOff").attr("autocomplete","off");});
and use the autocompleteOff class where you want :
<input type="text" name="fieldName" id="fieldId" class="firstCSSClass otherCSSClass autocompleteOff" />
If you want ALL your input to be autocomplete=off
, you can simply use that :
$(document).ready(function(){$("input").attr("autocomplete","off");});
If you want to use android R
class
textView.setBackgroundColor(ContextCompat.getColor(getActivity(), android.R.color.transparent));
and don't forget to add support library to Gradle file
compile 'com.android.support:support-v4:23.3.0'
You can change the write permissions to get it done.
sudo chmod -R ug+w .
This command will give 'w'
permissions to all the folders in the current directory.
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
Another solution is you could use a background image to mimic the look of a left border
You might need to tweak for IE (as per usual) but it's worth a shot if that's the design you are going for.
Depending on what you mean by "use them as Strings", you might not want to use an enum here. In most cases, the solution proposed by The Elite Gentleman will allow you to use them through their toString-methods, e.g. in System.out.println(STRING_ONE)
or String s = "Hello "+STRING_TWO
, but when you really need Strings (e.g. STRING_ONE.toLowerCase()
), you might prefer defining them as constants:
public interface Strings{
public static final String STRING_ONE = "ONE";
public static final String STRING_TWO = "TWO";
}
If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting
[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread
Try to put ulimit -s unlimited
into /etc/init.d/httpd
. This does not require a server reboot.
Here is the PHP code to check if 'id' parameter exists in the URL or not:
if(isset($_GET['id']))
{
$slide = $_GET['id'] // Getting parameter value inside PHP variable
}
I hope it will help you.
With subprocess.run
:
import subprocess
import re
active_process_txt = subprocess.run(['celery', '-A', 'my_proj', 'inspect', 'active'],
stdout=subprocess.PIPE).stdout.decode('utf-8')
return len(re.findall(r'worker_pid', active_process_txt))
Be careful to change my_proj
with your_proj
man 1 nm
For example:
nm -gU /usr/local/Cellar/cairo/1.12.16/lib/cairo/libcairo-trace.0.dylib
This steps are all in the terminal:)->source
sudo /usr/local/mysql/support-files/mysql.server start
/usr/local/mysql/bin/mysql -v
cd ; nano .bash_profile
paste in and save:
export PATH="/usr/local/mysql/bin:$PATH"
"The first command brings you to your home directory and opens the .bash_profile file or creates a new one if it doesn’t exist, then add in the line above which adds the mysql binary path to commands that you can run. Exit the file with type “control + x” and when prompted save the change by typing “y”. Last thing to do here is to reload the shell for the above to work straight away."
source ~/.bash_profile mysql -v
"You will get the version number again, just type “q” to exit."
in your terminal type in: mysql
and then
SHOW GLOBAL VARIABLES LIKE 'PORT';
use everytime a semikolon in the mysql client (shell)!
now you know your port and where you can configure your server(in the terminal with mysql shell/client). but for a successful connection with MySQL Benchmark or an other client you have to know more. username, passwort hostname and port. after the installation the root user has no passwort so set(howtoSetPW) the passwort in terminal with mysql shell/client. and the server is running local. so type in root, yourPW, localhost and 3007. have fun!
This should work in C++11 without boost:
namespace std {
template<class T>
T begin(std::pair<T, T> p)
{
return p.first;
}
template<class T>
T end(std::pair<T, T> p)
{
return p.second;
}
}
template<class Iterator>
std::reverse_iterator<Iterator> make_reverse_iterator(Iterator it)
{
return std::reverse_iterator<Iterator>(it);
}
template<class Range>
std::pair<std::reverse_iterator<decltype(begin(std::declval<Range>()))>, std::reverse_iterator<decltype(begin(std::declval<Range>()))>> make_reverse_range(Range&& r)
{
return std::make_pair(make_reverse_iterator(begin(r)), make_reverse_iterator(end(r)));
}
for(auto x: make_reverse_range(r))
{
...
}
This script that will output the files with the directory structure under "fixedFiles". At the moment is fixed to MOV files and will execute a number of transformations depending on the original "rotation" of the video. Works with iOS captured videos on a Mac running Mavericks, but should be easily exportable. Relies on having installed both exiftool and ffmpeg.
#!/bin/bash
# rotation of 90 degrees. Will have to concatenate.
#ffmpeg -i <originalfile> -metadata:s:v:0 rotate=0 -vf "transpose=1" <destinationfile>
#/VLC -I dummy -vvv <originalfile> --sout='#transcode{width=1280,vcodec=mp4v,vb=16384,vfilter={canvas{width=1280,height=1280}:rotate{angle=-90}}}:std{access=file,mux=mp4,dst=<outputfile>}\' vlc://quit
#Allowing blanks in file names
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
#Bit Rate
BR=16384
#where to store fixed files
FIXED_FILES_DIR="fixedFiles"
#rm -rf $FIXED_FILES_DIR
mkdir $FIXED_FILES_DIR
# VLC
VLC_START="/Applications/VLC.app/Contents/MacOS/VLC -I dummy -vvv"
VLC_END="vlc://quit"
#############################################
# Processing of MOV in the wrong orientation
for f in `find . -regex '\./.*\.MOV'`
do
ROTATION=`exiftool "$f" |grep Rotation|cut -c 35-38`
SHORT_DIMENSION=`exiftool "$f" |grep "Image Size"|cut -c 39-43|sed 's/x//'`
BITRATE_INT=`exiftool "$f" |grep "Avg Bitrate"|cut -c 35-38|sed 's/\..*//'`
echo Short dimension [$SHORT_DIMENSION] $BITRATE_INT
if test "$ROTATION" != ""; then
DEST=$(dirname ${f})
echo "Processing $f with rotation $ROTATION in directory $DEST"
mkdir -p $FIXED_FILES_DIR/"$DEST"
if test "$ROTATION" == "0"; then
cp "$f" "$FIXED_FILES_DIR/$f"
elif test "$ROTATION" == "180"; then
# $(eval $VLC_START \"$f\" "--sout="\'"#transcode{vfilter={rotate{angle=-"$ROTATION"}},vcodec=mp4v,vb=$BR}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
$(eval ffmpeg -i \"$f\" -vf hflip,vflip -r 30 -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\")
elif test "$ROTATION" == "270"; then
$(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=2,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )
else
# $(eval $VLC_START \"$f\" "--sout="\'"#transcode{scale=1,width=$SHORT_DIMENSION,vcodec=mp4v,vb=$BR,vfilter={canvas{width=$SHORT_DIMENSION,height=$SHORT_DIMENSION}:rotate{angle=-"$ROTATION"}}}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
echo ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\"
$(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )
fi
fi
echo
echo ==================================================================
sleep 1
done
#############################################
# Processing of AVI files for my Panasonic TV
# Use ffmpegX + QuickBatch. Bitrate at 16384. Camera res 640x424
for f in `find . -regex '\./.*\.AVI'`
do
DEST=$(dirname ${f})
DEST_FILE=`echo "$f" | sed 's/.AVI/.MOV/'`
mkdir -p $FIXED_FILES_DIR/"$DEST"
echo "Processing $f in directory $DEST"
$(eval ffmpeg -i \"$f\" -r 20 -acodec libvo_aacenc -b:a 128k -vcodec mpeg4 -b:v 8M -flags +aic+mv4 \"$FIXED_FILES_DIR/$DEST_FILE\" )
echo
echo ==================================================================
done
IFS=$SAVEIFS
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
DON'T FORGET - Use parseFloat();
if your dealing with decimals.
To find a very long list of words in big files, it can be more efficient to use egrep:
remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B
Try the following:
CONVERT(varchar(10), [MyDateTimecolumn], 20)
For a full date time and not just date do:
CONVERT(varchar(23), [MyDateTimecolumn], 121)
See this page for convert styles:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
OR
SQL Server CONVERT() Function
Please, see oficial encode()
and decode()
documentation from codecs
library. utf-8
is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1
or utf_32
.
If you have different modules installed and need to use a specific python install, then shebang appears to be limited at first. However, you can do tricks like the below to allow the shebang to be invoked first as a shell script and then choose python. This is very flexible imo:
#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
echo Using preferred python $PREFERRED_PYTHON
exec $PREFERRED_PYTHON "$0" "$@"
elif [ -x $ALTERNATIVE_PYTHON ]; then
echo Using alternative python $ALTERNATIVE_PYTHON
exec $ALTERNATIVE_PYTHON "$0" "$@"
else
echo Using fallback python $FALLBACK_PYTHON
exec python3 "$0" "$@"
fi
exit 127
'''
__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())
Or better yet, perhaps, to facilitate code reuse across multiple python scripts:
#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[@]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$@"; exit 127; '''
and then select.sh has:
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
CHOSEN_PYTHON=$FALLBACK_PYTHON
fi
Another solution is using a "while" loop instead a "for" loop:
index=0
while [ ${index} -lt ${#Array[@]} ]
do
echo ${Array[${index}]}
index=$(( $index + 1 ))
done
I think, this could be done without IIS URL Rewrite module. <httpRedirect>
supports wildcards, so you can configure it this way:
<system.webServer>
<httpRedirect enabled="true">
<add wildcard="/" destination="/menu_1/MainScreen.aspx" />
</httpRedirect>
</system.webServer>
Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects
If you want to return a char*
from a function, make sure you malloc()
it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.
change it to
char* createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3 * sizeof(char));
if(str == NULL) return NULL;
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Java
class Hello{
public static void main(String [] args){
System.out.println("Hello Shahid");
}
}
manifest.mf
Manifest-version: 1.0
Main-Class: Hello
On command Line:
$ jar cfm HelloMss.jar manifest.mf Hello.class
$ java -jar HelloMss.jar
Output:
Hello Shahid
Just don't call finish()
on your MainActivity
then this eliminates the need to Override your onBackPressed()
in your SecondActivity
unless you are doing other things in that function. If you feel the "need" for this back button then you can simply call finish()
on the SecondActivity
and that will take you to your MainActivity
as long as you haven't called finish()
on it
//add this to your css
.myClass{
margin 0 auto;
}
// add the class to the span tag( could add it to the div and not using a span
// at all
<div class="row">
<div class="col-xs-1 center-block">
<span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => {
this.progressBar.Value = 50;
}));
Information for other users who want to know about performance:
If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.
if(Application.Current.Dispatcher.CheckAccess())
{
this.progressBar.Value = 50;
}
else
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => {
this.progressBar.Value = 50;
}));
}
Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
ConcurrentHashMap
You can use java.util.concurrent.ConcurrentHashMap
.
It implements ConcurrentMap
(which extends the Map
interface).
E.g.:
Map<Object, Content> map = new ConcurrentHashMap<Object, Content>();
for (Object key : map.keySet()) {
if (something) {
map.remove(key);
}
}
This approach leaves your code untouched. Only the map
type differs.
Well to solve the problems of master password - the best approach is not to store the password anywhere, the application should encrypt passwords for itself - so that only it can decrypt them. So if I was using a .config file I would do the following, mySettings.config:
encryptTheseKeys=secretKey,anotherSecret
secretKey=unprotectedPasswordThatIputHere
anotherSecret=anotherPass
someKey=unprotectedSettingIdontCareAbout
so I would read in the keys that are mentioned in the encryptTheseKeys, apply the Brodwalls example from above on them and write them back to the file with a marker of some sort (lets say crypt:) to let the application know not to do it again, the output would look like this:
encryptTheseKeys=secretKey,anotherSecret
secretKey=crypt:ii4jfj304fjhfj934fouh938
anotherSecret=crypt:jd48jofh48h
someKey=unprotectedSettingIdontCareAbout
Just make sure to keep the originals in your own secure place...
I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.
window.addEventListener('scroll', function (evt) {
// This value is your scroll distance from the top
var distance_from_top = document.body.scrollTop;
// The user has scrolled to the tippy top of the page. Set appropriate style.
if (distance_from_top === 0) {
}
// The user has scrolled down the page.
if(distance_from_top > 0) {
}
});
This is what iDevelop is trying to say Enabled Property
So you have been infact using enabled
, coz your initial post was enable
..
You may try the following:
Sub disenable()
sheets(1).button1.enabled=false
DoEvents
Application.ScreenUpdating = True
For i = 1 To 10
Application.Wait (Now + TimeValue("0:00:1"))
Next i
sheets(1).button1.enabled = False
End Sub
Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const
correctness in a compact way.
Something like this:
const int n = (x != 0) ? 10 : 20;
so basically n
is a const
whose initial value is dependent on a condition statement. The easiest alternative is to make n
not a const
, this would allow an ordinary if
to initialize it. But if you want it to be const
, it cannot be done with an ordinary if
. The best substitute you could make would be to use a helper function like this:
int f(int x) {
if(x != 0) { return 10; } else { return 20; }
}
const int n = f(x);
but the ternary if version is far more compact and arguably more readable.
I added binary before the column name and solve the charset error.
insert into tableA values(binary stringcolname1);
This is a pretty old question but I used
My method has this parameter but it could be built:
Expression<Func<TModel, TValue>> expression
Then in the method this:
System.Linq.Expressions.MemberExpression memberExpression
= expression.Body as System.Linq.Expressions.MemberExpression;
Boolean hasIdentityAttr = System.Attribute
.IsDefined(memberExpression.Member, typeof(IsIdentity));
There some issues with pow method:
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
To update this ancient question for .NET 4, there is now a much neater way:
var lines = File.ReadAllLines(filename);
foreach (string line in lines)
{
Console.WriteLine(line);
}
I ran into this challenge when building an app where I wanted a table hidden for certain users but not for others.
Initially I set it up as display:none but then display:inline-block for those users who I wanted to see it but I experienced the formatting issues you might expect (columns consolidating or generally messy).
The way I worked around it was to show the table first and then do "display:none" for those users who I didn't want to see it. This way, it formatted normally but then disappeared as needed.
Bit of a lateral solution but might help someone!
Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...
The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...
Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)
Why not just use a CDN? Unless you need to edit the code of BS, then you just need to reference the codes in CDN.
See BS 4 CDN Here:
https://www.w3schools.com/bootstrap4/bootstrap_get_started.asp
At the bottom of the page.
Use asymptote instead!
This is what it can look like:
https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.html
This is the code: https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.asy
Asymptote can also read in data files.
And the full gallery: https://asymptote.sourceforge.io/gallery/index.html
To use asymptote from within Python:
https://ctan.org/tex-archive/graphics/asymptote/base/asymptote.py
This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.
Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.
Pre-requisites : An elementary knowledge of C++ Standard
The Standard says
At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)
Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).
For example:
int x = y++; //where y is also an int
In addition to the initialization operation the value of y
gets changed due to the side effect of ++
operator.
So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit
:
Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.
Those are:
at the end of the evaluation of full expression (§1.9/16
) (A full-expression is an expression that is not a subexpression of another expression.)1
Example :
int a = 5; // ; is a sequence point here
in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18
) 2
a && b (§5.14)
a || b (§5.15)
a ? b : c (§5.16)
a , b (§5.18)
(here a , b is a comma operator; in func(a,a++)
,
is not a comma operator, it's merely a separator between the arguments a
and a++
. Thus the behaviour is undefined in that case (if a
is considered to be a primitive type)) at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which
takes place before execution of any expressions or statements in the function body (§1.9/17
).
1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument
2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.
The Standard defines Undefined Behaviour in Section §1.3.12
as
behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.
Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.
3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.
Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.
You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified
.
For example:
int x = 5, y = 6;
int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.
Another example here.
Now the Standard in §5/4
says
What does it mean?
Informally it means that between two sequence points a variable must not be modified more than once.
In an expression statement, the next sequence point
is usually at the terminating semicolon, and the previous sequence point
is at the end of the previous statement. An expression may also contain intermediate sequence points
.
From the above sentence the following expressions invoke Undefined Behaviour:
i++ * ++i; // UB, i is modified more than once btw two SPs
i = ++i; // UB, same as above
++i = 2; // UB, same as above
i = ++i + 1; // UB, same as above
++++++i; // UB, parsed as (++(++(++i)))
i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)
But the following expressions are fine:
i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i); // well defined
int j = i;
j = (++i, i++, j*i); // well defined
What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.
For example in i = i + 1
all the access of i
(in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.
This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.
Example 1:
std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2
Example 2:
a[i] = i++ // or a[++i] = i or a[i++] = ++i etc
is disallowed because one of the accesses of i
(the one in a[i]
) has nothing to do with the value which ends up being stored in i (which happens over in i++
), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.
Example 3 :
int x = i + i++ ;// Similar to above
Follow up answer for C++11 here.
You can achieve it as below:
function Foo() {};
Foo.talk = function() { alert('I am talking.'); };
You can now invoke "talk" function as below:
Foo.talk();
You can do this because in JavaScript, functions are objects as well.
Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.
Since interning is automatic for String literals, the intern()
method is to be used on Strings constructed with new String()
Using your example:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh");
String s5 = new String("Rakesh").intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
if ( s1 == s4 ){
System.out.println("s1 and s4 are same" ); // 3.
}
if ( s1 == s5 ){
System.out.println("s1 and s5 are same" ); // 4.
}
will return:
s1 and s2 are same
s1 and s3 are same
s1 and s5 are same
In all the cases besides of s4
variable, a value for which was explicitly created using new
operator and where intern
method was not used on it's result, it is a single immutable instance that's being returned JVM's string constant pool.
Refer to JavaTechniques "String Equality and Interning" for more information.
Just do the same thing agin but then for TableC
SELECT *
FROM dbo.tableA A
INNER JOIN dbo.TableB B ON A.common = B.common
INNER JOIN dbo.TableC C ON A.common = C.common
Instead of saying:
if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then
say:
if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then
You might also want to refer to Conditional Constructs.
Your xpath is just a little off:
count(//Property/long[text()=$parPropId])
Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId]
than the text() xpath, though you could make a case for the latter on readability grounds.
What can I say, I'm a bit tired today :)
I had to post key value pairs without form and I could do it easily like below:
var request = require('request');
request({
url: 'http://localhost/test2.php',
method: 'POST',
json: {mes: 'heydude'}
}, function(error, response, body){
console.log(body);
});
Here is the simple solution by StreamEx:
StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());
This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.
This is a little faster (and looks nicer)
np.argmax(aa>5)
Since argmax
will stop at the first True
("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save another list.
In [2]: N = 10000
In [3]: aa = np.arange(-N,N)
In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop
In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop
In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
Define in wp_config file.
/var/www/html/Your-Project-File/wp-config.php
define( 'FS_METHOD', 'direct' );
chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions.
sudo chown -R www-data:www-data /var/www
I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
List<IDataRecord> list = data.Cast<IDataRecord>().ToList();
PropertyDescriptorCollection props = null;
DataTable table = new DataTable();
if (list != null && list.Count > 0)
{
props = TypeDescriptor.GetProperties(list[0]);
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
if (props != null)
{
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(values);
}
}
return table;
}
Swift 2.0
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){
if let error = error{
print("Error: \(error)")
}else{
//NO Error
//------------------------------------------------
var feedbackMsg = ""
switch result.rawValue {
case MFMailComposeResultCancelled.rawValue:
feedbackMsg = "Mail Cancelled"
case MFMailComposeResultSaved.rawValue:
feedbackMsg = "Mail Saved"
case MFMailComposeResultSent.rawValue:
feedbackMsg = "Mail Sent"
case MFMailComposeResultFailed.rawValue:
feedbackMsg = "Mail Failed"
default:
feedbackMsg = ""
}
print("Mail: \(feedbackMsg)")
//------------------------------------------------
}
}
I personally prefer VisualVM. One of the features I like in VisualVM is heap dump comparison. When you are doing a heap dump analysis there are various ways to go about figuring out what caused the crash. One of the ways I have found useful is doing a comparison of healthy vs unhealthy heap dumps.
Following are the steps you can follow for it :
link : https://visualvm.github.io
What I am wondering is if there is any strange way to make this check even faster, maybe exploiting some strange method in Regexp or some weird construct.
Regexp engines vary in how they implement searches, but, in general, anchor your patterns for speed, and avoid greedy matches, especially when searching long strings.
The best thing to do, until you're familiar with how a particular engine works, is to do benchmarks and add/remove anchors, try limiting searches, use wildcards vs. explicit matches, etc.
The Fruity gem is very useful for quickly benchmarking things, because it's smart. Ruby's built-in Benchmark code is also useful, though you can write tests that fool you by not being careful.
I've used both in many answers here on Stack Overflow, so you can search through my answers and will see lots of little tricks and results to give you ideas of how to write faster code.
The biggest thing to remember is, it's bad to prematurely optimize your code before you know where the slowdowns occur.
The good option is to use AdminClient as below before starting to produce or consume the messages
private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;
try (AdminClient client = AdminClient.create(properties)) {
client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
} catch (ExecutionException ex) {
LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
return;
}
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
Here's another way that I didn't see here:
>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}
You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!
>>> foo = dict(a=1,b=2,c=3,d=4)
>>> new_dict = {k: v for k, v in list(foo.items())[:2]}
>>> new_dict
{'a': 1, 'b': 2}
>>> new_dict.update(newvalue=99)
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99}
>>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
>>>
The above is using dictionary comprehension.
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.
First prepare your password salts file:
hash_generate.php:
<?php
$user = "Username"; // please replace with your user
$pass = "Password"; // please replace with your passwd
// two ; was missing
$useroptions = ['cost' => 8,];
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions);
$pwoptions = ['cost' => 8,];
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);
echo $userhash;
echo "<br />";
echo $passhash;
?>
Take your output $userhash
and $passhash
and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"
.htaccess
deny from all
Now no one can peek into the hash. Next up is your index.php:
index.php:
<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
$user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
$pass = $_POST['pass'];
}
$useroptions = ['cost' => 8,]; // all up to you
$pwoptions = ['cost' => 8,]; // all up to you
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions); // hash entered pw
$hasheduser = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass = file_get_contents("stuff/pass.txt"); // and our stored password
if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {
// the password verify is how we actually login here
// the $userhash and $passhash are the hashed user-entered credentials
// password verify now compares our stored user and pw with entered user and pw
include "pass-protected.php";
} else {
// if it was invalid it'll just display the form, if there was never a $_POST
// then it'll also display the form. that's why I set $user to "" instead of a $_POST
// this is the right place for comments, not inside html
?>
<form method="POST" action="index.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php
}
If you can't use "viewWillDisappear" or similar method, try to subclass UINavigationController. This is the header class:
#import <Foundation/Foundation.h>
@class MyViewController;
@interface CCNavigationController : UINavigationController
@property (nonatomic, strong) MyViewController *viewController;
@end
Implementation class:
#import "CCNavigationController.h"
#import "MyViewController.h"
@implementation CCNavigationController {
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
@"This is the moment for you to do whatever you want"
[self.viewController doCustomMethod];
return [super popViewControllerAnimated:animated];
}
@end
In the other hand, you need to link this viewController to your custom NavigationController, so, in your viewDidLoad method for your regular viewController do this:
@implementation MyViewController {
- (void)viewDidLoad
{
[super viewDidLoad];
((CCNavigationController*)self.navigationController).viewController = self;
}
}
tableColumns
null
for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... }
for specific columns as in SELECT column1, column2 FROM ...
- you can also put complex expressions here:new String[] { "(SELECT max(column1) FROM table1) AS max" }
would give you a column named max
holding the max value of column1
whereClause
WHERE
without that keyword, e.g. "column1 > 5"
?
for things that are dynamic, e.g. "column1=?"
-> see whereArgs
whereArgs
?
in whereClause
in the order they appearthe others
whereClause
the statement after the keyword or null
if you don't use it.Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '
.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a '
your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--"
might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;--
would be escaped to 'XYZ''; DROP TABLE table1;--'
and would only be treated as a value. Even if the '
is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int
and other primitives directly into whereClause
though)
Perhaps this is pythonic and slightly useful if you have an unknown number of lists, and without importing anything.
As long as the lists are of the same length, you can use the below function.
Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).
The * is used again in the returned list to unpack the elements in each of the lists.
def sum_lists(*args):
return list(map(sum, zip(*args)))
a = [1,2,3]
b = [1,2,3]
sum_lists(a,b)
Output:
[2, 4, 6]
Or with 3 lists
sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])
Output:
[19, 19, 19, 19, 19]
Below I split all the details of formatted address like City, State, Country and Zip code.
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically.
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
var places = new google.maps.places.Autocomplete(document
.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function() {
var place = places.getPlace();
var address = place.formatted_address;
var value = address.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
var z=state.split(" ");
document.getElementById("selCountry").text = country;
var i =z.length;
document.getElementById("pstate").value = z[1];
if(i>2)
document.getElementById("pzcode").value = z[2];
document.getElementById("pCity").value = city;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
var mesg = address;
document.getElementById("txtPlaces").value = mesg;
var lati = latitude;
document.getElementById("plati").value = lati;
var longi = longitude;
document.getElementById("plongi").value = longi;
});
});
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
Here is a simple .split
solution that works without regex.
This is an answer for Python split() without removing the delimiter, so not exactly what the original post asks but the other question was closed as a duplicate for this one.
def splitkeep(s, delimiter):
split = s.split(delimiter)
return [substr + delimiter for substr in split[:-1]] + [split[-1]]
Random tests:
import random
CHARS = [".", "a", "b", "c"]
assert splitkeep("", "X") == [""] # 0 length test
for delimiter in ('.', '..'):
for _ in range(100000):
length = random.randint(1, 50)
s = "".join(random.choice(CHARS) for _ in range(length))
assert "".join(splitkeep(s, delimiter)) == s
Here is how I solve this issue. I was using Babun(mintty.exe) on Win7/10. When I have tried many solutions mentioned above, and none of them works. I realized maybe I just used wrong ssh agent...
So I run echo $GIT_SSH
to find out, it shows the path to Plink.exe
.
What I actually expected is OpenSSH.
So, I add following one-liner to ~/.zshrc
file
Note 1: You can execute it in babun directly also
Note 2: You if you use bash then the config file is.bashrc
export GIT_SSH=$(which ssh)
And It works!
I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:
CREATE FUNCTION nomen_tree() RETURNS trigger
LANGUAGE plpgsql
AS $_$
DECLARE
old_parent INTEGER;
new_parent INTEGER;
id_nom INTEGER;
txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
IF TG_OP = 'INSERT' THEN
EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT $1.id,$1.id,0 UNION ALL
SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
ELSE
-- EXECUTE does not support conditional statements inside
EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
EXECUTE '
-- prevent cycles in the tree
UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
|| ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
|| TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
-- first remove edges between all old parents of node and its descendants
DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
(SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
AND ancestor_id IN
(SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
-- then add edges for all new parents ...
INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT child_id,ancestor_id,d_c+d_a FROM
(SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
CROSS JOIN
(SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.'
|| TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
END IF;
END IF;
RETURN NULL;
END;
$_$;
Then for each table where I have a hierarchy, I create a trigger
CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');
For populating a closure table from existing hierarchy I use this stored procedure:
CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE 'TRUNCATE ' || tbl_closure || ';
INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth)
WITH RECURSIVE tree AS
(
SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
UNION ALL
SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
JOIN tree ON child_id = ' || fld_parent || '
)
SELECT * FROM tree;';
END;
$$;
Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:
-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;
For Mars (Eclipse 4.5) and WTP 3.7 use this link. http://download.eclipse.org/webtools/repository/mars/
$(document).ready(function () {
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
});
You can try this:
func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
return true
}
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
NamesTable.beginUpdates()
Names.removeAtIndex(indexPath!.row)
NamesTable.deleteRowsAtIndexPaths([indexPath], withRowAnimation: nil)
NamesTable.endUpdates()
}
}
This code is work for me
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// add your action here that you want
return true;
}
else if (id==R.id.login)
{
// add your action here that you want
}
return super.onOptionsItemSelected(item);
}
No, that would be a huge security breach. Imagine if someone could run
format c:
whenever you visted their website.
how do you get
"\u6f22\u5b57"
from??
in JavaScript?
These are JavaScript Unicode escape sequences e.g. \u12AB
. To convert them, you could iterate over every code unit in the string, call .toString(16)
on it, and go from there.
However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA
in the output wherever possible.
Also note that ASCII symbols such as A
, b
, and -
probably don’t need to be escaped.
I’ve written a small JavaScript library that does all this for you, called jsesc
. It has lots of options to control the output.
Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97
Your question was tagged as utf-8
. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js
(online demo).
Do this:
function changeHeight() { document.getElementById('chartdiv').style.height = "200px" } <button type="button" onClick="changeHeight();"> Click Me!</button>
new {var_data[counter] =new [] {
new{ "S NO": "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
}
};
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
This should work properly this is just an improvement of previous answers.
DECLARE @Counter INT
DECLARE @Counter1 INT
SET @Counter = 0
SET @Counter1 = 0
DECLARE @TotalPrints INT
SET @TotalPrints = (LEN(@QUERY) / 4000) + 1
print @TotalPrints
WHILE @Counter < @TotalPrints
BEGIN
-- Do your printing...
print(substring(@query,@COUNTER1,@COUNTER1+4000))
set @COUNTER1 = @Counter1+4000
SET @Counter = @Counter + 1
END
You have to add the targeted map :
var markers = [
{
"title": 'This is title',
"lat": '-37.801578',
"lng": '145.060508',
"map": map,
"icon": 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png',
"description": 'Vikash Rathee. <strong> This is test Description</strong> <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by
City</a>'
}
];
In your ASPX page you've got the list like this:
<asp:CheckBoxList ID="YrChkBox" runat="server"
onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
<asp:Button ID="button" runat="server" Text="Submit" />
In your code behind aspx.cs page, you have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Populate the CheckBoxList items only when it's not a postback.
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
}
}
protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Create the list to store.
List<String> YrStrList = new List<string>();
// Loop through each item.
foreach (ListItem item in YrChkBox.Items)
{
if (item.Selected)
{
// If the item is selected, add the value to the list.
YrStrList.Add(item.Value);
}
else
{
// Item is not selected, do something else.
}
}
// Join the string together using the ; delimiter.
String YrStr = String.Join(";", YrStrList.ToArray());
// Write to the page the value.
Response.Write(String.Concat("Selected Items: ", YrStr));
}
Ensure you use the if (!IsPostBack) { }
condition because if you load it every page refresh, it's actually destroying the data.
Agreed with jcadcell comments, but had to use JDK 1.8 because my eclipse need that. So I just copied the MSVCR71.DLL from jdk1.6 and pasted into jdk1.8 in both the folder jdk1.8.0_121\bin and jdk1.8.0_121\jre\bin
and it Worked .... Wow... Thanks :)
EASY solution for Mac Excel 2008: I struggled with this soo many times, but here was my easy fix: Open the .csv file in Textwrangler which should open your UTF-8 chars correctly. Now in the bottom status bar change the file format from "Unicode (UTF-8)" to "Western (ISO Latin 1)" and save the file. Now go to your Mac Excel 2008 and select File > Import > Select csv > Find your file > in File origin select "Windows (ANSI)" and voila the UTF-8 chars are showing correctly. At least it does for me...
I was trying to fetch table meta data, but had the following error:
Using:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
DatabaseMetaData metaData = connection.getMetaData();
...
metaData.getColumns(...);
returned an empty ResultSet.
But using the following URL instead it worked properly:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";
There was a need to specify: DATABASE_TO_UPPER=false
According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:
git checkout -- a
(where a
is the directory you want to hard-reset). The original behavior can be accessed via
git checkout --ignore-skip-worktree-bits -- a
If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.
My compact version:
<script type="text/javascript">
$(window).load(function () {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
});
</script>
However, sometimes the iframe
is not ready on window loaded, so there is a need of using a timer.
Ready-to-use code (with timer):
<script type="text/javascript">
var frameListener;
$(window).load(function () {
frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
clearInterval(frameListener); // stop the listener
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
}
</script>
...and jQuery link:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
Actually, Docker images are stored in two files as shown by following command
$ docker info
Data file:
/var/lib/docker/devicemapper/devicemapper/data
Metadata file:
/var/lib/docker/devicemapper/devicemapper/metadata
In any case you can know it:
mysql> select @@datadir;
+----------------------------------------------------------------+
| @@datadir |
+----------------------------------------------------------------+
| D:\Documents and Settings\b394382\My Documents\MySQL_5_1\data\ |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
Thanks Barry Galbraith from the MySql Forum http://forums.mysql.com/read.php?10,379153,379167#msg-379167
I'm the OP. After some research and testing, the answer is:
No, there is no way to do exactly that.
You can create your own filter function using query
in pandas
. Here you have filtering of df
results by all the kwargs
parameters. Dont' forgot to add some validators(kwargs
filtering) to get filter function for your own df
.
def filter(df, **kwargs):
query_list = []
for key in kwargs.keys():
query_list.append(f'{key}=="{kwargs[key]}"')
query = ' & '.join(query_list)
return df.query(query)
Rather than finding top view controller, one can use
viewController.modalPresentationStyle = UIModalPresentationStyle.currentContext
Where viewController is the controller which you want to present This is useful when there are different kinds of views in hierarchy like TabBar, NavBar, though others seems to be correct but more sort of hackish
The other presentation style can be found on apple doc
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
You need to perform the action from the thread that owns the control.
That's how I'm doing that without adding too much code noise:
control.Invoke(() => textBox1.Text += "hi");
Where Invoke overload is a simple extension from Lokad Shared Libraries:
/// <summary>
/// Invokes the specified <paramref name="action"/> on the thread that owns
/// the <paramref name="control"/>.</summary>
/// <typeparam name="TControl">type of the control to work with</typeparam>
/// <param name="control">The control to execute action against.</param>
/// <param name="action">The action to on the thread of the control.</param>
public static void Invoke<TControl>(this TControl control, Action action)
where TControl : Control
{
if (!control.InvokeRequired)
{
action();
}
else
{
control.Invoke(action);
}
}
Add DOCTYPE tag ...
In this case:
<!DOCTYPE xml>
Add after:
<?xml version="1.0" encoding="UTF-8"?>
So:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
In Kotlin:
private val id = 1
private val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION)
fun hasPermissions(): Boolean {
for (perm in permissions) {
if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
return false
}
}
return true
}
if(! hasPermissions()){
requestPermissions(this, permissions, id)
}
In your web.config, make sure these keys exist:
<configuration>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
public class SubstringExample
{
public static void main(String[] args)
{
String str="OOPs is a programming paradigm...";
System.out.println(" Length is: " + str.length());
System.out.println(" Substring is: " + str.substring(10, 30));
}
}
Output:
length is: 31
Substring is: programming paradigm
Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.
myQueue.hpp:
template <class T>
class QueueA {
int size;
...
public:
template <class T> T dequeue() {
// implementation here
}
bool isEmpty();
...
}
myQueue.cpp:
// implementation of regular methods goes like this:
template <class T> bool QueueA<T>::isEmpty() {
return this->size == 0;
}
main()
{
QueueA<char> Q;
...
}
I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.
You need at least 1 level of inheritance and an upcast to demonstrate it. Here is a very simple example:
class Animal
{
public:
// turn the following virtual modifier on/off to see what happens
//virtual
std::string Says() { return "?"; }
};
class Dog: public Animal
{
public: std::string Says() { return "Woof"; }
};
void test()
{
Dog* d = new Dog();
Animal* a = d; // refer to Dog instance with Animal pointer
std::cout << d->Says(); // always Woof
std::cout << a->Says(); // Woof or ?, depends on virtual
}
I was able to invoke a shell script using this command:
ssh ${serverhost} "./sh/checkScript.ksh"
Of course, checkScript.ksh
must exist in the $HOME/sh
directory.
You can also make an exception for leaving the page via submitting a particular form:
$(window).bind('beforeunload', function(){
return "Do you really want to leave now?";
});
$("#form_id").submit(function(){
$(window).unbind("beforeunload");
});
If you have reached here that means all the other solutions did not work for you. One reason could be your source folder is not a java project.
Solution would be to run below command on the source folder
mvn eclipse:eclipse
This worked for me.
If this also doesn't work then try removing .classpath and .project file and run the above command again
The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:
JAVA_HOME=/usr/java/jdk1.7.0_79
In my case, originally the following error was occurring:
Cannot read configuration file due to insufficient permissions
I fixed the error by using the proposed solution and restarted the application through IIS Manager
. The original error was gone but the application was taking forever to load. I gave the permissions to IIS_IUSRS
again but this time to the whole deployment folder. After this, the application was able to load though an error was showing up:
This configuration section cannot be used at this path
After resolving the above-mentioned error using the solution, the application was finally loading without giving any error.
Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.
The service:
MyApp.service('getData',
[
'$http',
function($http) {
this.getQuote = function(ticker) {
var _url = 'https://www.google.com/finance/info?q=' + ticker;
return $http.get(_url); //Simply return the promise to the caller
};
}
]
);
The controller:
MyApp.controller('StockREST',
[
'$scope',
'getData', //<-- the service above
function($scope, getData) {
var getQuote = function(symbol) {
getData.getQuote(symbol)
.success(function(response, status, headers, config) {
var _data = response.substring(4, response.length);
var _json = JSON.parse(_data);
$scope.stockQuoteData = _json[0];
// ticker: $scope.stockQuoteData.t
// last price: $scope.stockQuoteData.l
// last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
// last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
})
.error(function(response, status, headers, config) {
console.log('@@@ Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
});
};
getQuote($scope.ticker.tick.name); //Initialize
$scope.getQuote = getQuote; //as defined above
}
]
);
The HTML:
<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>
At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.
Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.
I've done this plenty of times in VS 2005 without any problems.
I don' want to resurrect an old thread, but... anyone who wants to use a modern up to date secure solution, use argon2.
https://pypi.python.org/pypi/argon2_cffi
It won the the password hashing competition. ( https://password-hashing.net/ ) It is easier to use than bcrypt, and it is more secure than bcrypt.
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
You can retrieve the length of the file with File#length(), which will return a value in bytes, so you need to divide this by 1024*1024 to get its value in mb.
Try this:
ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
NR is an AWK builtin variable to count the no. of records
As I understand Copy-Item -Exclude
then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item
as in
Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item -Path $copyAdmin -Destination $AdminPath -Recurse -force
Adding to what @KyleMit said, consider using:
col-md-*
classes for the larger outer columnscol-xs-*
classes for the smaller inner columnsThis will be useful when you view the page on different screen sizes.
On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible
The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:
/* this
is a
multi-line comment */
// this is a single line comment
Just use 'elevation' property to get shadow in android. something like below
const Header = () => {
// const { textStyle, viewStyle } = styles;
return (
<View style={styles.viewStyle}>
<Text style={styles.textStyle}>Albums</Text>
</View>
)
}
const styles = {
viewStyle:{
backgroundColor:'#f8f8f8',
justifyContext:'center',
alignItems: 'center',
padding:16,
elevation: 2
}
}
This works well for me. It uses an array so you aren't looping through each cell. Runs much faster over large worksheet sections.
Sub Trim_Cells_Array_Method()
Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long
lRows = Selection.Rows.count
lCols = Selection.Columns.count
ReDim arrData(1 To lRows, 1 To lCols)
ReDim arrReturnData(1 To lRows, 1 To lCols)
Set rng = Selection
arrData = rng.value
For j = 1 To lCols
For i = 1 To lRows
arrReturnData(i, j) = Trim(arrData(i, j))
Next i
Next j
rng.value = arrReturnData
Set rng = Nothing
End Sub
In addition to specify a fixed amount of characters, you can also use *
which means that printf takes the number of characters from an argument:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char hello[] = "Hello world";
printf("message: '%.3s'\n", hello);
printf("message: '%.*s'\n", 3, hello);
printf("message: '%.*s'\n", 5, hello);
return 0;
}
Prints:
message: 'Hel'
message: 'Hel'
message: 'Hello'
If you already define your view in your layout(xml) file, only want to change the weight programmatically, this way is better
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);
new a LayoutParams overwrites other params defined in you xml file like margins, or you need to specify all of them in LayoutParams.
The
<%@include file="abc.jsp"%>
directive acts like C"#include"
, pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text).The <jsp:include page="abc.jsp"> tag compiles the file as a separate JSP file, and embeds a call to it in the compiled JSP.
Some JSP engines support the non-standard tags
<!--#include file="data.inc"-->
(NCSA-, or .shtml-style) and<%@ vinclude="data.inc" %>
(JRun-style), but these are not defined in the JSP spec and thus cannot be relied on.See also this question in the JSP FAQ.
First, as for your Athlete class, you can remove your Getter and Setter
methods since you have declared your instance variables with an access modifier of public
. You can access the variables via <ClassName>.<variableName>
.
However, if you really want to use that Getter and Setter
, change the public
modifier to private
instead.
Second, for the constructor, you're trying to do a simple technique called shadowing
. Shadowing
is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing
:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person
class as follow:
Person person = new Person("theolc");
Variable name
will be equal to "theolc"
.
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter
. Remove your parameters on your constructor
.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
Missing from these answers is how to get a file dialog without a input element on the page.
The function to show the input file dialog.
function openFileDialog (accept, callback) { // this function must be called from a user
// activation event (ie an onclick event)
// Create an input element
var inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = accept;
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", callback)
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
}
NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.
NOTE
input.accept
is not used in Edge
Calling above function when user clicks an anchor element.
// wait for window to load
window.addEventListener("load", windowLoad);
// open a dialog function
function openFileDialog (accept, multy = false, callback) {
var inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.accept = accept; // Note Edge does not support this attribute
if (multy) {
inputElement.multiple = multy;
}
if (typeof callback === "function") {
inputElement.addEventListener("change", callback);
}
inputElement.dispatchEvent(new MouseEvent("click"));
}
// onload event
function windowLoad () {
// add user click event to userbutton
userButton.addEventListener("click", openDialogClick);
}
// userButton click event
function openDialogClick () {
// open file dialog for text files
openFileDialog(".txt,text/plain", true, fileDialogChanged);
}
// file dialog onchange event handler
function fileDialogChanged (event) {
[...this.files].forEach(file => {
var div = document.createElement("div");
div.className = "fileList common";
div.textContent = file.name;
userSelectedFiles.appendChild(div);
});
}
_x000D_
.common {
font-family: sans-serif;
padding: 2px;
margin : 2px;
border-radius: 4px;
}
.fileList {
background: #229;
color: white;
}
#userButton {
background: #999;
color: #000;
width: 8em;
text-align: center;
cursor: pointer;
}
#userButton:hover {
background : #4A4;
color : white;
}
_x000D_
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>
_x000D_
Warning the above snippet is written in ES6.
When using SQL Express, you need to specify \SQLExpress instance in your connection string:
string str = "Data Source=HARIHARAN-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" ;
in visual 2019, Open Options to show all enter image description here
and multi select: keep Ctrl + Alt
then click position you want
or, keep Shift + Alt
then click position to multi select multi line from start to end line clicked
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
Solve this Issue Using this in build.gradle (app) File Inside main Android { inside }
buildTypes {
// crunchPngs false // or true when png error
release {
lintOptions {
checkReleaseBuilds false
abortOnError false
}
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}