Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.
int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}
}
If array item and list item are same
List<object> list=myArray.ToList();
If you don't want to mess with arrays' sizes, just use the magic of string concatenation:
byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");
Or define somewhere in your code
// concatenation charset
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;
and use
byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);
This, of course, also works with more than two string concatenations using the +
addition operator.
Both "l1"
and ISO_8859_1
indicate the Western Latin 1 character set that encodes each character as a single byte. As no multi-byte translations are performed the characters in the string will have the same values as the bytes (except that they will always be interpreted as positive values, as char
is unsigned). At least for the Oracle provided runtime, any byte will therefore be correctly "decoded" and then "encoded" again.
Beware that strings do expand the byte array considerately, requiring additional memory. Strings may also be interned and will therefore not easy be removed. Strings are also immutable, so the values inside them cannot be destroyed. You should therefore not concatenate sensitive arrays this way nor should you use this method for larger byte arrays. Giving a clear indication of what you are doing would also be required, as this method of array concatenation is not a common solution.
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)
np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.
You could also use matrix multiplication (aka dot product):
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)
numpy.dot(c,a)
Which is more elegant is probably a matter of taste.
Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :
$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
$query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;
Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7
Remember:
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%".
(Thanks to metamorphosis for the full quote)
Don't use a C array instead of a vector (or whatever) just because you believe it's faster as it is supposed to be lower-level. You would be wrong.
Use by default vector (or the safe container adapted to your need), and then if your profiler says it is a problem, see if you can optimize it, either by using a better algorithm, or changing container.
This said, we can go back to the original question.
The C++ array classes are better behaved than the low-level C array because they know a lot about themselves, and can answer questions C arrays can't. They are able to clean after themselves. And more importantly, they are usually written using templates and/or inlining, which means that what appears to a lot of code in debug resolves to little or no code produced in release build, meaning no difference with their built-in less safe competition.
All in all, it falls on two categories:
Using a pointer to a malloc-ed/new-ed array will be at best as fast as the std::vector version, and a lot less safe (see litb's post).
So use a std::vector.
Using a static array will be at best:
So use a std::array.
Sometimes, using a vector
instead of a raw buffer incurs a visible cost because the vector
will initialize the buffer at construction, while the code it replaces didn't, as remarked bernie by in his answer.
If this is the case, then you can handle it by using a unique_ptr
instead of a vector
or, if the case is not exceptional in your codeline, actually write a class buffer_owner
that will own that memory, and give you easy and safe access to it, including bonuses like resizing it (using realloc
?), or whatever you need.
Study up on multidimensional arrays. This question might help.
a = np.empty(0)
for x in y:
a = np.append(a, x)
const changedArray = array.filter( function(value) {
return value !== 'B'
});
or you can use :
const changedArray = array.filter( (value) => value === 'B');
The changedArray will contain the without value 'B'
This solution works for me (using the spread operator of ECMAScript 6):
let array = ['my', 'solution', 'works'];_x000D_
let newArray = [];_x000D_
let newArray2 = [];_x000D_
newArray.push(...array); // Adding to same array_x000D_
newArray2.push([...array]); // Adding as child/leaf/sub-array_x000D_
console.log(newArray);_x000D_
console.log(newArray2);
_x000D_
If you want to find the word you can use
var word = words.Where(item => item.IsKey).First();
This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()
To get both the item and the index you can use
KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
So you want to create a list of lists... We need to start with an empty list
list_of_lists = []
next, we read the file content, line by line
with open('data') as f:
for line in f:
inner_list = [elt.strip() for elt in line.split(',')]
# in alternative, if you need to use the file content as numbers
# inner_list = [int(elt.strip()) for elt in line.split(',')]
list_of_lists.append(inner_list)
A common use case is that of columnar data, but our units of storage are the rows of the file, that we have read one by one, so you may want to transpose your list of lists. This can be done with the following idiom
by_cols = zip(*list_of_lists)
Another common use is to give a name to each column
col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
by_names[col_name] = by_cols[i]
so that you can operate on homogeneous data items
mean_apple_prices = [money/fruits for money, fruits in
zip(by_names['apples revenue'], by_names['apples_sold'])]
Most of what I've written can be speeded up using the csv
module, from the standard library. Another third party module is pandas
, that lets you automate most aspects of a typical data analysis (but has a number of dependencies).
Update While in Python 2 zip(*list_of_lists)
returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists)
returns a zip object that is not subscriptable.
If you need indexed access you can use
by_cols = list(zip(*list_of_lists))
that gives you a list of lists in both versions of Python.
On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...
file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column
When dealing with a hash {}
, use both the key and value to the block inside the ||
.
details.map {|key,item|"" == item}
=>[false, false, true, false, false]
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index
is the array index of your car, or -1 if it doesn't exist.
Basically, don't use ArrayList.toString()
- build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray
when it's not actually an array, by the way.)
One option is strtok
example:
char name[20];
//pretend name is set to the value "My name"
You want to split it at the space between the two words
split=strtok(name," ");
while(split != NULL)
{
word=split;
split=strtok(NULL," ");
}
There are few mistakes you are doing:
addRow
methodsplice
method to remove an element from an array at particular index.my-item
component, where this can be modified.You can see working code here.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
It's simple. I did it the following way to get a string with unique values (from two columns of an output sheet):
Dim startpoint, endpoint, ArrCount As Integer
Dim SentToArr() As String
'created by running the first part (check for new entries)
startpoint = ThisWorkbook.Sheets("temp").Range("A1").Value
'set counter on 0
Arrcount = 0
'last filled row in BG
endpoint = ThisWorkbook.Sheets("BG").Range("G1047854").End(xlUp).Row
'create arr with all data - this could be any data you want!
With ThisWorkbook.Sheets("BG")
For i = startpoint To endpoint
ArrCount = ArrCount + 1
ReDim Preserve SentToArr(1 To ArrCount)
SentToArr(ArrCount) = .Range("A" & i).Value
'get prep
ArrCount = ArrCount + 1
ReDim Preserve SentToArr(1 To ArrCount)
SentToArr(ArrCount) = .Range("B" & i).Value
Next i
End With
'iterate the arr and get a key (l) in each iteration
For l = LBound(SentToArr) To UBound(SentToArr)
Key = SentToArr(l)
'iterate one more time and compare the first key (l) with key (k)
For k = LBound(SentToArr) To UBound(SentToArr)
'if key = the new key from the second iteration and the position is different fill it as empty
If Key = SentToArr(k) And Not k = l Then
SentToArr(k) = ""
End If
Next k
Next l
'iterate through all 'unique-made' values, if the value of the pos is
'empty, skip - you could also create a new array by using the following after the IF below - !! dont forget to reset [ArrCount] as well:
'ArrCount = ArrCount + 1
'ReDim Preserve SentToArr(1 To ArrCount)
'SentToArr(ArrCount) = SentToArr(h)
For h = LBound(SentToArr) To UBound(SentToArr)
If SentToArr(h) = "" Then GoTo skipArrayPart
GetEmailArray = GetEmailArray & "; " & SentToArr(h)
skipArrayPart:
Next h
'some clean up
If Left(GetEmailArray, 2) = "; " Then
GetEmailArray = Right(GetEmailArray, Len(GetEmailArray) - 2)
End If
'show us the money
MsgBox GetEmailArray
You are using the wrong type. The Array(...)
function returns a Variant
, not a String
.
Thus, in the Declaration section of your module (it does not need to be a different module!), you define
Public colHeader As Variant
and somewhere at the beginning of your program code (for example, in the Workbook_Open
event) you initialize it with
colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Another (simple) alternative would be to create a function that returns the array, e.g. something like
Public Function GetHeaders() As Variant
GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function
This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.
Well array.length
should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)
int[] SingleDimensionalArray = new int[2]
int[][] MultiDimensionalArray = new int[3][4]
What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:
part1,"part2,with a comma and a quote "" in it",part3
PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode
:
print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
[0] => part1
[1] => part2,with a comma and a quote " in it
[2] => part3
)
int.from_bytes is the best solution if you are at version >=3.2. The "struct.unpack" solution requires a string so it will not apply to arrays of bytes. Here is another solution:
def bytes2int( tb, order='big'):
if order == 'big': seq=[0,1,2,3]
elif order == 'little': seq=[3,2,1,0]
i = 0
for j in seq: i = (i<<8)+tb[j]
return i
hex( bytes2int( [0x87, 0x65, 0x43, 0x21])) returns '0x87654321'.
It handles big and little endianness and is easily modifiable for 8 bytes
A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
int[][] test;
test = new int[5][];//'2D array'
for (int i=0;i<test.length;i++)
test[i] = new int[i];
System.out.println(Arrays.deepToString(test));
Object[] test2;
test2 = new Object[5];//array of objects
for (int i=0;i<test2.length;i++)
test2[i] = new int[i];//array is a object too
System.out.println(Arrays.deepToString(test2));
}
}
Outputs
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
The arrays test
and test2
are (more or less) the same.
If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.
It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:
np.einsum('ij->ij', a[a[:,1].argsort(),:])
This is an overkill for two dimensions and a[a[:,1].argsort()]
would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.
Output:
[[7 0 5]
[9 2 3]
[4 5 6]]
A slightly faster option than using the already mentioned use of the Join()
method is the Concat() method. It doesn't require an empty delimiter parameter as Join()
does. Example:
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = String.Concat(test);
hence it is likely faster.
Try doing like this: array1.compare(array2)=true
Array.prototype.compare = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
Here's how Prototype does it:
/**
* Array#indexOf(item[, offset = 0]) -> Number
* - item (?): A value that may or may not be in the array.
* - offset (Number): The number of initial items to skip before beginning the
* search.
*
* Returns the position of the first occurrence of `item` within the array — or
* `-1` if `item` doesn't exist in the array.
**/
function indexOf(item, i) {
i || (i = 0);
var length = this.length;
if (i < 0) i = length + i;
for (; i < length; i++)
if (this[i] === item) return i;
return -1;
}
Also see here for how they hook it up.
If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &
-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:
void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference
You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)
), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.
Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.
I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:
void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo1(arr);
foo2(arr);
foo3(arr);
foo4(arr);
}
It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.
Just go with Apache Commons
Using map is the best solution without using extra libraries.(using ES6)
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
if ($value!=$remove) {
echo $value.'<br/>';
continue;
}
}
My attempt.
$ array=(one two "three four" five)
$ echo "${array[0]}$(printf " SEP %s" "${array[@]:1}")"
one SEP two SEP three four SEP five
You could do something like this
String[] myStrings = { "One", "Two", "Three" };
or in expression
functionCall(new String[] { "One", "Two", "Three" });
or
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
when new allocates an array, depending on the compiler (i use gnu c++), the word in front of the array contains information about the number of bytes allocated.
The test code:
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
int arraySz;
char *a;
unsigned int *q;
for (arraySz = 5; arraySz <= 64; arraySz++) {
printf ("%02d - ", arraySz);
a = new char[arraySz];
unsigned char *p = (unsigned char *) a;
q = (unsigned int *) (a - 4);
printf ("%02d\n", (*q));
delete[] (a);
}
}
on my machine dumps out:
05 - 19
06 - 19
07 - 19
08 - 19
09 - 19
10 - 19
11 - 19
12 - 19
13 - 27
14 - 27
15 - 27
16 - 27
17 - 27
18 - 27
19 - 27
20 - 27
21 - 35
22 - 35
23 - 35
24 - 35
25 - 35
26 - 35
27 - 35
28 - 35
29 - 43
30 - 43
31 - 43
32 - 43
33 - 43
34 - 43
35 - 43
36 - 43
37 - 51
38 - 51
39 - 51
40 - 51
41 - 51
42 - 51
43 - 51
44 - 51
45 - 59
46 - 59
47 - 59
48 - 59
49 - 59
50 - 59
51 - 59
52 - 59
53 - 67
54 - 67
55 - 67
56 - 67
57 - 67
58 - 67
59 - 67
60 - 67
61 - 75
62 - 75
63 - 75
64 - 75
I would not recommend this solution (vector is better), but if you are really desperate, you could find a relationship and be able to conclude the number of bytes allocated from the heap.
Looping through the array and inserting a key, value pair is about your best solution. You could use the 'map' function but it is just a matter of preference.
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
arrOfObj.map(function (obj) {
obj.isActive = true;
});
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine. creates the the key with its value in the array
You can use implode to return your array with a string separator.
$withComma = implode(",", $array);
echo $withComma;
// Will display apple,banana,orange
@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this
[{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map( ( {name, email} ) => {
return <p key={email}>{name} - {email}</p>
})
Cheers!
You can use key():
<?php
$array = array(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
);
while($element = current($array)) {
echo key($array)."\n";
next($array);
}
?>
You have to decompose the full object to reach the entry
array.
Assuming REPONSE_JSON_OBJECT
is already a parsed JSONObject
.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
Objective C Solution
NSArray * array = @[@"1", @"2", @"3"];
NSString * stringFromArray = [[array valueForKey:@"description"] componentsJoinedByString:@"-"]; // "1-2-3"
Those who are looking for a solution in Swift
If the array contains strings, you can use the String's join method:
var array = ["1", "2", "3"]
let stringFromArray = "-".join(array) // "1-2-3"
In Swift 2:
var array = ["1", "2", "3"]
let stringFromArray = array.joinWithSeparator("-") // "1-2-3"
In Swift 3 & 4
var array = ["1", "2", "3"]
let stringFromArray = array.joined(separator: "-") // "1-2-3"
It's actually the JavaScript array reduce
function rather than being something specific to TypeScript.
As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
Here's an example which sums up the values of an array:
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
The snippet should produce 6
.
What about this simple code, works for me and on Windows 7
set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin
:end
myarray = "abc";
...is the assignation of a pointer on "abc" to the pointer myarray.
This is NOT filling the myarray buffer with "abc".
If you want to fill the myarray buffer manually, without strcpy(), you can use:
myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;
or
char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;
Your question is about the difference between a pointer and a buffer (an array). I hope you now understand how C addresses each kind.
In newer versions of typescript you can use:
type Customers = Record<string, Customer>
In older versions you can use:
var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer
You can also make an interface if you don't want to type that whole type annotation out every time:
interface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of above
Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method
http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3
The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:
{"list":[
{"value": 1, "label": "abc"},
{"value": 2, "label": "def"},
{"value": 3, "label": "ghi"}
]}
Then on the source portion of the autocomplete method:
source: function(request, response) {
$.getJSON("listing.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.list, function(m) {
return {
label: m.label,
value: m.value
};
});
response(array);
});
},
select: function (event, ui) {
$("#autocomplete_field").val(ui.item.label); // display the selected text
$("#field_id").val(ui.item.value); // save selected id to hidden input
return false;
}
Hope this helps... all the best!
you can create a List[] and initialize them by for loop. it compiles without errors:
List<e>[] l;
for(int i = 0; i < l.length; i++){
l[i] = new ArrayList<e>();
}
it works with arrayList[] l as well.
There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
serialize() and unserialize() convert between php objects and a string representation.
Assuming lengths of portfolio and index are the same:
matrix = []
for i in range(len(portfolio)):
matrix.append([portfolio[i], index[i]])
Or a one-liner using list comprehension:
matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
Panda is quite powerful and smart library reading CSV in Python
A simple example here, I have example.zip file with four files in it.
EXAMPLE.zip
-- example1.csv
-- example1.txt
-- example2.csv
-- example2.txt
from zipfile import ZipFile
import pandas as pd
filepath = 'EXAMPLE.zip'
file_prefix = filepath[:-4].lower()
zipfile = ZipFile(filepath)
target_file = ''.join([file_prefix, '/', file_prefix, 1 , '.csv'])
df = pd.read_csv(zipfile.open(target_file))
print(df.head()) # print first five row of csv
print(df[COL_NAME]) # fetch the col_name data
Once you have data you can manipulate to play with a list or other formats.
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
char **orderIds;
orderIds = malloc(variableNumberOfElements * sizeof(char*));
for(int i = 0; i < variableNumberOfElements; i++) {
orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
strcpy(orderIds[i], your_string[i]);
}
You can't. However, you can replace the array with a new one which contains the extra element.
But it is easier and gives better performance to use an List<T>
(uses interface IList
) for this. List<T>
does not resize the array every time you add an item - instead it doubles it when needed.
Try:
class Student
{
IList<Subject> subjects = new List<Subject>();
}
class Subject
{
string Name;
string referenceBook;
}
Now you can say:
someStudent.subjects.Add(new Subject());
Very often this is done in a while
loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
Have a look at the examples in the documentation.
The mysql_fetch_*
methods will always get the next element of the result set:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
That is why the while
loops works. If there aren't any rows anymore $row
will be false
and the while
loop exists.
It only seems that mysql_fetch_array
gets more than one row, because by default it gets the result as normal and as associative value:
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
Your example shows it best, you get the same value 18
and you can access it via $v[0]
or $v['type']
.
It's easier using Array.filter
:
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:
Code:
Array.prototype.findFirstSubstring = function(s) {
for(var i = 0; i < this.length;i++)
{
if(this[i].indexOf(s) !== -1)
return i;
}
return -1;
};
Usage:
i.findFirstSubstring('height');
Returns:
-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2
)
EDIT: Years ago I gave an answer to this that was gross, too specific, and too complicated. So I'm editing it. I favor the functional answers above for their neat factor but not their readability; but if I were more familiar with javascript then I might like them for that, too.
Pseudo code:
Track index that contains largest value. Assume index 0 is largest initially. Compare against current index. Update index with largest value if necessary.
Code:
var mountains = [3, 1, 5, 9, 4];
function largestIndex(array){
var counter = 1;
var max = 0;
for(counter; counter < array.length; counter++){
if(array[max] < array[counter]){
max = counter;
}
}
return max;
}
console.log("index with largest value is: " +largestIndex(mountains));
// index with largest value is: 3
Here's a simple an quick solution. Hope it helps!.
public int[] reverse(int[] arr) {
for(int i = arr.length; i > 0 ; i--){
System.out.print(arr[i-1] + " ");
}
return arr;
}
It's ok to pass an array - in fact it amounts to the same thing
String.format("%s %s", "hello", "world!");
is the same as
String.format("%s %s", new Object[] { "hello", "world!"});
It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.
See
You can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
Starting with Swift 2, the enumerate function needs to be called on the collection like so:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
I have some fresh tests of different methods of prepending. For small arrays (<1000 elems) the leader is for cycle coupled with a push method. For huge arrays, Unshift method becomes the leader.
But this situation is actual only for Chrome browser. In Firefox unshift has an awesome optimization and is faster in all cases.
ES6 spread is 100+ times slower in all browsers.
As a variant you can use combiantion _.map
and _.ary
methods from the lodash library. Whole transformation will be a more compact. Here is example from the official documentation:
_.map(['6', '8', '10'], _.ary(parseInt, 1));
// ? [6, 8, 10]
var count = 0;
for(var i=0, n=array.length; i < n; i++)
{
count += array[i];
}
This retrieves array.length
once, rather than with each iteration. The optimization is made by caching the value.
var count=0;
for (var i=array.length; i--;) {
count+=array[i];
}
This is equivalent to a while reverse loop. It caches the value and is compared to 0, thus faster iteration.
For a more complete comparison list, see my JSFiddle.
Note: array.reduce is horrible there, but in Firebug Console it is fastest.
I started a JSPerf for array summations. It was quickly constructed and not guaranteed to be complete or accurate, but that's what edit is for :)
Using find with bind to pass specific key values to a callback function.
function byValue(o) {
return o.a === this.a && o.b === this.b;
};
var result = jsObjects.find(byValue.bind({ a: 5, b: 6 }));
Try array_merge.
$array1 = array('Item 1');
$array2 = array('Item 2');
$array3 = array_merge($array1, $array2);
I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.
Best alternative:
public static readonly byte[] ZeroHash = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
If you want to be really efficient and you have enough time to spent, use SIMD instruction.
You can compare several pairs in one instruction:
r0 := min(a0, b0)
r1 := min(a1, b1)
r2 := min(a2, b2)
r3 := min(a3, b3)
__m64 _mm_min_pu8(__m64 a , __m64 b );
Today every computer supports it. Other already have written min function for you:
http://smartdata.usbid.com/datasheets/usbid/2001/2001-q1/i_minmax.pdf
or use already ready library.
arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]
This will return a random element from array.
If You will use the line mentioned below
arr[1+rand(arr.count)]
then in some cases it will return 0 or nil value.
The line mentioned below
rand(number)
always return the value from 0 to number-1.
If we use
1+rand(number)
then it may return number and arr[number] contains no element.
Object.entries()
returns an array whose elements are arrays corresponding to the enumerable property[key, value]
pairs found directly uponobject
. The ordering of the properties is the same as that given by looping over the property values of the object manually.
The Object.entries
function returns almost the exact output you're asking for, except the keys are strings instead of numbers.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
console.log(Object.entries(obj));
_x000D_
If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
const entries = Object.entries(input);_x000D_
return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
I use an arrow function and Object.assign
for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign
returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.
This is equivalent to:
entry => {
entry[0] = +entry[0];
return entry;
}
As mentioned by @TravisClarke in the comments, the map function could be shortened to:
entry => [ +entry[0], entry[1] ]
However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.
Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.
You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
const entries = Object.entries(obj);_x000D_
entries.forEach(entry => entry[0] = +entry[0]);_x000D_
return entries;_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
System.out.println(Arrays.deepToString(array)
.replace("],","\n").replace(",","\t| ")
.replaceAll("[\\[\\]]", " "));
You can remove unwanted brackets with .replace()
, after .deepToString
if you like.
That will look like:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
10 | 11 | 12
13 | 15 | 15
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
I use the following in a console application to check for arguments
var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
Python suggests users use len()
instead of __len__()
for consistency, just like other guys said. However, There're some other benefits:
For some built-in types like list
, str
, bytearray
and so on, the Cython implementation of len()
takes a shortcut. It directly returns the ob_size
in a C structure, which is faster than calling __len__()
.
If you are interested in such details, you could read the book called "Fluent Python" by Luciano Ramalho. There're many interesting details in it, and may help you understand Python more deeply.
Using serialize and unserialize on cookies is a security risk. Users (or attackers) can alter cookie data, then when you unserialize it, it could run PHP code on your server. Cookie data should not be trusted. Use JSON instead!
From PHP's site:
Do not pass untrusted user input to
unserialize()
regardless of theoptions
value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (viajson_decode()
andjson_encode()
) if you need to pass serialized data to the user.
for integer types
#include <string.h>
int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[10];
memcpy(array2,array1,sizeof(array1)); // memcpy("destination","source","size")
If your row length is a compile time constant, C++11 allows
auto arr2d = new int [nrows][CONSTANT];
See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use new
as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.
Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap).
Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this:
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];
The above, for colCount= 5
and rowCount = 4
, would produce the following:
Don't forget to delete
each row separately with a loop, before deleting the array of pointers. Example in another answer.
So when you have multiple occurrences of 3 and you want only to delete the first occurrence of 3, you can simply do some thing as below.
arr = [2, 4, 6, 3, 8, 10, 3, 12]
arr.delete_at arr.index 3
#This will modify arr as [2, 4, 6, 8, 10, 3, 12] where first occurrence of 3 is deleted. Returns the element deleted. In this case => 3.
Empty slice and nil slice are initialized differently in Go:
var nilSlice []int
emptySlice1 := make([]int, 0)
emptySlice2 := []int{}
fmt.Println(nilSlice == nil) // true
fmt.Println(emptySlice1 == nil) // false
fmt.Println(emptySlice2 == nil) // false
As for all three slices, len and cap are 0.
This is almost certainly much slower than any other version given here, but it was fun to write.
static bool ByteArrayEquals(byte[] a1, byte[] a2)
{
return a1.Zip(a2, (l, r) => l == r).All(x => x);
}
Why is this blocked by Java?
You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.
But "why" is immaterial ... the restriction is there, and you have to live with it.
I know how to work around it, but from time to time it would be simpler.
You can write this:
AClass[] array;
...
array = new AClass[]{object1, object2};
-- html file --
<select name='city[]'>
<option name='Kabul' value="Kabul" > Kabul </option>
<option name='Herat' value='Herat' selected="selected"> Herat </option>
<option name='Mazar' value='Mazar'>Mazar </option>
</select>
-- php file --
$city = (isset($_POST['city']) ? $_POST['city']: null);
print("city is: ".$city[0]);
When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.
You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.
String is totally free so please check it out and tell us what you think.
It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string
Use array_count_values()
function . Check this link http://php.net/manual/en/function.array-count-values.php
DELIMITER $$
CREATE DEFINER=`mysqldb`@`%` PROCEDURE `abc`()
BEGIN
BEGIN
set @value :='11,2,3,1,';
WHILE (LOCATE(',', @value) > 0) DO
SET @V_DESIGNATION = SUBSTRING(@value,1, LOCATE(',',@value)-1);
SET @value = SUBSTRING(@value, LOCATE(',',@value) + 1);
select @V_DESIGNATION;
END WHILE;
END;
END$$
DELIMITER ;
To deserialize the response need to use HashMap
:
String resp = ...//String output from your source
Gson gson = new GsonBuilder().create();
gson.fromJson(resp,TheResponse.class);
class TheResponse{
HashMap<String,Song> songs;
}
class Song{
String id;
String pos;
}
Other folks have suggested array_search()
which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values()
:
$list = array(0=>'string1', 'foo'=>'string2', 42=>'string3');
$index = array_search('string2', array_values($list));
print "$index\n";
// result: 1
You said in your question that array_search()
was no use. Can you explain why? What did you try and how did it not meet your needs?
I disagree with the previous answers suggesting ArrayList
, because ArrayList
is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:
ArrayList list = new ArrayList(4);
list.put(3,"Test");
It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance
$elements_array = ['first', 'second'];
function to remove some array elements
function remove($arr, $data) {
return array_filter($arr, function ($element) use ($data) {
return $element != $data;
});
}
call and print
print_r(remove($elements_array, 'second'));
the result
Array ( [0] => first )
Yeah, I missed ++ and -- functionality as well. A few million lines of c code engrained that kind of thinking in my old head, and rather than fight it... Here's a class I cobbled up that implements:
pre- and post-increment, pre- and post-decrement, addition,
subtraction, multiplication, division, results assignable
as integer, printable, settable.
Here 'tis:
class counter(object):
def __init__(self,v=0):
self.set(v)
def preinc(self):
self.v += 1
return self.v
def predec(self):
self.v -= 1
return self.v
def postinc(self):
self.v += 1
return self.v - 1
def postdec(self):
self.v -= 1
return self.v + 1
def __add__(self,addend):
return self.v + addend
def __sub__(self,subtrahend):
return self.v - subtrahend
def __mul__(self,multiplier):
return self.v * multiplier
def __div__(self,divisor):
return self.v / divisor
def __getitem__(self):
return self.v
def __str__(self):
return str(self.v)
def set(self,v):
if type(v) != int:
v = 0
self.v = v
You might use it like this:
c = counter() # defaults to zero
for listItem in myList: # imaginary task
doSomething(c.postinc(),listItem) # passes c, but becomes c+1
...already having c, you could do this...
c.set(11)
while c.predec() > 0:
print c
....or just...
d = counter(11)
while d.predec() > 0:
print d
...and for (re-)assignment into integer...
c = counter(100)
d = c + 223 # assignment as integer
c = c + 223 # re-assignment as integer
print type(c),c # <type 'int'> 323
...while this will maintain c as type counter:
c = counter(100)
c.set(c + 223)
print type(c),c # <class '__main__.counter'> 323
EDIT:
And then there's this bit of unexpected (and thoroughly unwanted) behavior,
c = counter(42)
s = '%s: %d' % ('Expecting 42',c) # but getting non-numeric exception
print s
...because inside that tuple, getitem() isn't what used, instead a reference to the object is passed to the formatting function. Sigh. So:
c = counter(42)
s = '%s: %d' % ('Expecting 42',c.v) # and getting 42.
print s
...or, more verbosely, and explicitly what we actually wanted to happen, although counter-indicated in actual form by the verbosity (use c.v
instead)...
c = counter(42)
s = '%s: %d' % ('Expecting 42',c.__getitem__()) # and getting 42.
print s
WAMP stands for Windows,Apache,Mysql,Php
XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)
It is cross-platform software
It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.
it is easy to configure and use.
It is easy to Use. (Changing Configuration)
WAMP is Available for both 64 bit and 32-bit system.
if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.
i suggest using laragon :
Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.
Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.
Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.
Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.
Pretty URLs
Use app.test
instead of localhost/app
.
Portable
You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.
Isolated
Laragon has an isolated environment with your OS - it will keep your system clean.
Easy Operation
Unlike others which pre-config for you, Laragon auto-configsall
the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.
Modern & Powerful
Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed.
Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.
But its still giving an error message in Query Builder. I am using SqlServerCe 2008.
SELECT Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount,
Order_Details.TotalPrice
FROM Order_Products INNER JOIN
Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))
I replaced WHERE with HAVING as said by @powerlord. But still showing an error.
Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]
Refining Günter Zöchbauer answer:
This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the 'do not apply' case. As an example, I'll demonstrate with a link conditionally having an href attribute applied.
--EDIT--
It looks like angular has changed some things, so null
will now work as expected. I've update the example to use null
rather than undefined
.
An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.
For my navigation, I have a list of links, but one of those links represents the current page. I didn't want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).
<a [attr.href]="currentUrl !== link.url ? link.url : null">
This is cleaner than using two *ngIf's on a span and anchor tag, I think. It's also perfect for adding a disabled attribute to a button.
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Press enter to continue.....");
s.nextLine();
}
This nextline
is a pretty good option as it will help us run next line whenever the enter key is pressed.
small script i wrote to replace all files with .txt extension to .cpp extension under /tmp and sub directories recursively
#!/bin/bash
for file in $(find /tmp -name '*.txt')
do
mv $file $(echo "$file" | sed -r 's|.txt|.cpp|g')
done
Am I doing that right, as far as iterating through the Arraylist goes?
No: by calling iterator
twice in each iteration, you're getting new iterators all the time.
The easiest way to write this loop is using the for-each construct:
for (String s : arrayList)
if (s.equals(value))
// ...
As for
java.lang.ArrayIndexOutOfBoundsException: -1
You just tried to get element number -1
from an array. Counting starts at zero.
you CAN give it environment variables. Just preppend env: before the variable name, like this:
value="${env:MY_HOME}/logs/message.log"
This should be a good case for map and lambda
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
I stand corrected (or at least improved). List comprehensions is even more elegant
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
I have tuned up previous code a little bit. First of all range.Changed hasn't work for me. After I changed range.Changed to richTextBox.TextChanged it turns out that TextChanged event handler can invoke SetDocumentXaml recursively, so I've provided protection against it. I also used XamlReader/XamlWriter instead of TextRange.
public class RichTextBoxHelper : DependencyObject
{
private static HashSet<Thread> _recursionProtection = new HashSet<Thread>();
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
_recursionProtection.Add(Thread.CurrentThread);
obj.SetValue(DocumentXamlProperty, value);
_recursionProtection.Remove(Thread.CurrentThread);
}
public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata(
"",
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
(obj, e) => {
if (_recursionProtection.Contains(Thread.CurrentThread))
return;
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
try
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
var doc = (FlowDocument)XamlReader.Load(stream);
// Set the document
richTextBox.Document = doc;
}
catch (Exception)
{
richTextBox.Document = new FlowDocument();
}
// When the document changes update the source
richTextBox.TextChanged += (obj2, e2) =>
{
RichTextBox richTextBox2 = obj2 as RichTextBox;
if (richTextBox2 != null)
{
SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
}
};
}
)
);
}
Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
function getWindowRelativeOffset(parentWindow, elem) {
var offset = {
left : 0,
top : 0
};
// relative to the target field's document
offset.left = elem.getBoundingClientRect().left;
offset.top = elem.getBoundingClientRect().top;
// now we will calculate according to the current document, this current
// document might be same as the document of target field or it may be
// parent of the document of the target field
var childWindow = elem.document.frames.window;
while (childWindow != parentWindow) {
offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
childWindow = childWindow.parent;
}
return offset;
};
you can call it like this
getWindowRelativeOffset(top, inputElement);
I focus for IE only as per my requirement but similar can be done for other browsers
CLOSE_WAIT
means your program is still running, and hasn't closed the socket (and the kernel is waiting for it to do so). Add -p
to netstat
to get the pid, and then kill it more forcefully (with SIGKILL
if needed). That should get rid of your CLOSE_WAIT
sockets. You can also use ps
to find the pid.
SO_REUSEADDR
is for servers and TIME_WAIT
sockets, so doesn't apply here.
First define an object to hold the entity coming back in the array.. e.g.
@JsonIgnoreProperties(ignoreUnknown = true)
public class Rate {
private String name;
private String code;
private Double rate;
// add getters and setters
}
Then you can consume the service and get a strongly typed list via:
ResponseEntity<List<Rate>> rateResponse =
restTemplate.exchange("https://bitpay.com/api/rates",
HttpMethod.GET, null, new ParameterizedTypeReference<List<Rate>>() {
});
List<Rate> rates = rateResponse.getBody();
The other solutions above will also work, but I like getting a strongly typed list back instead of an Object[].
As an alternative to Regex, running:
Sub Replacer()
Dim N As Long, i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
If Left(Cells(i, "A").Value, 9) = "texts are" Then
Cells(i, "A").Value = "texts are replaced"
End If
Next i
End Sub
will produce:
You can also combine the two env_keep
statements in Ahmed Aswani's answer into a single statement like this:
Defaults env_keep += "http_proxy https_proxy"
You should also consider specifying env_keep
for only a single command like this:
Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"
conio.h
is a C
header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.
The #include <curses.h>
will give you almost all the functionalities that was provided in conio.h
nucurses need to be installed at the first place
In deb based Distros use
sudo apt-get install libncurses5-dev libncursesw5-dev
And in rpm based distros use
sudo yum install ncurses-devel ncurses
For getch()
class of functions, you can try this
The @Url.Action()
method is proccess on the server-side
, so you cannot pass a client-side
value to this function as a parameter. You can concat the client-side
variables with the server-side
url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer")
is processed on the server-side
and the rest of the string is processed on the client-side
, concatenating the result of the server-side
method with the client-side
.
One way around this problem is to use stored procedures with an output parameter.
exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2
values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.
optional : if you set config about php.ini but still can't upload
-this is php function to check error code
$error_type = [];
$error_type[0] = "There is no error";
$error_type[1] = "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
$error_type[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
$error_type[3] = "The uploaded file was only partially uploaded.";
$error_type[4] = "No file was uploaded.";
//$error_type["5"] = "";
$error_type[6] = "Missing a temporary folder. Introduced in PHP 5.0.3.";
$error_type[7] = "Failed to write file to disk. Introduced in PHP 5.1.0.";
$error_type[8] = "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.";
//------------------------------
//--> show msg error.
$status_code = $_FILES["uploadfile"]["error"];
if($status_code != 0){
echo $error_type[$status_code];
exit;
}
Amazon provides a policy generator tool:
https://awspolicygen.s3.amazonaws.com/policygen.html
After that, you can enter the policy requirements for the bucket on the AWS console:
curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects
--note
base46 encode =ZnJlZDpmcmVk
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
This is much easier in pandas now with drop_duplicates and the keep parameter.
import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)
I know it is an old question but i faced this error today.
and i found that, this error can be thrown when a database table trigger gets an error.
for your information, you can check your tables triggers too when you get this error.
Use
s.length()
The following was once suggested in one of the answers, but its very inefficient
textMessage.getText().toString().length()
START
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
NSError *error = nil;
NSString *filename = [NSString stringWithFormat:@"%@.caf",FILENAME];
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename];
NSURL *soundFileURL = [NSURL fileURLWithPath:path];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey,
[NSNumber numberWithInt:AVAudioQualityMedium], AVSampleRateConverterAudioQualityKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:22050.0],AVSampleRateKey,
nil];
AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (!error && [audioRecorder prepareToRecord])
{
[audioRecorder record];
}
STOP
[audioRecorder stop];
[audioRecorder release];
audioRecorder = nil;
I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
optionsBuilder.UseSqlServer(connectionString);
}
}
Sometimes we have an upstream that rebased/rewound a branch we're depending on. This can be a big problem -- causing messy conflicts for us if we're downstream.
The magic is
git pull --rebase
A normal git pull is, loosely speaking, something like this (we'll use a remote called origin and a branch called foo in all these examples):
# assume current checked out branch is "foo" git fetch origin git merge origin/foo
At first glance, you might think that a git pull --rebase does just this:
git fetch origin git rebase origin/foo
But that will not help if the upstream rebase involved any "squashing" (meaning that the patch-ids of the commits changed, not just their order).
Which means git pull --rebase has to do a little bit more than that. Here's an explanation of what it does and how.
Let's say your starting point is this:
a---b---c---d---e (origin/foo) (also your local "foo")
Time passes, and you have made some commits on top of your own "foo":
a---b---c---d---e---p---q---r (foo)
Meanwhile, in a fit of anti-social rage, the upstream maintainer has not only rebased his "foo", he even used a squash or two. His commit chain now looks like this:
a---b+c---d+e---f (origin/foo)
A git pull at this point would result in chaos. Even a git fetch; git rebase origin/foo would not cut it, because commits "b" and "c" on one side, and commit "b+c" on the other, would conflict. (And similarly with d, e, and d+e).
What
git pull --rebase
does, in this case, is:git fetch origin git rebase --onto origin/foo e foo
This gives you:
a---b+c---d+e---f---p'---q'---r' (foo)
You may still get conflicts, but they will be genuine conflicts (between p/q/r and a/b+c/d+e/f), and not conflicts caused by b/c conflicting with b+c, etc.
Answer taken from (and slightly modified):
http://gitolite.com/git-pull--rebase
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel
, and the scriptmanager
is on the usercontrol
.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com
You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255
Create a file with the name of your helper in /application/helpers and add it to the autoload config file/load it manually.
E.g. place a file called user_helper.php in /application/helpers with this content:
<?php
function pre($var)
{
echo '<pre>';
if(is_array($var)) {
print_r($var);
} else {
var_dump($var);
}
echo '</pre>';
}
?>
Now you can either load the helper via $this->load->helper(‘user’);
or add it to application/config/autoload.php config.
Here is a solution using the magic method __invoke
(Available since php 5.3)
class Foo {
public function __invoke($method=null, $args=[]){
if($method){
return call_user_func_array([$this, $method], $args);
}
return false;
}
public function methodName($arg1, $arg2, $arg3){
}
}
From inside same class:
$this('methodName', ['arg1', 'arg2', 'arg3']);
From an instance of an object:
$obj = new Foo;
$obj('methodName', ['arg1', 'arg2', 'arg3'])
Well, just to be different, I found an article that references using Reflection.Emit to do so.
Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.
A very detailed and analytic discussion on the topic is available on THIS page
It has the example codes and the pros/cons of different options.
Try this.
First in your searchable xml the fields (name and hint etc) put @string
and not literal strings.
Then method onCreateOptionsMenu
, it must have a ComponentName
object with your package name and your completed class name (with package name) - In case activity which has the SearchView
component is the same as the show search results use getComponentName()
, as the google android developer says.
I tried a lot of solutions and after much,much work this solution works for me.
After this question was asked, Facebook launched HipHop for PHP which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.
Beyond that, googling PHP compiler
turns up a number of 3rd party solutions.
bcompiler_write_exe_footer()
manual)You can load an XML document into an XMLType, then query it, e.g.:
DECLARE
x XMLType := XMLType(
'<?xml version="1.0" ?>
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>');
BEGIN
FOR r IN (
SELECT ExtractValue(Value(p),'/row/name/text()') as name
,ExtractValue(Value(p),'/row/Address/State/text()') as state
,ExtractValue(Value(p),'/row/Address/City/text()') as city
FROM TABLE(XMLSequence(Extract(x,'/person/row'))) p
) LOOP
-- do whatever you want with r.name, r.state, r.city
END LOOP;
END;
To illustrate the many excellent explanations, I developed the following console app:
using System;
using System.Collections.Generic;
namespace CSharpDemos
{
class Program
{
static void Main(string[] args)
{
List<string> StringList = new List<string> { "Hello" };
List<string> StringListRef = new List<string> { "Hallo" };
AppendWorld(StringList);
Console.WriteLine(StringList[0] + StringList[1]);
HalloWelt(ref StringListRef);
Console.WriteLine(StringListRef[0] + StringListRef[1]);
CiaoMondo(out List<string> StringListOut);
Console.WriteLine(StringListOut[0] + StringListOut[1]);
}
static void AppendWorld(List<string> LiStri)
{
LiStri.Add(" World!");
LiStri = new List<string> { "¡Hola", " Mundo!" };
Console.WriteLine(LiStri[0] + LiStri[1]);
}
static void HalloWelt(ref List<string> LiStriRef)
{ LiStriRef = new List<string> { LiStriRef[0], " Welt!" }; }
static void CiaoMondo(out List<string> LiStriOut)
{ LiStriOut = new List<string> { "Ciao", " Mondo!" }; }
}
}
/*Output:
¡Hola Mundo!
Hello World!
Hallo Welt!
Ciao Mondo!
*/
AppendWorld
: A copy of StringList
named LiStri
is passed. At the
start of the method, this copy references the original list and
therefore can be used to modify this list. Later LiStri
references
another List<string>
object inside the method which doesn't affect
the original list.
HalloWelt
: LiStriRef
is an alias of the already initialized
ListStringRef
. The passed List<string>
object is used to initialize a
new one, therefore ref
was necessary.
CiaoMondo
: LiStriOut
is an alias of ListStringOut
and must be
initialized.
So, if a method just modifies the object referenced by the passed variable, the compiler will not let you use out
and you should not use ref
because it would confuse not the compiler but the reader of the code. If the method will make the passed argument reference another object, use ref
for an already initialized object and out
for methods that must initialize a new object for the passed argument. Besides that, ref
and out
behave the same.
If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe
Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value
But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version
Sub CommandClick()
Dim rCell As Range
Dim rNext As Range
For Each rCell In Sheet2.Range("C1:C30000").Cells
If rCell.Value >= 100 And rCell.Value < 1000 Then
Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
End If
Next rCell
End Sub
What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class
, or an interface
does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.
Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:
In typical usage, the TypeSpec (if present) identifies a delegate whose signature matches the arguments passed to the event’s fire method.
However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a List
or a Dictionary
or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.
When you have several words like this which you want to concatenate in a string, I recommend using format
or f-strings
which increase readability dramatically (in my opinion).
To give an example:
s = "a word that needs quotation marks"
s2 = "another word"
Now you can do
print('"{}" and "{}"'.format(s, s2))
which will print
"a word that needs quotation marks" and "another word"
As of Python 3.6 you can use:
print(f'"{s}" and "{s2}"')
yielding the same output.
As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.
I would suggest try using DBWeaver from here :
I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.
You can also join if the number of columns are not same in both tables and can map static value to table column
from t1 in Table1
join t2 in Table2
on new {X = t1.Column1, Y = 0 } on new {X = t2.Column1, Y = t2.Column2 }
select new {t1, t2}
EDIT: Note that this method won't work with crontab -e, but only works if you edit /etc/crontab directly. Otherwise, you may get an error like /bin/sh: www-data: command not found
Just before the program name:
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1
You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.
However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.
IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:
overflow: auto;
overflow-y: hidden;
You may also need to add for IE8:
-ms-overflow-y: hidden;
as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)
On the other hand it's entirely possible IE8 will have fixed the bug anyway.
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
You can use:
CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO
To create the login (See here for more details).
Then you may need to use:
CREATE USER user_name
To create the user associated with the login for the specific database you want to grant them access too.
(See here for details)
You can also use:
GRANT permission [ ,...n ] ON SCHEMA :: schema_name
To set up the permissions for the schema's that you assigned the users to.
(See here for details)
Two other commands you might find useful are ALTER USER and ALTER LOGIN.
Try this regex "[-.]+"
. The + after treats consecutive delimiter chars as one. Remove plus if you do not want this.
if ($select.find('option[value=' + val + ']').length) {...}
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
You could use asprintf
to concatenate both into a new string:
char *new_str;
asprintf(&new_str,"%s%s",str1,str2);
How can I get the value from the map, which is passed as a reference to a function?
Well, you can pass it as a reference. The standard reference wrapper that is.
typedef std::map<std::string, std::string> MAP;
// create your map reference type
using map_ref_t = std::reference_wrapper<MAP>;
// use it
void function(map_ref_t map_r)
{
// get to the map from inside the
// std::reference_wrapper
// see the alternatives behind that link
MAP & the_map = map_r;
// take the value from the map
// by reference
auto & value_r = the_map["key"];
// change it, "in place"
value_r = "new!";
}
And the test.
void test_ref_to_map() {
MAP valueMap;
valueMap["key"] = "value";
// pass it by reference
function(valueMap);
// check that the value has changed
assert( "new!" == valueMap["key"] );
}
I think this is nice and simple. Enjoy ...
you could also create a class which extends ArrayList
:
public static class MyList extends ArrayList<Myclass> {}
and then use it like:
List<MyClass> list = objectMapper.readValue(json, MyList.class);
I've mapped File.Close to CTRL+SHIFT+W. That and CTRL+TAB mean you can close exactly whichever files you want.
The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:
//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]
list all containers with info and ID
docker ps
docker stop CONTAINER ID
For me i wanted to implement a 2-way handshake, meaning:
- the parent window will load faster then the iframe
- the iframe should talk to the parent window as soon as its ready
- the parent is ready to receive the iframe message and replay
this code is used to set white label in the iframe using [CSS custom property]
code:
iframe
$(function() {
window.onload = function() {
// create listener
function receiveMessage(e) {
document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
//alert(e.data.data.header_bg);
}
window.addEventListener('message', receiveMessage);
// call parent
parent.postMessage("GetWhiteLabel","*");
}
});
parent
$(function() {
// create listener
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
// replay to child (iframe)
document.getElementById('wrapper-iframe').contentWindow.postMessage(
{
event_id: 'white_label_message',
wl: {
header_bg: $('#Header').css('background-color'),
header_text: $('#Header .HoverMenu a').css('color'),
button_bg: $('#Header .HoverMenu a').css('background-color')
}
},
'*'
);
}, false);
});
naturally you can limit the origins and the text, this is easy-to-work-with code
i found this examlpe to be helpful:
[Cross-Domain Messaging With postMessage]
You could also use indexOf instead to do this
var i = review.indexOf('\u2022 \u2022 \u2022');
if (i !== -1) review.splice(i,1);
A merge conflict occurs when two branches you're trying to merge both changed the same part of the same file. You can generate a list of conflicts with git status
.
When the conflicted line is encountered, Git will edit the content of the affected files with visual indicators that mark both sides of the conflicting content.
<<<<<<< HEAD
conflicted text from HEAD
=======
conflicted text from merging_branch
>>>>>>> merging_branch
When you fix your conflicted files and you are ready to merge, all you have to do is run git add
and git commit
to generate the merge commit. Once the commit was made ,git push
the changes to the branch.
Reference article: Git merge.
Ok, looks like your post got editted...
double foo[4];
double *bar_1 = &foo[0];
See how you can use the &
to get the address of the beginning of the array structure? The following
Foo_1(double *bar, int size){ return bar[size-1]; }
Foo_2(double bar[], int size){ return bar[size-1]; }
will do the same thing.
For anyone who is still having issues after trying all the answers on this page, the following (finally) worked:
sudo apt-get install libgmp3-dev
gem install pg
This was after doing everything else mentioned on this page.
postgresql 9.5.8
Ubuntu 16.10
You can also use ISNULL and a select statement to get this result
SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
This is my implementation of the T4 suggestion... This will increment the build number every time you build the project regardless of the selected configuration (i.e. Debug|Release), and it will increment the revision number every time you do a Release build. You can continue to update the major and minor version numbers through Application ➤ Assembly Information...
To explain in more detail, this will read the existing AssemblyInfo.cs
file, and use regex to find the AssemblyVersion
information and then increment the revision and build numbers based on input from TextTransform.exe
.
AssemblyInfo.cs
file.Create a AssemblyInfo.tt
file in its place. Visual Studio should create AssemblyInfo.cs
and group it with the T4 file after you save the T4 file.
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
string output = File.ReadAllText(this.Host.ResolvePath("AssemblyInfo.cs"));
Regex pattern = new Regex("AssemblyVersion\\(\"(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
MatchCollection matches = pattern.Matches(output);
if( matches.Count == 1 )
{
major = Convert.ToInt32(matches[0].Groups["major"].Value);
minor = Convert.ToInt32(matches[0].Groups["minor"].Value);
build = Convert.ToInt32(matches[0].Groups["build"].Value) + 1;
revision = Convert.ToInt32(matches[0].Groups["revision"].Value);
if( this.Host.ResolveParameterValue("-","-","BuildConfiguration") == "Release" )
revision++;
}
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information
[assembly: AssemblyTitle("Insert title here")]
[assembly: AssemblyDescription("Insert description here")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Insert company here")]
[assembly: AssemblyProduct("Insert product here")]
[assembly: AssemblyCopyright("Insert copyright here")]
[assembly: AssemblyTrademark("Insert trademark here")]
[assembly: AssemblyCulture("")]
// Version informationr(
[assembly: AssemblyVersion("<#= this.major #>.<#= this.minor #>.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("<#= this.major #>.<#= this.minor #>.<#= this.revision #>.<#= this.build #>")]
[assembly: NeutralResourcesLanguageAttribute( "en-US" )]
<#+
int major = 1;
int minor = 0;
int revision = 0;
int build = 0;
#>
Add this to your pre-build event:
"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\$(VisualStudioVersion)\TextTransform.exe" -a !!BuildConfiguration!$(Configuration) "$(ProjectDir)Properties\AssemblyInfo.tt"
There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:
Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.
As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.
The below seems to work for me.
using System;
using System.Reflection;
public class ReflectStatic
{
private static int SomeNumber {get; set;}
public static object SomeReference {get; set;}
static ReflectStatic()
{
SomeReference = new object();
Console.WriteLine(SomeReference.GetHashCode());
}
}
public class Program
{
public static void Main()
{
var rs = new ReflectStatic();
var pi = rs.GetType().GetProperty("SomeReference", BindingFlags.Static | BindingFlags.Public);
if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
Console.WriteLine(pi.GetValue(rs, null).GetHashCode());
}
}
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
You can set Maven to use any java version following the instructions below.
Install jenv in your machine link
Check the available java versions installed in your machine by issuing the following command in command line.
jenv versions
You can specify global Java version using the following command.
jenv global oracle64-1.6.0.39
You can specify local Java version for any directory(Project) using the following command in the directory in command line.
jenv local oracle64-1.7.0.11
add the correct java version in your pom.xml
if you are running maven in command line install jenv maven plugin using below command
jenv enable-plugin maven
Now you can configure any java version in your machine to any project with out any trouble.
Here is my answer:
def draw_text(text, font_name, size, color, x, y, align="nw"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".
In query, CONCAT_WS()
function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000
".
new Guid()
default(Guid)
Guid.Empty
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
Maybe it is easier to convert the Date into the actual integer 20110506105524
and then convert this into a string:
function printDate() {
var temp = new Date();
var dateInt =
((((temp.getFullYear() * 100 +
temp.getMonth() + 1) * 100 +
temp.getDate()) * 100 +
temp.getHours()) * 100 +
temp.getMinutes()) * 100 +
temp.getSeconds();
debug ( '' + dateInt ); // convert to String
}
When temp.getFullYear() < 1000
the result will be one (or more) digits shorter.
Caution: this wont work with millisecond precision (i.e. 17 digits) since Number.MAX_SAFE_INTEGER is 9007199254740991
which is only 16 digits.
SELECT * FROM yourtable WHERE yourtimestampfield LIKE 'AAAA-MM%';
Where AAAA
is the year you want and MM
is the month you want
import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.
For getting all post parameters there is Map which contains request param name as key and param value as key.
Map params = servReq.getParameterMap();
And to get parameters with known name normal
String userId=servReq.getParameter("user_id");
For me I had to put the project x/src/test/java/ at the bottom of the "order and export" in the "java build path"
I was with the same problem in devices with SDK < 22, but for me the reason is the MultiDex, the MultiDex.install
must be in the attachBaseContext
method.
If you are using MultiDex, try this:
public class YourApplication extends Application {
@Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
Realm.init(this); //initialize other plugins
}
}
app/build.gradle:
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.test.app"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
....
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.2.1'
...
compile 'com.google.firebase:firebase-messaging:9.6.1'
compile 'com.google.android.gms:play-services:9.6.1'
compile 'com.android.support:multidex:1.0.1'
}
...
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
See following thread:
It sounds like perhaps the class is not the UITableViewDelegate
for that table view, though UITableViewController
is supposed to set that automatically.
Any chance you reset the delegate to some other class?
I had to do: c:\Users\xxxx>c:/python27/scripts/pip install openpyxl
I had to save the openpyxl files in the scripts folder.
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects
.
See their examples:
string myJsonString = @"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
To drop a table if there is a foreign key constraint in MySQL Server?
Run the sql query:
SET FOREIGN_KEY_CHECKS = 0; DROP TABLE table_name
Hope it helps!
All above solutions make table header scroll too... If you want to scroll tbody only then apply this:
tbody {
height: 100px !important;
overflow: scroll;
display:block;
}
I've had same problem, and this is how I fixed it:
Just throw this in your web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Good news! Python 3.4 (released March 2014) ships with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Nodejs, Haskell, Perl, Go--almost every other contemporary language with a majority open-source community. Thank you Python.
Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this at Does Python have a package/module management system?
Alas for everyone using an earlier Python. Manual instructions follow.
Follow my detailed instructions at https://stackoverflow.com/a/12476379/284795 . Essentially
Per https://pip.pypa.io/en/stable/installing.html
Download get-pip.py
, being careful to save it as a .py
file rather than .txt
. Then, run it from the command prompt.
python get-pip.py
You possibly need an administrator command prompt to do this. Follow http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx
For me, this installed Pip at C:\Python27\Scripts\pip.exe
. Find pip.exe
on your computer, then add its folder (eg. C:\Python27\Scripts
) to your path (Start / Edit environment variables). Now you should be able to run pip
from the command line. Try installing a package:
pip install httpie
There you go (hopefully)!
You can try as.vector(t(test))
. Please note that, if you want to do it by columns you should use unlist(test)
.
You can animate the position (top, bottom, left, right) and then subtract the element's width or height through a CSS transformation.
Consider:
$('.animate').on('click', function(){
$(this).toggleClass("move");
})
_x000D_
.animate {
height: 100px;
width: 100px;
background-color: #c00;
transition: all 1s ease;
position: absolute;
cursor: pointer;
font: 13px/100px sans-serif;
color: white;
text-align: center;
}
/* ? just to position things */
.animate.left { left: 0; top: 50%; margin-top: -100px;}
.animate.right { right: 0; top: 50%; }
.animate.top { top: 0; left: 50%; }
.animate.bottom { bottom: 0; left: 50%; margin-left: -100px;}
.animate.left.move {
left: 100%;
transform: translate(-100%, 0);
}
.animate.right.move {
right: 100%;
transform: translate(100%, 0);
}
.animate.top.move {
top: 100%;
transform: translate(0, -100%);
}
.animate.bottom.move {
bottom: 100%;
transform: translate(0, 100%);
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click to animate
<div class="animate left">left</div>
<div class="animate top">top</div>
<div class="animate bottom">bottom</div>
<div class="animate right">right</div>
_x000D_
And then animate depending on the position...
Google now has a feature stating that it won't allow insecure devices to send emails. When I ran my program it came up with the error in the first post. I had to go into my account and allow insecure apps to send emails, which I did by clicking on my account, going into the security tab, and allowing insecure apps to use my gmail.
Technically, Breadth-first search (BFS) by itself does not let you find the shortest path, simply because BFS is not looking for a shortest path: BFS describes a strategy for searching a graph, but it does not say that you must search for anything in particular.
Dijkstra's algorithm adapts BFS to let you find single-source shortest paths.
In order to retrieve the shortest path from the origin to a node, you need to maintain two items for each node in the graph: its current shortest distance, and the preceding node in the shortest path. Initially all distances are set to infinity, and all predecessors are set to empty. In your example, you set A's distance to zero, and then proceed with the BFS. On each step you check if you can improve the distance of a descendant, i.e. the distance from the origin to the predecessor plus the length of the edge that you are exploring is less than the current best distance for the node in question. If you can improve the distance, set the new shortest path, and remember the predecessor through which that path has been acquired. When the BFS queue is empty, pick a node (in your example, it's E) and traverse its predecessors back to the origin. This would give you the shortest path.
If this sounds a bit confusing, wikipedia has a nice pseudocode section on the topic.
Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:
TableA:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataA11 |
| 1 | DataA12 |
| 1 | DataA13 |
| 2 | DataA21 |
| 3 | DataA31 |
+----+---------+
TableB:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataB11 |
| 2 | DataB21 |
| 2 | DataB22 |
| 2 | DataB23 |
| 4 | DataB41 |
+----+---------+
Inner Join on column Id
will return columns from both the tables and only the matching records:
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
'----'---------'----'---------'
Left Join (or Left Outer join) on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table):
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
:----+---------+----+---------:
| 3 | DataA31 | | |
'----'---------'----'---------'
Right Join (or Right Outer join) on column Id
will return columns from both the tables and matching records with records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
+----+---------+----+---------¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Full Outer Join on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
¦----+---------+----+---------¦
¦ - ¦ ¦ ¦ ¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ 3 ¦ DataA31 ¦ ¦ ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Left Semi Join on column Id
will return columns only from left table and matching records only from left table:
+--------------+
¦ Id ¦ Data ¦
+----+---------¦
¦ 1 ¦ DataA11 ¦
¦ 1 ¦ DataA12 ¦
¦ 1 ¦ DataA13 ¦
¦ 2 ¦ DataA21 ¦
+--------------+
display
settingIt is of course possible - JSFiddle proof of concept where you can see all three possible solutions:
display: inline-block
- this is the one you're not aware of
position: absolute
float: left/right
Use like this
<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>
As other answers note, the correct way to find the Java home directory is to use /usr/libexec/java_home
.
The official documentation for this is in Apple's Technical Q&A QA1170: Important Java Directories on OS X: https://developer.apple.com/library/mac/qa/qa1170/_index.html
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
You can use str.split
by whitespace (default separator) and parameter expand=True
for DataFrame
with assign to new columns:
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL']})
print (df)
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
df[['a','b']] = df['row'].str.split(n=1, expand=True)
print (df)
row a b
0 00000 UNITED STATES 00000 UNITED STATES
1 01000 ALABAMA 01000 ALABAMA
2 01001 Autauga County, AL 01001 Autauga County, AL
3 01003 Baldwin County, AL 01003 Baldwin County, AL
4 01005 Barbour County, AL 01005 Barbour County, AL
Modification if need remove original column with DataFrame.pop
df[['a','b']] = df.pop('row').str.split(n=1, expand=True)
print (df)
a b
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
What is same like:
df[['a','b']] = df['row'].str.split(n=1, expand=True)
df = df.drop('row', axis=1)
print (df)
a b
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
If get error:
#remove n=1 for split by all whitespaces
df[['a','b']] = df['row'].str.split(expand=True)
ValueError: Columns must be same length as key
You can check and it return 4 column DataFrame
, not only 2:
print (df['row'].str.split(expand=True))
0 1 2 3
0 00000 UNITED STATES None
1 01000 ALABAMA None None
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
Then solution is append new DataFrame
by join
:
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL'],
'a':range(5)})
print (df)
a row
0 0 00000 UNITED STATES
1 1 01000 ALABAMA
2 2 01001 Autauga County, AL
3 3 01003 Baldwin County, AL
4 4 01005 Barbour County, AL
df = df.join(df['row'].str.split(expand=True))
print (df)
a row 0 1 2 3
0 0 00000 UNITED STATES 00000 UNITED STATES None
1 1 01000 ALABAMA 01000 ALABAMA None None
2 2 01001 Autauga County, AL 01001 Autauga County, AL
3 3 01003 Baldwin County, AL 01003 Baldwin County, AL
4 4 01005 Barbour County, AL 01005 Barbour County, AL
With remove original column (if there are also another columns):
df = df.join(df.pop('row').str.split(expand=True))
print (df)
a 0 1 2 3
0 0 00000 UNITED STATES None
1 1 01000 ALABAMA None None
2 2 01001 Autauga County, AL
3 3 01003 Baldwin County, AL
4 4 01005 Barbour County, AL
All that the test
attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
<c:if test="true">Hello world!</c:if>
The code within the <%= %>
returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if>
tag looks for.
This isn't possible with ruby currently. You can't pass 'empty' attributes to methods. The closest you can get is to pass nil:
ldap_get(base_dn, filter, nil, X)
However, this will set the scope to nil, not LDAP::LDAP_SCOPE_SUBTREE.
What you can do is set the default value within your method:
def ldap_get(base_dn, filter, scope = nil, attrs = nil)
scope ||= LDAP::LDAP_SCOPE_SUBTREE
... do something ...
end
Now if you call the method as above, the behaviour will be as you expect.
Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.
For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.
Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.
If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output()
command. Here is an example:
output = subprocess.check_output('ls')
To also redirect stderr you can use the following:
output = subprocess.check_output('ls', stderr=subprocess.STDOUT)
In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.
output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)
This is the safest solution:
git stash
Now you can do whatever you want without fear of conflicts.
For instance:
git checkout origin/master
If you want to include the remote changes in the master branch you can do:
git reset --hard origin/master
This will make you branch "master" to point to "origin/master".
Try this:
<h2>Favorite color</h2>
<select name="color">
<option value=""></option>
<option>Pink</option>
<option>Red</option>
<option>Blue</option>
</select>
The first option in the drop down would be blank.
You need to set the location
header as follows:
header('Location: http://www.example.com/');
Replacing http://www.example.com
of course with the url of your landing page.
Add this where you have finished logging the user in.
Note: When redirecting the user will be immediately redirected so you're message probably won't display.
Additionally, you need to move your PHP code to the top of the file for this solution to work.
On another side note, please see my comment above regarding the use of the deprecated mysql
statements and consider using the newer, safer and improved mysqli
or PDO
statements.
myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;
or the slightly shorter
myCars.Select((car, index) => new {car, index}).First(myCondition).index;
Since there are already many great solutions suggested, ill try to give a more dipictive explanation.
How to skip going back to the previous activity?
Remove the previous Activity from Backstack. Simple
How to remove the previous Activity from Backstack?
Call finish()
method
All the activities are stored in a Stack known as Backstack.
When you start a new Activity(startActivity(...)
) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
One key point to note is that when the back button is pressed then finish();
method is called internally. This is the default behavior of onBackPressed() method.
ie A<--- C
Just add finish();
method after your startActvity(...)
in the Activity B
Intent i = new Intent(this, C.class);
startActivity(i);
finish();
If you have a SOAPMessage
or SOAPMessageContext
, you can use a Transformer
, by converting it to a Source
via DOMSource
:
final SOAPMessage message = messageContext.getMessage();
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(message.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
// Now you have the XML as a String:
System.out.println(sw.toString());
This will take the encoding into account, so your "special characters" won't get mangled.
For Mac OS:
#ifdef __APPLE__
For MingW on Windows:
#ifdef __MINGW32__
For Linux:
#ifdef __linux__
For other Windows compilers, check this thread and this for several other compilers and architectures.
EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;
, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.
When you apply the following CSS to an element
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
Here's a Fiddle that demonstrates the effect.
You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".
Based on the stacktrace, an intuit class com.intuit.ipp.aggcat.util.SAML2AssertionGenerator needs a saml jar on the classpath.
A saml class org.opensaml.xml.XMLConfigurator needs on it's turn log4j, which is inside the WAR but cannot find it.
One explanation for this is that the class XMLConfigurator that needs log4j was found not inside the WAR but on a downstream classloader. could a saml jar be missing from the WAR?
The class XMLConfigurator that needs log4j cannot find it at the level of the classloader that loaded it, and the log4j version on the WAR is not visible on that particular classloader.
In order to troubleshoot this, a way is to add this before the oauth call:
System.out.println("all versions of log4j Logger: " + getClass().getClassLoader().getResources("org/apache/log4j/Logger.class") );
System.out.println("all versions of XMLConfigurator: " + getClass().getClassLoader().getResources("org/opensaml/xml/XMLConfigurator.class") );
System.out.println("all versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class: " + OAuthAuthorizer.class.getClassLoader().getResources("org/opensaml/xml/XMLConfigurator.class") );
System.out.println("all versions of log4j visible from the classloader of the OAuthAuthorizer class: " + OAuthAuthorizer.class.getClassloader().getResources("org/apache/log4j/Logger.class") );
Also if you are using Java 7, have a look at jHades, it's a tool I made to help troubleshooting these type of problems.
In order to see what is going on, could you post the results of the classpath queries above, for which container is this happening, tomcat, jetty? It would be better to put the full stacktrace with all the caused by's in pastebin, just in case.
@zetysz and @Manish already fixed the problem. I am just putting this in an answer for future reference:
pip
refers to Python 2 as a default in Ubuntu, this means that pip install x
will install the module for Python 2 and not for 3
pip3
refers to Python 3, it will install the module for Python 3
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir
Here is another simple clean way:
var jsonArr = [];
grid.getStore().each( function (model) {
jsonArr.push(model.data);
});
In case anybody comes back to this, I think the problem here was failing to install the parent pom first, which all these submodules depend on, so the Maven Reactor can't collect the necessary dependencies to build the submodule.
So from the root directory (here D:\luna_workspace\empire_club\empirecl
) it probably just needs a:
mvn clean install
(Aside: <relativePath>../pom.xml</relativePath>
is not really necessary as it's the default value).
I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:
Try using isnull(a), isnotnull(a), nvl(), etc. On some versions(potentially in conjunction with the server settings - atleast with the one I am working on) of hive the 'IS NULL' and 'IS NOT NULL' syntax does not execute the logic when it is compiled. Check here for more information.
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
This problem is because port 80 is used by some other application. Try to reconfigure port.
//To delete all the files of a specific folder & subfolder
public static void deleteFiles(File directory, Context c) {
try {
for (File file : directory.listFiles()) {
if (file.isFile()) {
final ContentResolver contentResolver = c.getContentResolver();
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
if (file.exists()) {
file.delete();
if (file.exists()) {
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if (file.exists()) {
c.deleteFile(file.getName());
}
}
}
} else
deleteFiles(file, c);
}
} catch (Exception e) {
}
}
here is your solution it will also refresh the gallery as well.
In the case where you have multiple variables containing the arguments for a command you're running, and not just a single string, you should not use eval directly, as it will fail in the following case:
function echo_arguments() {
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"
echo "Argument 4: $4"
}
# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"
Result:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg
Note that even though "Some arg" was passed as a single argument, eval
read it as two.
Instead, you can just use the string as the command itself:
# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
"$@";
}
Note the difference between the output of eval
and the new eval_command
function:
eval_command echo_arguments arg1 arg2 "Some arg"
Result:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:
Code bellow allows to play mp3-files and in-memory wave-files too
player.FileName = "123.mp3";
player.Play();
from http://alvas.net/alvas.audio,samples.aspx#sample6 or
Player pl = new Player();
byte[] arr = File.ReadAllBytes(@"in.wav");
pl.Play(arr);
There is no =>
for if.
Use if %energy% GEQ %m2enc%
See if /?
for some other details.
Setting ScrollTop
does give the desired result but the scroll is very abrupt. Using jquery
to have smooth scroll was not an option. So here's a native way to get the job done that supports all major browsers. Reference - caniuse
// get the "Div" inside which you wish to scroll (i.e. the container element)
const El = document.getElementById('xyz');
// Lets say you wish to scroll by 100px,
El.scrollTo({top: 100, behavior: 'smooth'});
// If you wish to scroll until the end of the container
El.scrollTo({top: El.scrollHeight, behavior: 'smooth'});
That's it!
And here's a working snippet for the doubtful -
document.getElementById('btn').addEventListener('click', e => {
e.preventDefault();
// smooth scroll
document.getElementById('container').scrollTo({top: 175, behavior: 'smooth'});
});
_x000D_
/* just some styling for you to ignore */
.scrollContainer {
overflow-y: auto;
max-height: 100px;
position: relative;
border: 1px solid red;
width: 120px;
}
body {
padding: 10px;
}
.box {
margin: 5px;
background-color: yellow;
height: 25px;
display: flex;
align-items: center;
justify-content: center;
}
#goose {
background-color: lime;
}
_x000D_
<!-- Dummy html to be ignored -->
<div id="container" class="scrollContainer">
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div id="goose" class="box">goose</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
</div>
<button id="btn">goose</button>
_x000D_
Update: As you can perceive in the comments, it seems that Element.scrollTo()
is not supported in IE11. So if you don't care about IE11 (you really shouldn't), feel free to use this in all your projects. Note that support exists for Edge! So you're not really leaving your Edge/Windows users behind ;)
The ensure the browser downloads a new version of the favicon and does not use a cached version you can add a dummy parameter to the favicon url:
<link rel="icon" type="image/x-icon" href="favicon.ico?any=param">
That might happen because the pojos you are using lack of the precise constructor the service needs. That is, try to generate all the constructors for the pojo or objects (model object) that your serviceClient uses, so that the client can be instanced correctly. In your case,regenerate the constructors (with arguments)for your client object (taht is your model object).
I wanted to post this answer as an update for users of more recent Android builds (CM11/KitKat/4.4.4). I have not tested any of this with TouchWiz or older Android releases so YMMV.
The following commands can be run in all the usual places (ADB, Terminal Emulator, shell scripts, Tasker).
List all available properties:
getprop
Get WiFi interface:
getprop wifi.interface
WiFi properties:
getprop dhcp.wlan0.dns1
getprop dhcp.wlan0.dns2
getprop dhcp.wlan0.dns3
getprop dhcp.wlan0.dns4
getprop dhcp.wlan0.domain
getprop dhcp.wlan0.gateway
getprop dhcp.wlan0.ipaddress
getprop dhcp.wlan0.mask
The above commands will output information regardless of whether WiFi is actually connected at the time.
Use either of the following to check whether wlan0 is on or not:
ifconfig wlan0
netcfg | awk '{if ($2=="UP" && $3 != "0.0.0.0/0") isup=1} END {if (! isup) exit 1}'
Use either of the following to get the IP address of wlan0 (only if it is connected):
ifconfig wlan0 | awk '{print $3}'
netcfg | awk '/^wlan0/ {sub("(0\\.0\\.0\\.0)?/[0-9]*$", "", $3); print $3}'
Just for thoroughness, to get your public Internet-facing IP address, you're going to want to use an external service. To obtain your public IP:
wget -qO- 'http://ipecho.net/plain'
To obtain your public hostname:
wget -qO- 'http://ifconfig.me/host'
Or to obtain your public hostname directly from your IP address:
(nslookup "$(wget -qO- http://ipecho.net/plain)" | awk '/^Address 1: / { if ($NF != "0.0.0.0") {print $NF; exit}}; /name =/ {sub("\\.$", "", $NF); print $NF; exit}') 2>/dev/null
Note: The aforementioned awk
command seems overly complicated only because is able to handle output from various versions of nslookup
. Android includes a minimal version of nslookup
as part of busybox
but there is a standalone version as well (often included in dnsutils
).
This works for me on both YouTube and Vimeo players. I'm basically just resetting the src attribute, so be aware that the video will go back to the beginning.
var $theSource = $theArticleDiv.find('.views-field-field-video-1 iframe').attr('src');
$theArticleDiv.find('.views-field-field-video-1 iframe').attr('src', $theSource); //reset the video so it stops playing
$theArticleDiv is my current video's container - since I have multiple videos on the page, and they're being exposed via a Drupal view at runtime, I have no idea what their ids are going to be. So I've bound muy click event to a currently visible element, found its parent, and decided that's $theArticleDiv.
('.views-field-field-video-1 iframe') finds the current video's iframe for me - in particular the one that's visible right now. That iframe has a src attribute. I just pick that up and reset it right back to what it already was, and automagically the video stops and goes back to the start. If my users want to pause and resume, they can do it without closing the video, of course - but frankly if they do close the video, I feel they can live with the fact that it's reset to the start.
HTH
I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
As you can see, $rootScope.$broadcast
hits a lot more listeners than $scope.$emit
.
Also, $scope.$emit
's bubbling effect can be cancelled, whereas $rootScope.$broadcast
cannot.
I'm posting this just to cover all possibilities since neither of the other solutions worked for me (they threw errors due angular-bootstrap template dependencies, among others).
While you are developing/debugging a specific template, you can ensure it always refreshes by included a timestamp in the path, like this:
$modal.open({
// TODO: Only while dev/debug. Remove later.
templateUrl: 'core/admin/organizations/modal-selector/modal-selector.html?nd=' + Date.now(),
controller : function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
}
});
Note the final ?nd=' + Date.now()
in the templateUrl
variable.
Copy your Json and paste at textbox on json2csharp and click on Generate button.
A cs class will be generated use that cs file as below
var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);
Where RootObject
is the name of the generated cs file;
To understand why, you need to know that the CPU represents signed numbers using the two's complement (maybe not all, but many).
byte n = 1; //0000 0001 = 1
n = ~n + 1; //1111 1110 + 0000 0001 = 1111 1111 = -1
And also, that the type int and unsigned int can be of different sized depending on your CPU. When doing specific stuff like this:
#include <stdint.h>
int8_t ibyte;
uint8_t ubyte;
int16_t iword;
//......
This only works if the values are in order i.e all the "red" are together and all the "blue" are together etc. assume that your data is in column A starting in A2 - (Don't start from row 1) In the B2 type in 1 In b3 type =if(A2 = A3, B2,B2+1) Drag down the formula until the end of your data All " Red" will be 1 , all "blue" will be 2 all "green" will be 3 etc.
In C2 type in 1, 2 ,3 etc going down the column In D2 = OFFSET($A$1,MATCH(c2,$B$2:$B$x,0),0) - where x is the last cell Drag down, only the unique values will appear. -- put in some error checking
You can also use primefaces <p:spacer width="10" height="10" />
you can do it in two ways using
Serializable
Parcelable.
This examle will show you how to implement it with serializable
class Customer implements Serializable
{
// properties, getter setters & constructor
}
// This is your custom object
Customer customer = new Customer(name, address, zip);
Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);
// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Customer customer = (Customer)extras.getSerializable("customer");
// do something with the customer
}
Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.
Look at this.. This discussion will let you know which is much better way to implement it.
Thanks.
A quick and probably dirty way to do it is described here: https://superuser.com/a/889267. You open the DLL in an editor and check the first characters after the "PE" sequence.
It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break
is up there with the while
), you could create a variable result = None
and loop while it is None
. You should also adjust the variables and you can replace continue
with the semantically perhaps correct pass
(you don't care if an error occurs, you just want to ignore it) and drop the break
- this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except:
clauses are evil for reasons given in the documentation.
Example incorporating all of the above:
result = None
while result is None:
try:
# connect
result = get_data(...)
except:
pass
# other code that uses result but is not involved in getting it
You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.
I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.
The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.
Overall application stages are :
{
fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
if (fileExtension.equalsIgnoreCase("xlsx")) {
workbook = createWorkbook(openOPCPackage(inputSheetFile));
} else {
workbook =
createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
}
sheet = workbook.getSheetAt(0);
}
{
Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();
//skip a header
if (rowIterator.hasNext()) {
rowIterator.next();
}
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
// inserting rows
}
}
Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).
each_with_object
is your friend!
input = [:bla,:blubb,:bleh,:bla,:bleh,:bla,:blubb,:brrr]
# to get the counts of the elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}
=> {:bla=>3, :blubb=>2, :bleh=>2, :brrr=>1}
# to get only the counts of the non-unique elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}.reject{|k,v| v < 2}
=> {:bla=>3, :blubb=>2, :bleh=>2}
You can also send characters that you want to be trimed
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func trim(characterSet:CharacterSet) -> String {
return self.trimmingCharacters(in: characterSet)
}
}
validationMessage = validationMessage.trim(characterSet: CharacterSet(charactersIn: ","))
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
Just use <br/>
. I found myself here looking for the answer to this question and then felt sort of silly for not thinking about using a simple line break as suggested by user JayKilleen in a comment.
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
You can use LiteWare.Configuration library for that. It is very similar to .NET Framework original ConfigurationManager
and works for .NET Core/Standard. Code-wise, you'll end up with something like:
string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");
Disclaimer: I am the author of LiteWare.Configuration.
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
For Bootstrap, you might try this (working on
Firefox
,Chrome
andMicrosoft Edge
) :
body.modal-open {
overflow: hidden;
position:fixed;
width: 100%;
}
Hope this helps...
Another solution (non T-SQL
): you can use tablediff utility.
For example if you want to compare two tables (Localitate
) from two different servers (ROBUH01 & ROBUH02) you can use this shell command:
C:\Program Files\Microsoft SQL Server\100\COM>tablediff -sourceserver ROBUH01 -s
ourcedatabase SIM01 -sourceschema dbo -sourcetable Localitate -destinationserver
ROBUH02 -destinationschema dbo -destinationdatabase SIM02 -destinationtable Lo
calitate
Results:
Microsoft (R) SQL Server Replication Diff Tool Copyright (c) 2008 Microsoft Corporation User-specified agent parameter values:
-sourceserver ROBUH01
-sourcedatabase SIM01
-sourceschema dbo
-sourcetable Localitate
-destinationserver ROBUH02
-destinationschema dbo
-destinationdatabase SIM02
-destinationtable Localitate
Table [SIM01].[dbo].[Localitate] on ROBUH01 and Table [SIM02].[dbo].[Localitate ] on ROBUH02 have 10 differences.
Err Id Dest.
Only 21433 Dest.
Only 21434 Dest.
Only 21435 Dest.
Only 21436 Dest.
Only 21437 Dest.
Only 21438 Dest.
Only 21439 Dest.
Only 21441 Dest.
Only 21442 Dest.
Only 21443
The requested operation took 9,9472657 seconds.
------------------------------------------------------------------------
Using subprocess.run
import subprocess
ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
processNames = subprocess.run(['grep', 'process_name'],
input=ps.stdout, capture_output=True)
print(processNames.stdout)
React + TypeScript inline util method:
const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;
In Java, you can escape quotes with \
:
String value = " \"ROM\" ";
You could open Messages or Event Log tool window to see your log. In addition to that if you want to see device log then you could open Logcat tool window to view your log : View > Tool Windows > Logcat
Starting with
img_data = b'iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQVR42uzBAQEAAACAkP6v7ggK\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAIcAeHkAAeLqlDIAAAAASUVORK5CYII='
Decoded the data using the base64 codec, and then write it to the filesystem.
# In Python 2.7
fh = open("imageToSave.png", "wb")
fh.write(img_data.decode('base64'))
fh.close()
# or, more concisely using with statement
with open("imageToSave.png", "wb") as fh:
fh.write(img_data.decode('base64'))
Modernizing this example to Python 3, which removed arbitrary codec support from string/bytes .encode()
and .decode()
functions:
# For both Python 2.7 and Python 3.x
import base64
with open("imageToSave.png", "wb") as fh:
fh.write(base64.decodebytes(img_data))
A solution without using "eval":
var setInnerHtml = function(elm, html) {
elm.innerHTML = html;
var scripts = elm.getElementsByTagName("script");
// If we don't clone the results then "scripts"
// will actually update live as we insert the new
// tags, and we'll get caught in an endless loop
var scriptsClone = [];
for (var i = 0; i < scripts.length; i++) {
scriptsClone.push(scripts[i]);
}
for (var i = 0; i < scriptsClone.length; i++) {
var currentScript = scriptsClone[i];
var s = document.createElement("script");
// Copy all the attributes from the original script
for (var j = 0; j < currentScript.attributes.length; j++) {
var a = currentScript.attributes[j];
s.setAttribute(a.name, a.value);
}
s.appendChild(document.createTextNode(currentScript.innerHTML));
currentScript.parentNode.replaceChild(s, currentScript);
}
}
This essentially clones the script tag and then replaces the blocked script tag with the newly generated one, thus allowing execution.
If you are using read only input field, you can use ng-value with filter.
for example:
ng-value="price | number:8"
If you look at the bootstrap-button.js source, you'll see that the bootstrap plugin replaces the buttons inner html with whatever is in data-loading-text when calling $(myElem).button('loading')
.
For your case, I think you should just be able to do this:
<button type="button"
class="btn btn-primary start"
id="btnStartUploads"
data-loading-text="<i class='icon-spinner icon-spin icon-large'></i> @Localization.Uploading">
<i class="icon-upload icon-large"></i>
<span>@Localization.StartUpload</span>
</button>
I'd use STUFF
to insert dividing chars and then use CONVERT
with the appropriate style. Something like this:
DECLARE @dt VARCHAR(100)='111290';
SELECT CONVERT(DATETIME,STUFF(STUFF(@dt,3,0,'/'),6,0,'/'),3)
First you use two times STUFF
to get 11/12/90 instead of 111290, than you use the 3 to convert this to datetime
(or any other fitting format: use .
for german, -
for british...) More details on CAST and CONVERT
Best was, to store date and time values properly.
yyyyMMdd
yyyy-MM-dd
or yyyy-MM-ddThh:mm:ss
More details on ISO8601Any culture specific format will lead into troubles sooner or later...
You can declare multiple type variables on a type or method. For example, using type parameters on the method:
<P, Q> int f(Set<P>, Set<Q>) {
return 0;
}
Extract single value from JSON response Python
Try this
import json
import sys
#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
#print the resp
print (resp)
#extract an element in the response
print (resp['test1'])
Just add .pack
between the name and the extension in the <script>
tag in src.
i.e.:
<script src="name.pack.js">
// code here
</script>
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.
The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.
I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.
CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN
(
SELECT tenant.ID AS TenantID,
SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTenant tenant
LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
)
Now to use that function, in your SQL...
SELECT t.TenantName,
t.CarPlateNumber,
t.CarColor,
t.Sex,
t.SSNO,
t.Phone,
t.Memo,
u.UnitNumber,
p.PropertyName
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
LEFT JOIN dbo.fnMyFunc() AS a
ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber
If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY
or CROSS OUTER APPLY
.
Read up on that here.
Cheers
Back when I worked at Twitter, I wrote a utility for calculating deep object size. It takes into account different memory models (32-bit, compressed oops, 64-bit), padding, subclass padding, works correctly on circular data structures and arrays. You can just compile this one .java file; it has no external dependencies:
Yes, you can. Go to Tools > Designers > Table and Designers and uncheck "Prevent Saving Changes That Prevent Table Recreation".
I'm using UAParser https://github.com/faisalman/ua-parser-js
var a = new UAParser();
var name = a.getResult().browser.name;
var version = a.getResult().browser.version;
Only MyISAM allows for FULLTEXT, as seen here.
Try this:
CREATE TABLE gamemech_chat (
id bigint(20) unsigned NOT NULL auto_increment,
from_userid varchar(50) NOT NULL default '0',
to_userid varchar(50) NOT NULL default '0',
text text NOT NULL,
systemtext text NOT NULL,
timestamp datetime NOT NULL default '0000-00-00 00:00:00',
chatroom bigint(20) NOT NULL default '0',
PRIMARY KEY (id),
KEY from_userid (from_userid),
FULLTEXT KEY from_userid_2 (from_userid),
KEY chatroom (chatroom),
KEY timestamp (timestamp)
) ENGINE=MyISAM;
In addition to the example given in the Advanced Bash Scripting Guide referenced by Jefromi, these examples show how pipes create subshells:
$ echo $$ $BASHPID | cat -
11656 31528
$ echo $$ $BASHPID
11656 11656
$ echo $$ | while read line; do echo $line $$ $BASHPID; done
11656 11656 31497
$ while read line; do echo $line $$ $BASHPID; done <<< $$
11656 11656 11656
Yes, the SSL connection is between the TCP layer and the HTTP layer. The client and server first establish a secure encrypted TCP connection (via the SSL/TLS protocol) and then the client will send the HTTP request (GET, POST, DELETE...) over that encrypted TCP connection.
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
ul {_x000D_
list-style-type: none;_x000D_
padding-left: 0px;_x000D_
}_x000D_
_x000D_
ul li span {_x000D_
float: left;_x000D_
width: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li><span></span> The lazy dog.</li>_x000D_
<li><span>AND</span> The lazy cat.</li>_x000D_
<li><span>OR</span> The active goldfish.</li>_x000D_
</ul>
_x000D_
Like Eoin said, you need to put a non-breaking space into your "empty" spans, but you can't assign a width to an inline element, only padding/margin so you'll need to make it float so that you can give it a width.
For a jsfiddle example, see http://jsfiddle.net/laurensrietveld/JZ2Lg/
var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push ( {"cool":"34.39","also cool":"45459"} );
Your variable is a javascript object {}
not an array []
.
You could do:
var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
and
var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
Later, you add those objects to your array: array.push (o, o2);
Also JSON
is simply a string representation of a javascript object, thus:
var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again
Java 8 added a new API for working with dates and times. With Java 8 you can use
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
Instant.now()
returns an Instant that represents the current system time. With getEpochSecond()
you get the epoch seconds (unix time) from the Instant
.
I found this;
from here;
vba- Can a combobox present more then one column on it's textbox part?
and this may help;
I added a sort of demo here;
Check your runtime tag inside the web.config, and verify you have something like this declared:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
.....
</runtime>
Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.
What this looks like:
private static someClass[] arr = new someClass[someNum];
and
public class someClass {
private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;
...
}
you can check length of items
ng-show="items.length"
Also, if you are using TortoiseSVN, just export to the current working copy location and it will remove the .svn folders and files.
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-export.html#tsvn-dug-export-unversion
Updated Answer for Subversion 1.7:
In Subversion 1.7 the working copy has been revised extensively. There is only one .svn folder, located in the base of the working copy. If you are using 1.7, then just deleting the .svn folder and its contents is an easy solution (regardless of using TortoiseSVN or command line tools).
In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".
this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "Icons/Freq.png", UriKind.Absolute));
I also made a function if anybody would like it...
/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute));
}
Usage:
this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");
PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.
Here is an excerpt from the PHP website:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
The above code will output:
Unquoted string: Nice
Quoted string: 'Nice'
You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:
List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
if(a.getXXX().equalsIgnoreCase("AAA")){
toRemove.add(a);
}
}
list.removeAll(toRemove);
If you want to convert back the file formats which have been changed to UNIX Format from PC format.
(1)You need to reinstall tortoise GIT and in the "Line Ending Conversion" Section make sure that you have selected "Check out as is - Check in as is"option.
(2)and keep the remaining configurations as it is.
(3)once installation is done
(4)write all the file extensions which are converted to UNIX format into a text file (extensions.txt).
ex:*.dsp
*.dsw
(5) copy the file into your clone Run the following command in GITBASH
while read -r a;
do
find . -type f -name "$a" -exec dos2unix {} \;
done<extension.txt
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block
, so when one is pushed down the hole line is pushed down with him. Float fixes this:
#header button {
float:left;
}
Here's a working jsfidle.
I would use:
if (Stream.of("a","b","c").anyMatch("a"::equals)) {
//Code to execute
};
or:
Stream.of("a","b","c")
.filter("a"::equals)
.findAny()
.ifPresent(ignore -> /*Code to execute*/);
Do not use Mockito.anyXXXX(). Directly pass the value to the method parameter of same type. Example:
A expected = new A(10);
String firstId = "10w";
String secondId = "20s";
String product = "Test";
String type = "type2";
Mockito.when(service.getTestData(firstId, secondId, product,type)).thenReturn(expected);
public class A{
int a ;
public A(int a) {
this.a = a;
}
}
I saw a nested function technique for computing a weighted average on S.O. one time, altering that technique can solve your issue.
def group_weight(overall_size):
def inner(group):
return len(group)/float(overall_size)
inner.__name__ = 'weight'
return inner
d = {"my_label": pd.Series(['A','B','A','C','D','D','E'])}
df = pd.DataFrame(d)
print df.groupby('my_label').apply(group_weight(len(df)))
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
dtype: float64
Here is how to do a weighted average within groups
def wavg(val_col_name,wt_col_name):
def inner(group):
return (group[val_col_name] * group[wt_col_name]).sum() / group[wt_col_name].sum()
inner.__name__ = 'wgt_avg'
return inner
d = {"P": pd.Series(['A','B','A','C','D','D','E'])
,"Q": pd.Series([1,2,3,4,5,6,7])
,"R": pd.Series([0.1,0.2,0.3,0.4,0.5,0.6,0.7])
}
df = pd.DataFrame(d)
print df.groupby('P').apply(wavg('Q','R'))
P
A 2.500000
B 2.000000
C 4.000000
D 5.545455
E 7.000000
dtype: float64
protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// To check condition on integer value
if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
{
e.Row.BackColor = System.Drawing.Color.Cyan;
}
}
you are having the FindOpenSSL.cmake file in the cmake module(path usr/shared.cmake-3.5/modules) # Search OpenSSL
find_package(OpenSSL REQUIRED)
if( OpenSSL_FOUND )
include_directories(${OPENSSL_INCLUDE_DIRS})
link_directories(${OPENSSL_LIBRARIES})
message(STATUS "Using OpenSSL ${OPENSSL_VERSION}")
target_link_libraries(project_name /path/of/libssl.so /path/of/libcrypto.so)
The simplest, most robust way is to use the internal ._trigger() to fire the autocomplete change event.
$("#CompanyList").autocomplete({
source : yourSource,
change : yourChangeHandler
})
$("#CompanyList").data("ui-autocomplete")._trigger("change");
Note, jQuery UI 1.9 changed from .data("autocomplete") to .data("ui-autocomplete"). You may also see some people using .data("uiAutocomplete") which indeed works in 1.9 and 1.10, but "ui-autocomplete" is the official preferred form. See http://jqueryui.com/upgrade-guide/1.9/#changed-naming-convention-for-data-keys for jQuery UI namespaecing on data keys.
well here is common usage of getter setter in actual use case,
public class OrderItem
{
public int Id {get;set;}
public int quantity {get;set;}
public int Price {get;set;}
public int TotalAmount {get {return this.quantity *this.Price;}set;}
}
wrap all the script between this...
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
});
</script>
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.
Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:
Sub find()
Dim i As Integer
Dim firstTime As Integer
Dim bNotFound As Boolean
i = 1
bNotFound = True
Do While bNotFound
If Cells(i, 2).Value = "ProjTemp" Then
firstTime = i
bNotFound = false
End If
i = i + 1
Loop
End Sub
trunc(my_date,'DD')
will give you just the date and not the time in Oracle.
Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.
In different terms, your d
and your e
would be exactly equivalent dictionaries.
What you can do here is to use an OrderedDict
:
from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
key=lambda kv: kv[1]['key3'], reverse=True))
The original d
has some arbitrary order. d_ascending
has the order you thought you had in your original d
, but didn't. And d_descending
has the order you want for your e
.
If you don't really need to use e
as a dictionary, but you just want to be able to iterate over the elements of d
in a particular order, you can simplify this:
for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
do_something_with(key, value)
If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict
, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict
that re-sorts itself as necessary, etc.
In a couple of experiments in my masters thesis (e.g. page 59), I found that the bias might be important for the first layer(s), but especially at the fully connected layers at the end it seems not to play a big role.
This might be highly dependent on the network architecture / dataset.