date stringlengths 10 10 | nb_tokens int64 60 629k | text_size int64 234 1.02M | content stringlengths 234 1.02M |
|---|---|---|---|
2018/03/15 | 424 | 1,143 | <issue_start>username_0: I'm having problem when getting the exact number of days. Given I have date/time which consider hours in counting number of days below the code give me zero days
```
$fisrstDate = new DateTime("2018-03-07 04:46:00");
$secondDate = new DateTime("2018-03-07 11:10:00");
$days=$fisrstDate->diff($secondDate)->days;
```
another example is this it should give me 2 days but shows only 1 days my idea is when 24 hours exceed I want to add another 1 days so that it would give me an output of 2 days
```
$fisrstDate = new DateTime("2018-03-07 04:46:00");
$secondDate = new DateTime("2018-03-08 05:00:00");
$days=$fisrstDate->diff($secondDate)->days;
```<issue_comment>username_1: You can use `strtotime` to get the exact seconds between two time stamps and then convert it to days followed by `ceil` to make it work. Eg:
```
$fisrstDate = strtotime("2018-03-07 04:46:00");
$secondDate = strtotime("2018-03-07 11:10:00");
$days = abs(ceil((abs($fisrstDate - $secondDate)/ (60 * 60 * 24)) - (1 / 24)));
echo $days;
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Isn't it just `date2 - date1 + 1`?
Upvotes: 0 |
2018/03/15 | 439 | 1,514 | <issue_start>username_0: Consider I have a string like this, and I want to append html tags before and after a specific keyword in the string.
```
let name = "<NAME>";
let keyword = "geo";
```
After appending the html tags, i want to get result like this,
```
**Geo**rge William
```
I tried something like this,
```
name.replace(new RegExp(keyword, 'gi'), "**"+keyword+"**");
```
But it results like this,
```
**geo**rge William
```
How can i get the result with exact "case" in the original name?<issue_comment>username_1: This isn't the prettiest code I have ever written, but it doesn't use Regular Expressions and it does work for ignoring the case, while making this a re-usable function that doesn't have to be tied to the tag specifically.
```js
let name = "<NAME>";
let keyword = "geo";
const newHtml = (str, key, tagName) => {
return str.toLowerCase()
.split(key.toLowerCase())
.map((val) => {
if (val !== '') {
return val;
}
else {
let idx = str.toLowerCase().indexOf(key.toLowerCase());
return `<${tagName}>${str.split('').slice(idx, key.length).join('')}`;
}
})
.join('');
};
console.log(newHtml(name, keyword, 'strong'));
```
Upvotes: 2 <issue_comment>username_2: You can refer to the matched substring in your result using `$&`
```js
let name = '<NAME>';
let keyword = 'geo';
console.log(name.replace(new RegExp(keyword, 'gi'), '**$&**'));
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 754 | 2,394 | <issue_start>username_0: I want to check each values from my array if it matches the string,
however it doesn't work when i'm using `console.log(/^reg_arr[i]/.test(str1));`
but when I use `console.log(/^table/.test(str1));` it works
```js
var str1 = 'table football';
var reg_arr = ["table","football"];
for(var i = 0, reg_arr_length = reg_arr.length; i < reg_arr_length; i++)
{
console.log(/^reg_arr[i]/.test(str1)); /* doesnt work */
}
console.log(/^table/.test(str1)); /* this works */
```
Is there a problem with my syntax,
Thank you,<issue_comment>username_1: Use `new RegExp(source: string[, flags: string])` (simply `RegExp(source: string[, flags: string])` is also working)
```js
var str1 = 'table football';
var reg_arr = ["table","football"];
for(var i = 0, reg_arr_length = reg_arr.length; i < reg_arr_length; i++)
{
console.log(new RegExp(`^${reg_arr[i]}`).test(str1));
}
```
Upvotes: 1 <issue_comment>username_2: Using slashes to define a regular expression doesn't allow you to enter variables into the regular expression, that is, in the following example, `str1` is checked to contain `"test"`, not the value of the variable test.
```
var str1 = "hello";
var str2 = "Hello world";
console.log(/str1/i.test(str2))
```
To solve this issue, you need to create a new regular expression for each value in the array, something that can be done with `new RegExp(str)`, instead of slashes.
```
var str1 = "hello";
var str2 = "hello world";
console.log(new RegExp(str1, "i").test(str2))
```
However, this method has a catch, characters from that string are not escaped. So `new RegExp("test.hello")` will match `"test hello"`, because the dot is interpreted as a regular expression wildcard character and not a period. To fix that, we first have to manually escape any special characters in our search string (unless the things `reg_arr` are actually regular expressions). I took the code to do that from the middle of [this MDN page.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressionss)
```
var str1 = "hello"
var str2 = "hello world"
str1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
console.log(new RegExp(str, "i").test(str2))
```
So without changing anything else, your final `console.log` could look like this:
```
console.log(new RegExp(reg_arr[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).test(str1));
```
Upvotes: 0 |
2018/03/15 | 825 | 2,975 | <issue_start>username_0: I am working on my small project in which I have a situation in which, we need to show report like below:
```
gender gender_count rejected selected
Male 230 50 180
Female 150 20 130
```
All values in above report(excluding gender column) are count from table.
Table structure is given below:
```
user_id gender status
1 male selected
2 male selected
3 female rejected
4 female selected
5 male rejected
```
I am not able to write query for this kind of report. I was using group by to count gender. but how can I count gender by status and then make them as column.
Please help me on this. Thanks in advance.<issue_comment>username_1: ```
SELECT
GENDER, COUNT(*) GENDER_COUNT,
SUM(IF(STATUS='REJECTED',1,0)) REJECTED,
SUM(IF(STATUS='SELECTED',1,0)) SELECTED
FROM
TABLE
GROUP BY GENDER
```
Other DBs you would need to use `CASE` instead of `IF`
(I am not a MySQL expert but this should point you in the right way)
Upvotes: 1 <issue_comment>username_2: Try this:
```
SELECT gender, COUNT(*) gender_count, SUM(status='rejected') rejected,
SUM(status='selected') selected
FROM yourTable
GROUP BY gender;
```
Upvotes: 0 <issue_comment>username_3: I've checked through SQLfiddle and the link is provided below you can check it...
<http://sqlfiddle.com/#!9/822019/3>
```
CREATE TABLE table1 (
user_id int,
gender varchar(255),
status varchar(255)
);
INSERT INTO table1 VALUES (1,"male","selected"),
(2,"male","selected"),
(3,"female","rejected"),
(4,"female","selected"),
(5,"male","rejected");
SELECT
gender, COUNT(*) GENDER_COUNT,
SUM(IF(STATUS='REJECTED',1,0)) REJECTED,
SUM(IF(STATUS='SELECTED',1,0)) SELECTED
FROM
table1
GROUP BY gender
```
Upvotes: 0 <issue_comment>username_4: for your case
```
mysql> select * from genderlist;
+---------+--------+--------+
| user_id | gender | status |
+---------+--------+--------+
| 1 | male | select |
| 2 | female | select |
| 3 | female | reject |
| 4 | female | reject |
| 5 | male | reject |
| 6 | male | select |
+---------+--------+--------+
```
try the below query
>
> SELECT gender,count(\*) as gendercount,sum(status='select') as 'selected',sum(status='reject') as reject from genderlist group by gender;
>
>
>
output will be
```
mysql> SELECT gender,count(*) as gendercount,sum(status='select') as 'selected',sum(status='reject') as reject from genderlist group by gender;
+--------+-------------+----------+--------+
| gender | gendercount | selected | reject |
+--------+-------------+----------+--------+
| female | 3 | 1 | 2 |
| male | 3 | 2 | 1 |
+--------+-------------+----------+--------+
```
Upvotes: 0 |
2018/03/15 | 5,241 | 12,598 | <issue_start>username_0: I have homework where I have to create a C program which sorts 5 numbers from smallest to largest. I know how to easily program this using functions and `if` statements (using `>=` and `<=`).
However, the catch is I am only allowed to use `printf` and `scanf`, so I have to calculate all the `>=` and `<=` inside the `printf`. And I'm not allowed to use the ternary operator.
I've been trying to a long time. So I tried to sort just 3 numbers, I still can't even get past sorting the smallest number. It just keeps printing `1`.
```
// This printf is just trying to figure out the smallest number from 3 numbers provided but it keeps printing 1.
printf("The ascending order of the numbers are: %d ",
(
(num1 <= num2 && num1 <= num3) || // Checking if num1 is the smallest
(num2 <= num1 && num2 <= num3) || // Checking if num2 is the smallest
(num3 <= num2 && num3 <= num1) // Checking if num3 is the smallest
));
```
One possible solution I have come up with is adding the `((num1 + num2 + num3) -1)` because if one of the statements is true (for example if `num2` is the smallest, it would print `1` because `1` means true). If it is false it prints `0`. So I could technically add the statement which is true then `-1`. So if `num2`'s statement is true, I could do `+ num2 - 1`.<issue_comment>username_1: ### Pass 1: Minimum of three distinct values
Note that if a condition evaluates to false, the result is `0`; if true, `1`. So you can use a trick (as long as multiplication and addition aren't verboten too) — for three distinct values as shown in the question:
```
printf("The smallest number is: %d ",
(num1 * (num1 <= num2 && num1 <= num3) +
num2 * (num2 <= num1 && num2 <= num3) +
num3 * (num3 <= num1 && num3 <= num2)));
```
There will be trouble if two values are the same and are also the smaller value.
### Pass 2: Minimum of five distinct values
If you need to process 5 values, it is (as noted in a comment) more tedious than difficult.
```
printf("The smallest number is: %d ",
(num1 * (num1 <= num2 && num1 <= num3 && num1 <= num4 && num1 <= num5) +
num2 * (num2 <= num1 && num2 <= num3 && num2 <= num4 && num2 <= num5) +
num3 * (num3 <= num1 && num3 <= num2 && num3 <= num4 && num3 <= num5) +
num4 * (num4 <= num1 && num4 <= num2 && num4 <= num3 && num4 <= num5) +
num5 * (num5 <= num1 && num5 <= num2 && num5 <= num3 && num5 <= num4)));
```
This is just for finding the minimum; working it for each of the other cases quickly becomes preposterous. Indeed, the whole exercise is fairly silly, but it is also fairly typical of some courses.
### Pass 3: Minimum of three values not necessarily distinct
After a bit of cogitation, I think you can deal with 2 or 3 numbers the same with this (which is basically what [user3386109](https://stackoverflow.com/users/3386109/user3386109) said in a [comment](https://stackoverflow.com/questions/49290953/how-do-i-make-conditions-in-printf-statements/49291191#comment85585542_49290953)).
```
#include
static void print\_smallest(int num1, int num2, int num3)
{
printf("The smallest number of (%d, %d, %d) is %d\n",
num1, num2, num3,
(num1 \* (num1 <= num2 && num1 <= num3) +
num2 \* (num2 < num1 && num2 <= num3) +
num3 \* (num3 < num1 && num3 < num2)));
}
int main(void)
{
for (int i = 1; i < 4; i++)
{
for (int j = 1; j < 4; j++)
{
for (int k = 1; k < 4; k++)
print\_smallest(i, j, k);
}
}
return 0;
}
```
Output:
```
The smallest number of (1, 1, 1) is 1
The smallest number of (1, 1, 2) is 1
The smallest number of (1, 1, 3) is 1
The smallest number of (1, 2, 1) is 1
The smallest number of (1, 2, 2) is 1
The smallest number of (1, 2, 3) is 1
The smallest number of (1, 3, 1) is 1
The smallest number of (1, 3, 2) is 1
The smallest number of (1, 3, 3) is 1
The smallest number of (2, 1, 1) is 1
The smallest number of (2, 1, 2) is 1
The smallest number of (2, 1, 3) is 1
The smallest number of (2, 2, 1) is 1
The smallest number of (2, 2, 2) is 2
The smallest number of (2, 2, 3) is 2
The smallest number of (2, 3, 1) is 1
The smallest number of (2, 3, 2) is 2
The smallest number of (2, 3, 3) is 2
The smallest number of (3, 1, 1) is 1
The smallest number of (3, 1, 2) is 1
The smallest number of (3, 1, 3) is 1
The smallest number of (3, 2, 1) is 1
The smallest number of (3, 2, 2) is 2
The smallest number of (3, 2, 3) is 2
The smallest number of (3, 3, 1) is 1
The smallest number of (3, 3, 2) is 2
The smallest number of (3, 3, 3) is 3
```
### Pass 4: Sorted order for three values not necessarily distinct
Calculating the maximum instead of the minimum is trivial; simply use `>` in place of `<` throughout.
Calculating the median turns out to be harder. I suspect there is a better way of doing it than this, but at least this works. Note the subtracted term — omit that, and the median value is doubled when the three values are the same.
```
#include
static void print\_smallest(int num1, int num2, int num3)
{
printf("The sorted order of (%2d, %2d, %2d) is (%2d, %2d, %2d)\n",
num1, num2, num3,
(num1 \* (num1 <= num2 && num1 <= num3) + /\* Min1 \*/
num2 \* (num2 < num1 && num2 <= num3) + /\* Min2 \*/
num3 \* (num3 < num1 && num3 < num2)), /\* Min3 \*/
(num1 \* (num1 >= num2 && num1 <= num3) + /\* Med1 \*/
num2 \* (num2 > num1 && num2 <= num3) + /\* Med2 \*/
num3 \* (num3 > num1 && num3 < num2) - /\* Med3 \*/
num1 \* (num1 == num2 && num1 == num3) + /\* Med4 \*/
num1 \* (num1 <= num2 && num1 >= num3) + /\* Med5 \*/
num2 \* (num2 < num1 && num2 >= num3) + /\* Med6 \*/
num3 \* (num3 < num1 && num3 > num2)), /\* Med7 \*/
(num1 \* (num1 >= num2 && num1 >= num3) + /\* Max1 \*/
num2 \* (num2 > num1 && num2 >= num3) + /\* Max2 \*/
num3 \* (num3 > num1 && num3 > num2)) /\* Max3 \*/
);
}
int main(void)
{
int lo = -7; // +1, -2
int hi = +6; // +4, +4
int jp = +6; // +1, +2
for (int i = lo; i < hi; i += jp)
{
for (int j = lo; j < hi; j += jp)
{
for (int k = lo; k < hi; k += jp)
print\_smallest(i, j, k);
}
}
return 0;
}
```
Output:
```
The sorted order of (-7, -7, -7) is (-7, -7, -7)
The sorted order of (-7, -7, -1) is (-7, -7, -1)
The sorted order of (-7, -7, 5) is (-7, -7, 5)
The sorted order of (-7, -1, -7) is (-7, -7, -1)
The sorted order of (-7, -1, -1) is (-7, -1, -1)
The sorted order of (-7, -1, 5) is (-7, -1, 5)
The sorted order of (-7, 5, -7) is (-7, -7, 5)
The sorted order of (-7, 5, -1) is (-7, -1, 5)
The sorted order of (-7, 5, 5) is (-7, 5, 5)
The sorted order of (-1, -7, -7) is (-7, -7, -1)
The sorted order of (-1, -7, -1) is (-7, -1, -1)
The sorted order of (-1, -7, 5) is (-7, -1, 5)
The sorted order of (-1, -1, -7) is (-7, -1, -1)
The sorted order of (-1, -1, -1) is (-1, -1, -1)
The sorted order of (-1, -1, 5) is (-1, -1, 5)
The sorted order of (-1, 5, -7) is (-7, -1, 5)
The sorted order of (-1, 5, -1) is (-1, -1, 5)
The sorted order of (-1, 5, 5) is (-1, 5, 5)
The sorted order of ( 5, -7, -7) is (-7, -7, 5)
The sorted order of ( 5, -7, -1) is (-7, -1, 5)
The sorted order of ( 5, -7, 5) is (-7, 5, 5)
The sorted order of ( 5, -1, -7) is (-7, -1, 5)
The sorted order of ( 5, -1, -1) is (-1, -1, 5)
The sorted order of ( 5, -1, 5) is (-1, 5, 5)
The sorted order of ( 5, 5, -7) is (-7, 5, 5)
The sorted order of ( 5, 5, -1) is (-1, 5, 5)
The sorted order of ( 5, 5, 5) is ( 5, 5, 5)
```
### Pass 5: Sorted order for three values, no loops or function
As before, the code in Pass 4 does a thorough test of all combinations of three numbers in their relative positions. If you're required to read three numbers and then sort them (and you're not allowed to use loops or functions other than `main()`, `scanf()`, `printf()`, so be it — you can transplant the `printf()` statement into your `main()` immediately after you've read three values:
```
#include
int main(void)
{
int num1, num2, num3;
if (scanf("%d%d%d", &num1, &num2, &num3) != 3)
{
fprintf(stderr, "failed to read 3 integers\n");
return 1;
}
printf("The sorted order of (%2d, %2d, %2d) is (%2d, %2d, %2d)\n",
num1, num2, num3,
(num1 \* (num1 <= num2 && num1 <= num3) + /\* Min1 \*/
num2 \* (num2 < num1 && num2 <= num3) + /\* Min2 \*/
num3 \* (num3 < num1 && num3 < num2)), /\* Min3 \*/
(num1 \* (num1 >= num2 && num1 <= num3) + /\* Med1 \*/
num2 \* (num2 > num1 && num2 <= num3) + /\* Med2 \*/
num3 \* (num3 > num1 && num3 < num2) - /\* Med3 \*/
num1 \* (num1 == num2 && num1 == num3) + /\* Med4 \*/
num1 \* (num1 <= num2 && num1 >= num3) + /\* Med5 \*/
num2 \* (num2 < num1 && num2 >= num3) + /\* Med6 \*/
num3 \* (num3 < num1 && num3 > num2)), /\* Med7 \*/
(num1 \* (num1 >= num2 && num1 >= num3) + /\* Max1 \*/
num2 \* (num2 > num1 && num2 >= num3) + /\* Max2 \*/
num3 \* (num3 > num1 && num3 > num2)) /\* Max3 \*/
);
return 0;
}
```
Testing with a random number generator (program name `sort3-53`) yields:
```
$ for i in $(range 0 9); do random -n 3 10 99 | sort3-53; done
The sorted order of (66, 62, 70) is (62, 66, 70)
The sorted order of (43, 99, 23) is (23, 43, 99)
The sorted order of (20, 46, 66) is (20, 46, 66)
The sorted order of (87, 82, 19) is (19, 82, 87)
The sorted order of (63, 29, 62) is (29, 62, 63)
The sorted order of (40, 66, 15) is (15, 40, 66)
The sorted order of (17, 13, 58) is (13, 17, 58)
The sorted order of (84, 50, 11) is (11, 50, 84)
The sorted order of (60, 86, 54) is (54, 60, 86)
The sorted order of (37, 33, 96) is (33, 37, 96)
$
```
You can probably use `seq` where I use `range`. I'm not sure there's a standard PRNG program analogous to the `random` I use (and wrote). The invocation shown generates 3 random numbers between 10 and 99 inclusive.
### How it should be done?
The whole process here is preposterous — but that's because of the conditions placed on the techniques that can be used. If you need to sort three or more numbers, put them in an array, sort the array, and print the array. Failing that, you should swap the values to find the sorted order; it would dramatically reduce the number of comparisons needed, and there'd be no multiplications.
Upvotes: 3 <issue_comment>username_2: If you are allowed to use `int` which I presume you do (how else could you store the user input) why not use a precomputed table with the correct sorting?
```
#include
int map[2][2] = {
{1, 0},
{0, 1}
};
int main() {
int n[2] = {7, 5};
int tmp = n[0] >= n[1];
printf("1.) %d\n", n[map[tmp][0]]);
printf("2.) %d\n", n[map[tmp][1]]);
}
```
**UPDATE**: This seems to work for three numbers:
```
#include
int map[2][2][2][3] = {
{
{
{2, 1, 0},
{1, 2, 0}
},
{
{2, 0, 1},
{0, 1, 0}
}
},
{
{
{0, 0, 0},
{1, 0, 2}
},
{
{0, 2, 1},
{0, 1, 2}
}
}
};
int main() {
int n[3] = {30, 59, 100};
int tmp1 = n[0] > n[2];
int tmp2 = n[0] > n[1];
int tmp3 = n[1] > n[2];
printf("1.) %d\n", n[map[tmp1][tmp2][tmp3][0]]);
printf("2.) %d\n", n[map[tmp1][tmp2][tmp3][1]]);
printf("3.) %d\n", n[map[tmp1][tmp2][tmp3][2]]);
}
```
Upvotes: 0 <issue_comment>username_3: Here is a simple solution that can be easily adapted for any number of values:
```
#include
int main() {
int n[5], o[5], s[5];
while (scanf("%d%d%d%d%d", &n[0], &n[1], &n[2], &n[3], &n[4]) == 5) {
o[0] = (n[0] > n[1]) + (n[0] > n[2]) + (n[0] > n[3]) + (n[0] > n[4]);
o[1] = (n[1] >= n[0]) + (n[1] > n[2]) + (n[1] > n[3]) + (n[1] > n[4]);
o[2] = (n[2] >= n[0]) + (n[2] >= n[1]) + (n[2] > n[3]) + (n[2] > n[4]);
o[3] = (n[3] >= n[0]) + (n[3] >= n[1]) + (n[3] >= n[2]) + (n[3] > n[4]);
o[4] = (n[4] >= n[0]) + (n[4] >= n[1]) + (n[4] >= n[2]) + (n[4] >= n[3]);
s[o[0]] = n[0];
s[o[1]] = n[1];
s[o[2]] = n[2];
s[o[3]] = n[3];
s[o[4]] = n[4];
printf("%d %d %d %d %d\n", s[0], s[1], s[2], s[3], s[4]);
}
return 0;
}
```
Note that `while` is only used to repeat the input / sort / output phase. You can get rid of it if no `if` or `while` statement is allowed, but then I do not know how to test for successful `scanf()` conversion, yet undefined behavior can be avoided via initialization:
```
#include
int main() {
int n0, n1, n2, n3, n4, s[5];
n0 = n1 = n2 = n3 = n4 = 0;
scanf("%d%d%d%d%d", &n0, &n1, &n2, &n3, &n4);
s[(n0 > n1) + (n0 > n2) + (n0 > n3) + (n0 > n4)] = n0;
s[(n1 >= n0) + (n1 > n2) + (n1 > n3) + (n1 > n4)] = n1;
s[(n2 >= n0) + (n2 >= n1) + (n2 > n3) + (n2 > n4)] = n2;
s[(n3 >= n0) + (n3 >= n1) + (n3 >= n2) + (n3 > n4)] = n3;
s[(n4 >= n0) + (n4 >= n1) + (n4 >= n2) + (n4 >= n3)] = n4;
printf("%d %d %d %d %d\n", s[0], s[1], s[2], s[3], s[4]);
return 0;
}
```
Upvotes: 2 |
2018/03/15 | 768 | 2,412 | <issue_start>username_0: I almost have this answer. I want to match everything following a colon and a space.
So if I have these lines
```none
What is your name: Alain
What is your major: Computer Science
```
I would like to capture `"Alain"` and `"Computer Science"`.
I have this regex
```
(?<=:)\s*\w*
```
That captures a white space followed by my name and it captures `" Alain"` and `" Computer"`. How can I get rid of the leading white space?
Thank you!<issue_comment>username_1: There might be less verbose ways of doing this, however this works
```
(?<=What is your name: )(.*)(?= What is your major:)|(?<=What is your major: )(.*)
```
**Update**
Since its multi line (courtesy of Ben Voigt) with the added word boundary
```
(?<=:\s*)\b.*$
```
**Example**
```
var pattern = @"(?<=:\s*)\b.*$";
var input = "What is your name: Alain \r\nWhat is your major: Computer Science";
var matches = Regex.Matches(input, pattern, RegexOptions.Multiline);
foreach (var match in matches)
{
Console.WriteLine(match);
}
```
[**You can test it here**](https://dotnetfiddle.net/KcJdmC)
Upvotes: 0 <issue_comment>username_2: Perhaps you could use [Regex.Split](https://msdn.microsoft.com/en-us/library/8yttk7sy(v=vs.110).aspx) and split by a colon and zero or more whitespaces [`:\s*`](http://regexstorm.net/tester?p=%3a%5cs*&i=What+is+your+name%3a+Alain%0d%0aWhat+is+your+major%3a+Computer+Science)
```
string[] lines = { "What is your name: Alain" , "What is your major: Computer Science " };
string pattern = @":\s*";
foreach (string str in lines)
{
Console.WriteLine(Regex.Split(str, pattern)[1]);
}
```
[Demo](http://rextester.com/TXT80367)
Upvotes: 0 <issue_comment>username_3: ```
: (.*)
```
See the [demo](https://regex101.com/r/hafrKL/1)
(This regex is implementation agnostic, and should work with any regex library)
If you are using a capture group, this will capture the contents you are looking for, but will match the colon and space.
Upvotes: 2 <issue_comment>username_4: You can use split as suggested above. But if you really have to use Regex, the following works on your string.
```
string line1 = "What is your name: Alain";
Regex rgex = new Regex(@"(?<=:\s)(.*)", RegexOptions.Compiled);
Match match = rgex.Match(line1);
if (match.Success)
{
Console.WriteLine("Name= " + match.Value);
}
Console.ReadKey();
```
Upvotes: 1 |
2018/03/15 | 909 | 2,242 | <issue_start>username_0: I have two dicts , and I want compare the key first and value second with input 2 :
exampal like key ope1 compare with second input and output a tuple ('x','1) as key in the out put
we come to the value 'y' and 'z' compare them to second list which shown y --> 2 and z--> 4 and produce a list of tuple [(‘y’-‘2’), (‘z’,‘4’)]
as shown in the example
```
input1 = {'x':['y','z'], 'w':['m','n']}
input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
#output = {('x','1'):[('y','2'),('z','4')], ('w','3'): [('m','100'),('n','200')]}
```<issue_comment>username_1: One approach is to iterate over your input1 dictionary and form the required output.
**Demo**
```
input1 = {'x':['y','z'], 'w':['m','n']}
input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
d = {}
for k,v in input1.items(): #iterate over input1
d[(k, input2[k])] = [] #Create key and list as value.
for i in v:
d[(k, input2[k])].append((i, input2[i]))
print(d)
```
**Output:**
```
{('x', '1'): [('y', '2'), ('z', '4')], ('w', '3'): [('m', '100'), ('n', '200')]}
```
Upvotes: 0 <issue_comment>username_2: You can use a dictionary comprehension for this:
```
i1 = {'x':['y','z'], 'w':['m','n']}
i2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
d = {(k, i2[k]): [(i, i2[i]) for i in v] for k, v in i1.items()}
# {('w', '3'): [('m', '100'), ('n', '200')],
# ('x', '1'): [('y', '2'), ('z', '4')]}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: There are many ways to achieve this :
```
input1 = {'x':['y','z'], 'w':['m','n']}
input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
```
with defaultdict in one line
```
import collections
d=collections.defaultdict(list)
[d[(i,input2[i])].append((m,input2[m])) for i,j in input1.items() for m in j]
```
without any import :
```
new_dict={}
for i,j in input1.items():
for m in j:
if (i,input2[i]) not in new_dict:
new_dict[(i,input2[i])]=[(m,input2[m])]
else:
new_dict[(i, input2[i])].append((m,input2[m]))
print(new_dict)
```
output:
```
{('w', '3'): [('m', '100'), ('n', '200')], ('x', '1'): [('y', '2'), ('z', '4')]}
```
Upvotes: 0 |
2018/03/15 | 607 | 2,334 | <issue_start>username_0: As we know C/C++ has macro function to do text replacement, here is an example:
```
#include
#include
using namespace std;
#define FIRST\_NAME Print("Moon")
#define FAMILY\_NAME Print("Sun")
string Print(string name)
{
cout << name << endl;
return name;
}
int main()
{
string name = FIRST\_NAME + FAMILY\_NAME;
return 0;
}
```
As you can see the `FIRST_NAME` and `FAMILY_NAME` are macros which will be replaced by the function `Print()`.
My question is does Python have a similar feature? Or what can I do to create this kind of feature?<issue_comment>username_1: Already in C++ using macros is not considered a good practice. You can get the same performance, and better compiler checking, using functions or templates. These have less risk of repeating side effects, or breaking bugs because of multi-statement macros.
Therefore, a remaining legitimate use for macros, especially in C++, is metaprogramming. e.g The boost preprocessor library.
In python, there are no hard types, only duck types. (If it quacks like a duck, it's enough). It is a dynamic language (versus static), and reduces, if not completely eliminates, the need for macros.
Python has a taste (a philosophy), and it is called being "pythonic". Macros are not pythonic. Just don't use them.
In your case, make functions.
Upvotes: 2 <issue_comment>username_2: Yes, python has a similar feature, assignment
```
def MyPrint(name):
print(name)
return name
FIRST_NAME = MyPrint("Moon")
FAMILY_NAME = MyPrint("Sun")
```
Note that C++ also has this feature.
Upvotes: -1 <issue_comment>username_3: In Python you can pretty much do achieve *almost* anything you want with its metaclasses (custom behavior of common Python operations on objects), runtime reflection and runtime evaluation.
On the other hand, such an approach is discouraged unless you really need it because it balloons complexity and kills your ability to "statically" understand the code. That is, do not use them unless you are doing things like:
* Dynamic code generation
* Designing a Python-based DSL
* Some kind of framework that needs a bit of magic to look best for users
There is also the possibility of applying any sort of preprocessor to your Python source code, of course, including C's, and including a Python script too.
Upvotes: 0 |
2018/03/15 | 360 | 1,067 | <issue_start>username_0: I am attempting to iterate over a string to check for punctuation. I've tried to use ispunct() but am receiving an error that there is no matching fucntion for call to ispunct. Is there a better way to implement this?
```
for(std::string::iterator it = oneWord.begin(); it != oneWord.end(); it++)
{
if(ispunct(it))
{
}
}
```<issue_comment>username_1: `it` is an iterator; it points to a character in a string. You have to dereference it to get the thing it points to.
```
if(ispunct(static_cast(\*it)))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> Is there a better way to implement this?
>
>
>
Use [std::any\_of](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of):
```
#include
#include
#include
int main()
{
std::string s = "Contains punctuation!!";
std::string s2 = "No puncuation";
std::cout << std::any\_of(s.begin(), s.end(), ::ispunct) << '\n';
std::cout << std::any\_of(s2.begin(), s2.end(), ::ispunct) << '\n';
}
```
[Live Example](https://www.ideone.com/oyRhev)
Upvotes: 3 |
2018/03/15 | 1,928 | 6,158 | <issue_start>username_0: It seems like in **Swift 4.1** `flatMap` is deprecated. However there is a new method in **Swift 4.1** `compactMap` which is doing the same thing?
With `flatMap` you can transform each object in a collection, then remove any items that were nil.
**Like flatMap**
```
let array = ["1", "2", nil]
array.flatMap { $0 } // will return "1", "2"
```
**Like compactMap**
```
let array = ["1", "2", nil]
array.compactMap { $0 } // will return "1", "2"
```
`compactMap` is doing the same thing.
What are the differences between these 2 methods? Why did Apple decide to rename the method?<issue_comment>username_1: There are three different variants of `flatMap`. The variant of `Sequence.flatMap(_:)` that accepts a closure returning an Optional value has been deprecated. Other variants of `flatMap(_:)` on both Sequence and Optional remain as is. The reason as explained in proposal document is because of the misuse.
Deprecated `flatMap` variant functionality is exactly the same under a new method `compactMap`.
See details [here](https://github.com/apple/swift-evolution/blob/master/proposals/0187-introduce-filtermap.md).
Upvotes: 4 <issue_comment>username_2: The Swift standard library defines 3 overloads for `flatMap` function:
```
Sequence.flatMap~~(\_: (Element) -> S) -> [S.Element]
Optional.flatMap(\_: (Wrapped) -> U?) -> U?
Sequence.flatMap(\_: (Element) -> U?) -> [U]~~
```
The last overload function can be misused in two ways:
Consider the following struct and array:
```
struct Person {
var age: Int
var name: String
}
let people = [
Person(age: 21, name: "Osame"),
Person(age: 17, name: "Masoud"),
Person(age: 20, name: "Mehdi")
]
```
**First Way: Additional Wrapping and Unwrapping:**
If you needed to get an array of ages of persons included in `people` array you could use two functions :
```
let flatMappedAges = people.flatMap({$0.age}) // prints: [21, 17, 20]
let mappedAges = people.map({$0.age}) // prints: [21, 17, 20]
```
In this case the `map` function will do the job and there is no need to use `flatMap`, because both produce the same result. Besides, there is a useless wrapping and unwrapping process inside this use case of flatMap.(The closure parameter wraps its returned value with an Optional and the implementation of flatMap unwraps the Optional value before returning it)
**Second Way - String conformance to Collection Protocol:**
Think you need to get a list of persons' name from `people` array. You could use the following line :
```
let names = people.flatMap({$0.name})
```
If you were using a swift version prior to 4.0 you would get a transformed list of
```
["Osame", "Masoud", "Mehdi"]
```
but in newer versions `String` conforms to `Collection` protocol, So, your usage of `flatMap()` would match the first overload function instead of the third one and would give you a flattened result of your transformed values:
```
["O", "s", "a", "m", "e", "M", "a", "s", "o", "u", "d", "M", "e", "h", "d", "i"]
```
**So, How did they solve it? They deprecated third overload of flatMap()**
Because of these misuses, swift team has decided to deprecate the third overload to flatMap function. And their solution to the case where you need to to deal with `Optional`s so far was to introduce a new function called `compactMap()` which will give you the expected result.
Upvotes: 6 [selected_answer]<issue_comment>username_3: **High-order function** - is a function which operates by another function in arguments or/and returned. For example - sort, map, filter, reduce...
**map vs compactMap vs flatMap**
[[RxJava Map vs FlatMap]](https://stackoverflow.com/a/67590499/4770877)
* `map` - transform(Optional, Sequence, String)
* `flatMap` - flat difficult structure into a single one(Optional, Collection)
* `compactMap` - next step of flatMap. removes nil
`flatMap` vs `compactMap`
Before Swift v4.1 three realisations of `flatMap` had a place to be(without `compactMap`). That realisation were responsible for removing nil from a sequence. And it were more about `map` than `flatMap`
Experiments
```
//---------------------------------------
//map - for Optional, Sequence, String, Combine
//transform
//Optional
let mapOptional1: Int? = Optional(1).map { $0 } //Optional(1)
let mapOptional2: Int? = Optional(nil).map { $0 } //nil
let mapOptional3: Int?? = Optional(1).map { _ in nil } //Optional(nil)
let mapOptional4: Int?? = Optional(1).map { _ in Optional(nil) } //Optional(nil)
//collection
let mapCollection1: [Int] = [1, 2].map { $0 } //[1, 2]
let mapCollection2: [Int?] = [1, 2, nil, 4].map { $0 } //Optional(1), Optional(2), nil, Optional(4),
let mapCollection3: [Int?] = ["Hello", "1"].map { Int($0) } //[nil, Optional(1)]
//String
let mapString1: [Character] = "Alex".map { $0 } //["A", "l", "e", "x"]
//---------------------------------------
//flatMap - Optional, Collection, Combime
//Optional
let flatMapOptional1: Int? = Optional(1).flatMap { $0 } //Optional(1)
let flatMapOptional2: Int? = Optional(nil).flatMap { $0 } //nil
let flatMapOptional3: Int? = Optional(1).flatMap { _ in nil }
let flatMapOptional4: Int? = Optional(1).flatMap { _ in Optional(nil) }
//Collection
let flatMapCollection1: [Int] = [[1, 2], [3, 4]].flatMap { $0 } //[1, 2, 3, 4]
let flatMapCollection2: [[Int]] = [[1, 2], nil, [3, 4]].flatMap { $0 } //DEPRECATED(use compactMap): [[1, 2], [3, 4]]
let flatMapCollection3: [Int?] = [[1, nil, 2], [3, 4]].flatMap { $0 } //[Optional(1), nil, Optional(2), Optional(3), Optional(4)]
let flatMapCollection4: [Int] = [1, 2].flatMap { $0 } //DEPRECATED(use compactMap):[1, 2]
//---------------------------------------
//compactMap(one of flatMap before 4.1) - Array, Combine
//removes nil from the input array
//Collection
let compactMapCollection1: [Int] = [1, 2, nil, 4].compactMap { $0 } //[1, 2, 4]
let compactMapCollection2: [[Int]] = [[1, 2], nil, [3, 4]].compactMap { $0 } //[[1, 2], [3, 4]]
```
[[Swift Optional map vs flatMap]](https://stackoverflow.com/a/69867501/4770877)
[[Swift Functor, Applicative, Monad]](https://stackoverflow.com/a/70229530/4770877)
Upvotes: 0 |
2018/03/15 | 776 | 2,745 | <issue_start>username_0: I am currently trying to publish a gem to rubygems.org and having some difficulty. I have built the gem on my system, but when I go to push it to rubygems, I am receiving this error:
```
// ♥ gem push upcoming-0.2.0.gem
Pushing gem to https://rubygems.org...
Repushing of gem versions is not allowed.
Please use `gem yank` to remove bad gem releases.
```
When I go to yank the version, I receive this:
```
// ♥ gem yank upcoming-0.2.0.gem -v 0.2.0
Yanking gem from https://rubygems.org...
This gem could not be found
```
Here is the terminal output for the gem build:
```
// ♥ gem build upcoming.gemspec
WARNING: open-ended dependency on nokogiri (>= 0) is not recommended
if nokogiri is semantically versioned, use:
add_runtime_dependency 'nokogiri', '~> 0'
WARNING: open-ended dependency on pry (>= 0, development) is not recommended
if pry is semantically versioned, use:
add_development_dependency 'pry', '~> 0'
WARNING: See http://guides.rubygems.org/specification-reference/ for help
Successfully built RubyGem
Name: upcoming
Version: 0.2.0
File: upcoming-0.2.0.gem
```
Does anyone know where I am going wrong here or how to bypass this issue to publish the gem?
update: I think the issue is that the gem's name is already taken on rubygems.
```
// ♥ gem yank upcoming -v 0.2.0
Yanking gem from https://rubygems.org...
You do not have permission to delete this gem.
```
Anyone know the quickest way to rename the gem? All of my files and their contents contain the word upcoming, which was the original name for it. Is there an easy way to rename it without renaming all of those files and changing their contents? I tried renaming the gemspec file to upcoming-denver-concerts.gemspec and got this error:
```
// ♥ gem build upcoming-denver-concerts.gemspec
WARNING: See http://guides.rubygems.org/specification-reference/ for help
ERROR: While executing gem ... (Gem::InvalidSpecificationException)
["upcoming.gemspec"] are not files
```<issue_comment>username_1: The first message (`This gem could not be found`) happens when you've already pushed the current version of your gem (0.2.0) to Rubygems. You can't push it twice.
The second message, I think, is from misusing the Rubygems CLI. The helpfile states `Usage: gem yank GEM -v VERSION`. I think if you changed your command to the following:
```
$ gem yank upcoming -v 0.2.0
```
Your `yank` would succeed.
The messages in your build are just warnings-- worth fixing but not preventing a successful build.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I was able to rename the gemspec file, `git add .` and gem push (new gemspec filename) and the gem successfully registered. Thanks all!
Upvotes: 0 |
2018/03/15 | 734 | 2,229 | <issue_start>username_0: I have a text file containing:
```
1:PAPER TOWNS,TOMORROWLAND
2:ENTOURAGE,JUPITER ASCENDING
```
and I'm planning to read them into a list which outputs:
```
[[1,'PAPERTOWNS','TOMORROWLAND'],[2,'ENTOURAGE','JUPITERASCENDING']]
```
I have written:
```
def read_file():
fileName = "testing.txt"
testFile = open(fileName)
table = []
for line in testFile:
contents = line.strip().split(':')
contents[0] = int(contents[0])
contents[1] = contents[1].replace(' ','')
table.append(contents)
print(table)
```
I almost managed to get the output i wanted but i couldn't figure out a way to separate the strings from:
```
[[1,'PAPERTOWNS,TOMORROWLAND'],[2,'ENTOURAGE,JUPITERASCENDING']]
```
to
```
[[1,'PAPERTOWNS','TOMORROWLAND'],[2,'ENTOURAGE','JUPITERASCENDING']]
```<issue_comment>username_1: You can split the second element by comma.
**Demo**
```
def read_file():
fileName = "testing.txt"
testFile = open(fileName)
table = []
for line in testFile:
contents = line.strip().split(':')
table.append([int(contents[0])] + contents[1].split(","))
print(table)
```
**Output:**
```
[[1, 'PAPER TOWNS', 'TOMORROWLAND'], [2, 'ENTOURAGE', 'JUPITER ASCENDING']]
```
**Using Regex:**
```
import re
def read_file():
fileName = "testing.txt"
testFile = open(fileName)
table = []
for line in testFile:
contents = re.split("[,:]+", line.strip())
table.append(contents)
print(table)
```
**Output:**
```
[['1', 'PAPER TOWNS', 'TOMORROWLAND'], ['2', 'ENTOURAGE', 'JUPITER ASCENDING']]
```
Upvotes: 1 <issue_comment>username_2: This is a one-liner with pandas. Your file is like a CSV file, just the separator character can be colon or comma, so we use a regex:
```
import pandas as pd
df = pd.read_csv('file.txt', header=None, sep=r'[:,]')
```
Upvotes: 0 <issue_comment>username_3: You can split a string by multiple delimiters :
```
import re
print([[int(re.split(':|,', line.strip())[0])]+re.split(':|,', line.strip())[1:] for line in open('text_file','r')])
```
output:
```
[[1, 'PAPER TOWNS', 'TOMORROWLAND'], [2, 'ENTOURAGE', 'JUPITER ASCENDING']]
```
Upvotes: 0 |
2018/03/15 | 671 | 1,777 | <issue_start>username_0: so far I cannot find any one who has had the same problem as mine:
* input: "['atom\_with\_special\_CHARACTERS\_like@123']"
* output: ['atom\_with\_special\_CHARACTERS\_like@123']
just that, but after spending all this morning till noon, trying mixing something like: string:tokens, list\_to\_tuple, erl\_parse... I cannot find any solution...
I know I'm getting close to the output, but just cannot really get it done.
could you please let me have some idea please ?<issue_comment>username_1: Here is my solution:
```
drop_first_last(Str) ->
lists:reverse(tl(lists:reverse(tl(Str)))).
parse(Str) ->
R = drop_first_last(Str),
[list_to_atom(drop_first_last(E)) || E <-string:tokens(R,",")].
```
calling parse function:
```
pokus:parse("['atom_with_special_CHARACTERS_like@123']").
```
output:
```
[atom_with_special_CHARACTERS_like@123]
```
or with multiple values:
```
pokus:parse("
['atom_with_special_CHARACTERS_like@123','another_atom@111']").
```
output:
```
[atom_with_special_CHARACTERS_like@123,another_atom@111]
```
Upvotes: 1 <issue_comment>username_2: ```
1> Parse = fun(S) -> {ok, Ts, _} = erl_scan:string(S), {ok, Result} = erl_parse:parse_term(Ts ++ [{dot,1} || element(1, lists:last(Ts)) =/= dot]), Result end.
#Fun
2> L = "['atom\_with\_special\_CHARACTERS\_like@123', 'you mean[like, this%']".
"['atom\_with\_special\_CHARACTERS\_like@123', 'you mean[like, this%']"
3> Parse(L).
[atom\_with\_special\_CHARACTERS\_like@123,
'you mean[like, this%']
4> Parse(" [foo, bar,\n baz, 'q u ux' ] ").
[foo,bar,baz,'q u ux']
5> Parse("{you, [can, 'write any', term, 123, 3.5, yep]}").
{you,[can,'write any',term,123,3.5,yep]}
6> Parse("even\_end\_with\_dot.").
even\_end\_with\_dot
```
Upvotes: 3 [selected_answer] |
2018/03/15 | 1,260 | 3,483 | <issue_start>username_0: I'm trying to make an html page that that has a map for the main page, and a sidenav for a menu. The problem is that I can't get the sidenav open button to show in front or above the map. It seem that its always behind it, or if I mess with stuff I can make the map disappear and then the sidenav open button is visible and works fine.
```
Test
/\*sidenav\*/
html, body {
font-family: "Lato", sans-serif;
margin:0;
padding:0;
}
#map { position:absolute; top:0; bottom:0; width:100%; }
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 30px;
}
.sidenav a, .dropdown-btn {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 20px;
color: #818181;
display: block;
border: none;
background: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
}
.sidenav a:hover, .dropdown-btn:hover {
color: #f1f1f1;
}
#myInput {
font-size: 18px;
padding: 6px 8px 6px 16px;
border: none;
border-bottom: 1px solid #ddd;
}
.main {
margin-left: 10px;
font-size: 20px;
padding: 0px 10px;
}
.active {
background-color: #111;
color: white;
}
.dropdown-container {
display: none;
background-color: #262626;
padding-left: 8px;
}
.fa-caret-down {
float: right;
padding-right: 8px;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 30px;
margin-left: 50px;
}
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
//this is the map stuff//
mapboxgl.accessToken = '<KEY>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-88.75, 42.15],
zoom: 8
});
[×](javascript:void(0))
[Home](#)
Select Congregation
[Mt. Calm](#Mt. Calm)
[Newark](#Newark)
[Wildwood](#Wildwood)
[Contact](#)
[About](#)
☰ open
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function openNav() {
document.getElementById("mySidenav").style.width = "260px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
```<issue_comment>username_1: In line number 22, change the value of the width to say 200px. Your sidenav appears just fine. Checked with your code.
Upvotes: 0 <issue_comment>username_2: Instead of setting the z-index at the navigation menu, try to give z-index to your map itself
`z-index: -1;`
Btw instead of giving google driver, better to write line codes in this directly:
<https://meta.stackexchange.com/questions/51144/how-do-i-post-code-in-stackoverflow>
Upvotes: 2 [selected_answer] |
2018/03/15 | 1,056 | 3,712 | <issue_start>username_0: I'm trying to retrieve all items from a DynamoDB table that match a `FilterExpression`, and although all of the items are scanned and half do match, the expected items aren't returned.
I have the following in an AWS Lambda function running on Node.js 6.10:
```
var AWS = require("aws-sdk"),
documentClient = new AWS.DynamoDB.DocumentClient();
function fetchQuotes(category) {
let params = {
"TableName": "quotient-quotes",
"FilterExpression": "category = :cat",
"ExpressionAttributeValues": {":cat": {"S": category}}
};
console.log(`params=${JSON.stringify(params)}`);
documentClient.scan(params, function(err, data) {
if (err) {
console.error(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
});
}
```
There are 10 items in the table, one of which is:
```
{
"category": "ChuckNorris",
"quote": "<NAME> does not sleep. He waits.",
"uuid": "844a0af7-71e9-41b0-9ca7-d090bb71fdb8"
}
```
When testing with category "ChuckNorris", the log shows:
```
params={"TableName":"quotient-quotes","FilterExpression":"category = :cat","ExpressionAttributeValues":{":cat":{"S":"ChuckNorris"}}}
{"Items":[],"Count":0,"ScannedCount":10}
```
The `scan` call returns all 10 items when I only specify `TableName`:
```
params={"TableName":"quotient-quotes"}
{"Items":[,{"category":"ChuckNorris","uuid":"844a0af7-71e9-41b0-9ca7-d090bb71fdb8","CamelCase":"thevalue","quote":"<NAME> does not sleep. He waits."},],"Count":10,"ScannedCount":10}
```<issue_comment>username_1: You do not need to specify the type (`"S"`) in your `ExpressionAttributeValues` because you are using the DynamoDB DocumentClient. Per the [documentation](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html):
>
> The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types.
>
>
>
It's only when you're using the raw DynamoDB object via `new AWS.DynamoDB()` that you need to specify the attribute types (i.e., the simple objects keyed on `"S"`, `"N"`, and so on).
With `DocumentClient`, you should be able to use params like this:
```
const params = {
TableName: 'quotient-quotes',
FilterExpression: '#cat = :cat',
ExpressionAttributeNames: {
'#cat': 'category',
},
ExpressionAttributeValues: {
':cat': category,
},
};
```
Note that I also moved the field name into an `ExpressionAttributeNames` value just for consistency and safety. It's a good practice because certain field names may break your requests if you do not.
Upvotes: 6 [selected_answer]<issue_comment>username_2: I was looking for a solution that combined KeyConditionExpression with FilterExpression and eventually I worked this out.
Where aws is the uuid. Id is an assigned unique number preceded with the text 'form' so I can tell I have form data, optinSite is so I can find enquiries from a particular site. Other data is stored, this is all I need to get the packet.
Maybe this can be of help to you:
```
let optinSite = 'https://theDomainIWantedTFilterFor.com/';
let aws = 'eu-west-4:EXAMPLE-aaa1-4bd8-9ean-1768882l1f90';
let item = {
TableName: 'Table',
KeyConditionExpression: "aws = :Aw and begins_with(Id, :form)",
FilterExpression: "optinSite = :Os",
ExpressionAttributeValues: {
":Aw" : { S: aws },
":form" : { S: 'form' },
":Os" : { S: optinSite }
}
};
```
Upvotes: 1 |
2018/03/15 | 1,015 | 3,014 | <issue_start>username_0: Similar to this Fiddle I found, <http://jsfiddle.net/JBjXN/>
I'm attempting to have it so when I select an option from
**HTML**
```
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
It will then change the value of my tag from *"Select a Show"* to other text! If someone could point me in the right direction or show me how I would go about doing this...<issue_comment>username_1: Use `.change` event listener:
```js
$('#radio-manager').on('change', function() {
const val = $('#radio-manager').val();
$('h1').text(val);
})
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 2 <issue_comment>username_2: Just add an `.change(handler)`
```js
$(() => {
$('#radio-manager').change((e) => {
$('#to-change').text(`You selected: ${e.target.value}`)
})
})
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 2 <issue_comment>username_3: You can do something like:
```js
$(function() {
//Add event listener to dropdown with class radio-line
$('.radio-line').change(function() {
//Get the text of the selected option. Not its value
var text = $(this).find("option:selected").text();
//Update the text of h1
$('h1').text(text);
});
});
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 4 [selected_answer]<issue_comment>username_4: You need to use [`change`](https://api.jquery.com/change) event of jQuery.
```js
$('#radio-manager').change(function() {
$('h1').text($(this).val());
});
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 1 <issue_comment>username_5: The .change event is what you are looking for. This event will allow you to run a function when the select items change:
```js
var h1 = $('.targetChange')
$('.target').change(function(e){
h1.text($(this).val())
})
```
```html
Hello
=======
Option 1
Option 2
Trigger the handler
```
Upvotes: 1 <issue_comment>username_6: Give id to h1 tag (whose value you want to change) like the below html
```
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
And then put below jquery inside script tag.
```
$("#radio-manager").change(function(){
var dropdown = this;
var dropdownValue = $(dropdown).val();
console.log(dropdownValue);
$("#h1_head").text(dropdownValue);
});
```
Above JQuery fired when the value of 'Select' is changed. (If it not fired put it inside document ready i.e
```
$(document).ready(function(){
$("#radio-manager").change(function(){
var dropdown = this;
var dropdownValue = $(dropdown).val();
$("#h1_head").text(dropdownValue);
});
});
```
Upvotes: 0 |
2018/03/15 | 1,113 | 3,498 | <issue_start>username_0: I have a few components that need to use same reference data, but I don't quite know how to do it. I want to write just one http service which collects the data and one function which returns the data. And I want to use that function everywhere in my components by importing the service.
Here is what I tried.
example.service.ts:
```
// http get
getRefCountriesService(): Observable {
this.countries = this.http.get(this.refCountryListUrl);
return this.countries;
}
// function which returns the data
getCountries(): any {
this.getRefCountriesService()
.subscribe(countries => {
this.countries = countries['\_embedded']['refCountries'];
return this.countries;
});
}
```
example.component.ts
```
//here is where I want to get the data to a variable
ngOnInit() {
this.countries = this.exampleService.getCountries();
}
```
I must be missing something incredibly simple, please help.<issue_comment>username_1: Use `.change` event listener:
```js
$('#radio-manager').on('change', function() {
const val = $('#radio-manager').val();
$('h1').text(val);
})
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 2 <issue_comment>username_2: Just add an `.change(handler)`
```js
$(() => {
$('#radio-manager').change((e) => {
$('#to-change').text(`You selected: ${e.target.value}`)
})
})
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 2 <issue_comment>username_3: You can do something like:
```js
$(function() {
//Add event listener to dropdown with class radio-line
$('.radio-line').change(function() {
//Get the text of the selected option. Not its value
var text = $(this).find("option:selected").text();
//Update the text of h1
$('h1').text(text);
});
});
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 4 [selected_answer]<issue_comment>username_4: You need to use [`change`](https://api.jquery.com/change) event of jQuery.
```js
$('#radio-manager').change(function() {
$('h1').text($(this).val());
});
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 1 <issue_comment>username_5: The .change event is what you are looking for. This event will allow you to run a function when the select items change:
```js
var h1 = $('.targetChange')
$('.target').change(function(e){
h1.text($(this).val())
})
```
```html
Hello
=======
Option 1
Option 2
Trigger the handler
```
Upvotes: 1 <issue_comment>username_6: Give id to h1 tag (whose value you want to change) like the below html
```
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
And then put below jquery inside script tag.
```
$("#radio-manager").change(function(){
var dropdown = this;
var dropdownValue = $(dropdown).val();
console.log(dropdownValue);
$("#h1_head").text(dropdownValue);
});
```
Above JQuery fired when the value of 'Select' is changed. (If it not fired put it inside document ready i.e
```
$(document).ready(function(){
$("#radio-manager").change(function(){
var dropdown = this;
var dropdownValue = $(dropdown).val();
$("#h1_head").text(dropdownValue);
});
});
```
Upvotes: 0 |
2018/03/15 | 972 | 2,972 | <issue_start>username_0: I have the name of a test class (as a string), eg.`"Reports::SalesReportTest"`. Without loading all the test files into memory, how can I find out which file Ruby *would have* loaded for this test-class to work?
To rephrase, is there a function which takes a class/module name (as a string), and returns the file-path that needs to be loaded for the class/module to work?<issue_comment>username_1: Use `.change` event listener:
```js
$('#radio-manager').on('change', function() {
const val = $('#radio-manager').val();
$('h1').text(val);
})
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 2 <issue_comment>username_2: Just add an `.change(handler)`
```js
$(() => {
$('#radio-manager').change((e) => {
$('#to-change').text(`You selected: ${e.target.value}`)
})
})
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 2 <issue_comment>username_3: You can do something like:
```js
$(function() {
//Add event listener to dropdown with class radio-line
$('.radio-line').change(function() {
//Get the text of the selected option. Not its value
var text = $(this).find("option:selected").text();
//Update the text of h1
$('h1').text(text);
});
});
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 4 [selected_answer]<issue_comment>username_4: You need to use [`change`](https://api.jquery.com/change) event of jQuery.
```js
$('#radio-manager').change(function() {
$('h1').text($(this).val());
});
```
```html
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
Upvotes: 1 <issue_comment>username_5: The .change event is what you are looking for. This event will allow you to run a function when the select items change:
```js
var h1 = $('.targetChange')
$('.target').change(function(e){
h1.text($(this).val())
})
```
```html
Hello
=======
Option 1
Option 2
Trigger the handler
```
Upvotes: 1 <issue_comment>username_6: Give id to h1 tag (whose value you want to change) like the below html
```
Select a Show
=============
Show 1 - May 9th 2017
Show 2 - May 10th 2017
Show 3 - May 11th 2017
```
And then put below jquery inside script tag.
```
$("#radio-manager").change(function(){
var dropdown = this;
var dropdownValue = $(dropdown).val();
console.log(dropdownValue);
$("#h1_head").text(dropdownValue);
});
```
Above JQuery fired when the value of 'Select' is changed. (If it not fired put it inside document ready i.e
```
$(document).ready(function(){
$("#radio-manager").change(function(){
var dropdown = this;
var dropdownValue = $(dropdown).val();
$("#h1_head").text(dropdownValue);
});
});
```
Upvotes: 0 |
2018/03/15 | 1,218 | 3,520 | <issue_start>username_0: I have a php array like below.
```
$array1 =Array
(
[date_stamp] => 31/01/2018
[over_time_policy_id] => 3
[over_time] => 04:00
[over_time_policy-2] => 02:00 //this
[schedule_working] => 00:00
[schedule_absence] => 00:00
[shedule_start_time] =>
[shedule_end_time] =>
[min_punch_time_stamp] => 8:00
[max_punch_time_stamp] => 20:00
[regular_time] => 01:00
[over_time_policy-3] => 02:00 //this
[worked_time] => 12:00
[actual_time] => 12:00
[actual_time_diff] => 00:00
[actual_time_diff_wage] => 0.00
[hourly_wage] => 47.1200
[paid_time] => 12:00
)
```
I want to get the result of below from the array indexes.
```
$result = Array (
[0]=>over_time_policy-2
[1]=>over_time_policy-3
);
```
I implemented the following code but not outputting anything.
```
$searchword = 'over_time_policy-';
foreach (preg_grep('/\b$searchword\b/i', $array1) as $key => $value) {
print_r($key);
}
```
Please help me on this.<issue_comment>username_1: I came up with a answer as below,
```
$searchword = 'over_time_policy-';
$matches = array();
foreach($array1 as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $k)) {
$matches[] = $k;
}
}
print_r($matches);
```
I gave me the array like below
```
$matches= Array (
[0]=>over_time_policy-2
[1]=>over_time_policy-3
);
```
Upvotes: 1 <issue_comment>username_2: You can do as :
```
$searchword = 'over_time_policy-';
$output = [];
foreach ($array1 as $key => $value) {
if (preg_match('/'.$searchword.'/i', $key)) {
$output[] = $key;
}
}
print_r($output);
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: This may helpful to you. (Get Array Keys (`array_keys`) and then apply `preg_match` on that)
```
$array1 = [
'date_stamp' => '31/01/2018',
'over_time_policy_id' => 3,
'over_time' => '04:00',
'over_time_policy-2' => '02:00', //this
'schedule_working' => '00:00',
'schedule_absence' => '00:00',
'shedule_start_time' => '',
'shedule_end_time' => '',
'min_punch_time_stamp' => '8:00',
'max_punch_time_stamp' => '20:00',
'regular_time' => '01:00',
'over_time_policy-3' => '02:00', //this
'worked_time' => '12:00',
'actual_time' => '12:00',
'actual_time_diff' => '00:00',
'actual_time_diff_wage' => '0.00',
'hourly_wage' => '47.1200',
'paid_time' => '12:00'
];
$searchword = 'over_time_policy-';
$output = [];
foreach (array_keys($array1) as $k) {
if (preg_match("/\b$searchword\b/i", $k)) {
$output[] = $k;
}
}
echo "
";
print_r($output);
```
output :-
```
Array ( [0] => over_time_policy-2 [1] => over_time_policy-3 )
```
Upvotes: 2 <issue_comment>username_4: This has a little edit on the answer
```
$word = 'over_time_policy-';
$output = [];
foreach (array_keys($array1) as $k) {
if (preg_match("/\b$word\b/i", $k)) {
$output[] = $k;
}
}
print_r($output);
```
Upvotes: 1 |
2018/03/15 | 968 | 3,021 | <issue_start>username_0: The reason I want todo this is so I can open up a Embeded youtube video in Full screen. At the moment, if I click on the Webview it opens up the youtube video into the native IOS video player. This is what I want.
However, I need to be able todo this programatically without the client clicking it. Why? The user clicks on an image inside a image gallery (image only - no video), so I close the gallery, and this is when I want to open the WebView (programatically trigger a click on it) in full screen (note: when clicking on webview, it opens the youtube video into the player straight away).
Is this even possible?
There are other ways around this which would involve changing the UI/UX, I'd want to try avoid this (if possible).<issue_comment>username_1: I came up with a answer as below,
```
$searchword = 'over_time_policy-';
$matches = array();
foreach($array1 as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $k)) {
$matches[] = $k;
}
}
print_r($matches);
```
I gave me the array like below
```
$matches= Array (
[0]=>over_time_policy-2
[1]=>over_time_policy-3
);
```
Upvotes: 1 <issue_comment>username_2: You can do as :
```
$searchword = 'over_time_policy-';
$output = [];
foreach ($array1 as $key => $value) {
if (preg_match('/'.$searchword.'/i', $key)) {
$output[] = $key;
}
}
print_r($output);
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: This may helpful to you. (Get Array Keys (`array_keys`) and then apply `preg_match` on that)
```
$array1 = [
'date_stamp' => '31/01/2018',
'over_time_policy_id' => 3,
'over_time' => '04:00',
'over_time_policy-2' => '02:00', //this
'schedule_working' => '00:00',
'schedule_absence' => '00:00',
'shedule_start_time' => '',
'shedule_end_time' => '',
'min_punch_time_stamp' => '8:00',
'max_punch_time_stamp' => '20:00',
'regular_time' => '01:00',
'over_time_policy-3' => '02:00', //this
'worked_time' => '12:00',
'actual_time' => '12:00',
'actual_time_diff' => '00:00',
'actual_time_diff_wage' => '0.00',
'hourly_wage' => '47.1200',
'paid_time' => '12:00'
];
$searchword = 'over_time_policy-';
$output = [];
foreach (array_keys($array1) as $k) {
if (preg_match("/\b$searchword\b/i", $k)) {
$output[] = $k;
}
}
echo "
";
print_r($output);
```
output :-
```
Array ( [0] => over_time_policy-2 [1] => over_time_policy-3 )
```
Upvotes: 2 <issue_comment>username_4: This has a little edit on the answer
```
$word = 'over_time_policy-';
$output = [];
foreach (array_keys($array1) as $k) {
if (preg_match("/\b$word\b/i", $k)) {
$output[] = $k;
}
}
print_r($output);
```
Upvotes: 1 |
2018/03/15 | 1,174 | 4,013 | <issue_start>username_0: I was reading Programming: Principles and Practice Using C++ (2nd Edition)
I found this question:
* Write a program that consists of a while-loop that (each time around the loop) reads in two
ints and then prints them. Exit the program when a terminating '|' is entered.
Here is what I've tried:
```
#include
using namespace std;
int main () {
int x, y;
while (x != '|' || y != '|'){
cin >> x;
cin >> y;
cout << x << endl;
cout << y << endl;
}
return 0;
}
```
When '|' is entered, it prints something like infinity loop, unexpected outputs.
* What is happening there?
* What did I do wrong?<issue_comment>username_1: First off, you have not set `x` or `y` to anything before comparing them to `'|'` in the `while` loop. That means they may have *arbitrary* values and your loop may not even start.
---
As to *why* you're seeing an infinite loop, because the variables are of type `int`, the `cin >> something` will attempt to translate the characters that you enter *into* an integer and place it into the variable.
If the initial sequence of those characters do *not* form a valid integer (say, for example, it's the `|` character), the `cin >>` will fail, the variable will be unchanged, and the input stream will remain exactly where it is.
So, when you come around again to get the next integer, `|` is *still* in the input stream and exactly the same thing will happen again, ad infinitum - note the similarity between that Latin phrase and your question title :-)
---
What you can do to fix that is to *try* to look ahead character by character to see if you have a `|` in the stream. If so, just exit. If not, try to get two integers using the normal `if (stream >> variable)` method.
This can be done with `cin.peek()` to check the next character, and `cin.get()` to remove a character. You also have to take into account the fact that neither `peek` nor `get` will skip white space the way that `operator>>` may.
Something like this should be a good start:
```
#include
#include
int main() {
int x, y;
while (true) {
// Skip all white space to (hopefully) get to number or '|'.
while (std::isspace(std::cin.peek())) std::cin.get();
// If it's '|', just exit, your input is done.
if (std::cin.peek() == '|') break;
// Otherwise, try to get two integers, fail and stop if no good.
if (! (std::cin >> x >> y)) {
std::cout << "Invalid input, not two integers\n";
break;
}
// Print the integers and carry on.
std::cout << "You entered " << x << " and " << y << "\n";
}
return 0;
}
```
---
Using various test data for that shows that it covers all the cases (taht I could think of):
```
pax$ ./myprog
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Because you defined x , y as integer but you are entering input as char.
try this code
```
#include
using namespace std;
int main ()
{
char x=NULL, y=NULL;
while (x != '|' || y != '|')
{
cin >> x;
cin >> y;
cout << x << endl;
cout << y << endl;
}
return 0;
}
```
but it has also limitation. you can only take input as single digit.if you want to take large number try this one
```
#include
using namespace std;
int main ()
{
string x="", y="";
while (x != "|" || y != "|")
{
cin >> x;
cin >> y;
cout << x << endl;
cout << y << endl;
}
return 0;
}
```
Upvotes: -1 <issue_comment>username_3: As people have pointed out in the comments and in the answer by username_1, you're two variables are uninitialized and you're trying to input into an int, and then compare it to a char.
Instead of trying to compare the inputted int to a char, we can use `cin.peek()` to peek at the next character and check if it is '|' before it is read.
```
#include
int main()
{
int x, y;
while(std::cin.peek() != '|') //cin.peek() will return the next character to be read
{
std::cin >> x >> y;
std::cout << x << ' ' << y << '\n';
std::cin.ignore(); //ignore whitespace/linebreak character left by extraction (>> operator)
}
}
```
Upvotes: 2 |
2018/03/15 | 595 | 2,432 | <issue_start>username_0: Below I am describing the sequence of events triggered by clicking on the `NavItem` of my app:
I have a `ControlledTabs` `React` component that has a child `MarkerGenesChart` which has a child `ScatterChart`. Inside the topmost `ControlledTabs` component upon switching from one `NavItem` to another I am calling `setState()` which triggers `componentWillReceiveProps()` in the `MarkerGenesChart` because it modifies some of the props that I am passing to it. Then, `MarkerGenesChart` in its `componentWillReceiveProps` is calling `setState()` that triggers the `componentWillReceiveProps` of the child `ScatterChart`. The issue is that the action `switching the NavItem` causes my childmost element `ScatterChart` to call `componentWillReceiveProps()` twice: once for the topmost component, and another time for the middle one. The first time it triggers the `ScatterChart` to draw chart with the old data, and the second time it adds the updated one without removing the old.
Here is how I am updating the data in `ScatterChart` component:
```
d3.select(node)
.datum(data_func);
chart.update();
```
I am using `nvd3` `scatterChart` and there it has `nv.utils.windowResize(chart.update);`. When I am just resizing the window everything becomes like I want it to be. How could I clean up the data before adding new one? Or maybe I should somehwere `this.forceUpdate()` but I tried it nearly everywhere and can not make it to work.
Any suggestions would be greatly appreciated.
>
> Update
>
>
>
I can partially solve it by introducing a global counter and counting the number of times `componentWillReceiveProps()` in `ScatterChart` is called, but that is a wrong way to go obviously.<issue_comment>username_1: ```
chart.update();
this.forceUpdate();
```
calling forceUpdate() is not recommended, but this is by far the simplest approach.
Upvotes: 1 <issue_comment>username_2: I was drawing the chart both in `componentDidUpdate()` and in `componentWillReceiveProps()` because some of my functionalities would be broken if I did not do that. `componentWillReceiveProps` was drawing the old data, and then `componentDidUpdate()` was adding the new one. That is why I was having the issue, and not because `componentWillReceiveProps` was called twice. I completely removed `componentWillReceiveProps` and fixed the other part of my app that was broken by that removal.
Upvotes: 0 |
2018/03/15 | 808 | 2,313 | <issue_start>username_0: I am new in angular js i want to put filter in `ng-repeat` i have json like this
```
var data = [
{name:test1,b1:{lastValue:0},b2:{lastValue:6},b3:{lastValue:6},b4:{lastValue:0}}
{name:test2,b1:{lastValue:6},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
{name:test3,b1:{lastValue:6},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
]
```
I want to put filter on lastValue i tested like this
```
ng-repeat = "d in data | filter:{*.lastValue:filterStatus}"
filterStatus // contain value of filter which user selected but its not working
```
I don't know how to do this i tried google but nothing found please help me<issue_comment>username_1: ```
```
your filterStatus should hold model value
```
ng-repeat = "d in data | filter:filterStatus"
```
Upvotes: 1 <issue_comment>username_2: ```js
var app = angular.module("Profile", []);
app.controller("ProfileCtrl", function($scope) {
$scope.filter_val = {}
$scope.data = [{
name: 'test1',
b1: {
lastValue: 0
},
index: 'b1'
}, {
name: 'test2',
b2: {
lastValue: 6
},
index: 'b2'
}, {
name: 'test3',
b3: {
lastValue: 6
},
index: 'b3'
}, {
name: 'test4',
b4: {
lastValue: 0
},
index: 'b4'
}, {
name: 'test5',
b5: {
lastValue: 89
},
index: 'b5'
}, {
name: 'test6',
b6: {
lastValue: 68
},
index: 'b6'
}]
$scope.own_filter = function(val) {
if (!$scope.filter_val.value)
return true;
else {
return (String(val[val['index']]['lastValue'] || '').indexOf($scope.filter_val.value) != -1)
}
}
})
```
```html
#### {{'Name : ' + event.name}}------{{'Last Value : '+event[event['index']]['lastValue']}}
```
Upvotes: 1 <issue_comment>username_3: Use `{$:filterStatus}` construction:
```js
angular.module('app', []).controller('ctrl',function($scope){
$scope.data = [
{name:'test1',b1:{lastValue:1},b2:{lastValue:6},b3:{lastValue:6},b4:{lastValue:0}},
{name:'test2',b1:{lastValue:2},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}},
{name:'test3',b1:{lastValue:3},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
]
})
```
```html
* {{item.name}}
```
Upvotes: 0 |
2018/03/15 | 608 | 1,772 | <issue_start>username_0: Ive looked other questions similiar to my issue but ive been unable understand and resolve issue.
```
```<issue_comment>username_1: ```
```
your filterStatus should hold model value
```
ng-repeat = "d in data | filter:filterStatus"
```
Upvotes: 1 <issue_comment>username_2: ```js
var app = angular.module("Profile", []);
app.controller("ProfileCtrl", function($scope) {
$scope.filter_val = {}
$scope.data = [{
name: 'test1',
b1: {
lastValue: 0
},
index: 'b1'
}, {
name: 'test2',
b2: {
lastValue: 6
},
index: 'b2'
}, {
name: 'test3',
b3: {
lastValue: 6
},
index: 'b3'
}, {
name: 'test4',
b4: {
lastValue: 0
},
index: 'b4'
}, {
name: 'test5',
b5: {
lastValue: 89
},
index: 'b5'
}, {
name: 'test6',
b6: {
lastValue: 68
},
index: 'b6'
}]
$scope.own_filter = function(val) {
if (!$scope.filter_val.value)
return true;
else {
return (String(val[val['index']]['lastValue'] || '').indexOf($scope.filter_val.value) != -1)
}
}
})
```
```html
#### {{'Name : ' + event.name}}------{{'Last Value : '+event[event['index']]['lastValue']}}
```
Upvotes: 1 <issue_comment>username_3: Use `{$:filterStatus}` construction:
```js
angular.module('app', []).controller('ctrl',function($scope){
$scope.data = [
{name:'test1',b1:{lastValue:1},b2:{lastValue:6},b3:{lastValue:6},b4:{lastValue:0}},
{name:'test2',b1:{lastValue:2},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}},
{name:'test3',b1:{lastValue:3},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
]
})
```
```html
* {{item.name}}
```
Upvotes: 0 |
2018/03/15 | 434 | 1,748 | <issue_start>username_0: I am trying get innerHeight, scrollHeight and scrollTop of a new page after user click the url,
```
driver.switch_to_window(driver.window_handles[-1]) # switch to newest window after user click some link
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
documentElement = driver.execute_script("return document.documentElement.scrollTop")
innerHeight = driver.execute_script("return window.innerHeight")
pageHeight = driver.execute_script("return document.body.scrollHeight")
```
However, These script return wrong value because it executed before the new page is completely loaded. How can I get the correct values?<issue_comment>username_1: As you are using driver.execute\_script, you return your innerHeight, scrollHeight and scrollTop after `document.onload` or `window.onload`.
```
driver.execute_script(document.onload = function(){return document.documentElement.scrollTop})
```
`window.onload` is recommended.
Also you can try
`driver.execute_script(window.onload=document.documentElement.scrollTop)`
Upvotes: 0 <issue_comment>username_2: You can inspect the document's ready state using JavaScript.
```
state = driver.execute_script('return document.readyState')
if state == 'complete':
# the page is completely loaded
```
You can create your own custom expected condition that tests for this.
```
class document_complete(object):
def __call__(self, driver):
script = 'return document.readyState'
try:
return driver.execute_script(script) == 'complete'
except WebDriverException:
return False
```
And use it like any other EC
```
WebDriverWait(driver, 20).until(document_complete())
```
Upvotes: 2 |
2018/03/15 | 588 | 2,056 | <issue_start>username_0: I'm trying to set a session in codeigniter 3.1.7 but its not properly working.
When I do this
```
function test(){
$params = array(
'test' =>'worked',
'base_url'=> base_url(),
'temperture' => 23,
'cart_length'=>'7 items'
);
$this->session->set_userdata($params);
print_r( $this->session->all_userdata());
// prints data no problem
}
function redirect(){
print_r( $this->session->all_userdata());
//prints Array ( [__ci_last_regenerate] => 1521089504 )
}
```
config settings
```
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'centrl';
$config['sess_expiration'] = 0;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 1800;
$config['sess_regenerate_destroy'] = FALSE;
$config['sess_expire_on_close'] = TRUE;
```
I can't understand how in the actual function it sets the session but it seems to remove it when going to another function.<issue_comment>username_1: As you are using driver.execute\_script, you return your innerHeight, scrollHeight and scrollTop after `document.onload` or `window.onload`.
```
driver.execute_script(document.onload = function(){return document.documentElement.scrollTop})
```
`window.onload` is recommended.
Also you can try
`driver.execute_script(window.onload=document.documentElement.scrollTop)`
Upvotes: 0 <issue_comment>username_2: You can inspect the document's ready state using JavaScript.
```
state = driver.execute_script('return document.readyState')
if state == 'complete':
# the page is completely loaded
```
You can create your own custom expected condition that tests for this.
```
class document_complete(object):
def __call__(self, driver):
script = 'return document.readyState'
try:
return driver.execute_script(script) == 'complete'
except WebDriverException:
return False
```
And use it like any other EC
```
WebDriverWait(driver, 20).until(document_complete())
```
Upvotes: 2 |
2018/03/15 | 820 | 2,521 | <issue_start>username_0: I have `FloatingActionButton` in my app. It is working fine in Android N and O . but it is crashing in Marshmallow. Can any one help me to solve this issue.
**Error**
```
Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.FloatingActionButton
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at LibraryFragment.onCreateView(LibraryFragment.java:69)
```
XML
```
```
build.gradle
```
compileSdkVersion 26
defaultConfig {
minSdkVersion 15
targetSdkVersion 26
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.github.moondroid.coverflow:library:1.0'
compile 'com.google.android.gms:play-services-ads:11.8.0'
compile 'com.android.support:recyclerview-v7:26.1.0'
compile 'com.android.support:cardview-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.github.florent37:diagonallayout:1.0.2'
compile 'de.hdodenhof:circleimageview:2.1.0'
}
```<issue_comment>username_1: Maybe it's because of the version you are using with Android design library:
Paste this inside dependencies, if it is already there then replace it
```
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
```
Also change compileSdkVersion to 25
Also change:
`android:backgroundTint="#114358"` with `app:backgroundTint="#114358"`
And if you are using vector asset as src then use
```
app:srcCompat="@drawable/you_graphics"
```
Insted of this
`android:src="@drawable/your_graphics"`
Hope it helps
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> This work in marshmallow and lollipop
>
>
>
```
```
>
> Add bellow in App gradle file
>
>
>
```
compileSdkVersion 26
buildToolsVersion "26.0.2"
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:support-v13:26.1.0'
```
Upvotes: 1 |
2018/03/15 | 1,372 | 4,433 | <issue_start>username_0: I am working on a Vue Js 2 application and I'm currently building the store and the different modules to separate out the code.
Is there a way to write a common function and share it across all modules?
For example, I have a function truncate() that I need to be use in customer.js, cart.js, address.js.
If I declare it in store.js and try to use in modules, it throws an error.
Is export and import the only way?
What is the best way to share the function?<issue_comment>username_1: you can use vue js events to share function like
eventBus.js // it will create common instance
```
import Vue from 'vue';
export const eventBus = new Vue();
```
common.js // your common functions will go into this file
```
import { eventBus } from '';
mounted() {
eventBus.$on('truncate',()=> {
this.truncate();
})
}
methods: {
truncate(){
//truncate code
}
}
```
customer.js // call your common truncate function from customer.js
```
import { eventBus } from '';
eventBus.$emit('truncate');
```
Upvotes: 0 <issue_comment>username_2: The simplest case is, naturally, to just define a regular function in a js file and import/use it anywhere you need it.
There are Vue-specific approaches, though:
For common reusable functions in **Vuex modules**, you can use [**Vuex Plugins**](https://vuex.vuejs.org/en/plugins.html).
Check an example below. Mind the usage at the root store: `plugins: [myTruncatePlugin]`.
```js
const myTruncatePlugin = store => {
store.truncate = function(str) {
return str.replace(/-/g, '') + ' ...was truncaaaated!'; // example implementation
}
}
const moduleA = {
namespaced: true,
state: {name: "name@moduleA"},
mutations: { changeName(state, data) { state.name = this.truncate(data); } },
}
const moduleB = {
namespaced: true,
state: {title: "title@moduleB"},
mutations: { changeTitle(state, data) { state.title = this.truncate(data); } },
}
const myStore = new Vuex.Store({
strict: true,
modules: {
aaa: moduleA,
bbb: moduleB
},
plugins: [myTruncatePlugin] // IMPORTANT: YOU MUST DECLARE IT HERE
});
new Vue({
store: myStore,
el: '#app',
mounted: function() {
setTimeout(() => {
this.changeName("-n-e-w-N-A-M-E-");
this.changeTitle("-n-e-w-T-I-T-L-E-");
}, 200);
},
computed: {
...Vuex.mapState('aaa', ['name']),
...Vuex.mapState('bbb', ['title'])
},
methods: {
...Vuex.mapMutations('aaa', ['changeName']),
...Vuex.mapMutations('bbb', ['changeTitle'])
}
})
```
```html
moduleA's name: {{ name }}
moduleB's title: {{ title }}
```
For common reusable functions in Vue instances, you can use [**Mixins**](https://v2.vuejs.org/v2/guide/mixins.html). For the most general case there's the [**Global Mixin**](https://v2.vuejs.org/v2/guide/mixins.html#Global-Mixin) (use with care):
```js
Vue.mixin({
methods: {
truncate(str) {
return str.replace(/-/g, '') + ' ...was truncaaaated!'; // example implementation
}
}
})
// this.truncate() will be available in all Vue instances...
new Vue({
el: '#app1',
data: {myStr1: '-o-n-e-'},
mounted() { this.myStr1 = this.truncate(this.myStr1); }
})
new Vue({
el: '#app2',
data: {myStr2: '-t-w-o-'},
mounted() { this.myStr2 = this.truncate(this.myStr2); }
})
// ...and components
Vue.component('my-comp', {
template: '#t3',
data() { return {myStr3: '-t-h-r-e-e-'} },
mounted() { this.myStr3 = this.truncate(this.myStr3); }
});
new Vue({
el: '#app3',
})
```
```html
App1: "{{ myStr1 }}"
App2: "{{ myStr2 }}"
App3's component: "{{ myStr3 }}"
```
Upvotes: 4 <issue_comment>username_3: @username_2 has the best answer using Mixins, but I'm giving you another option by just declaring method in your Vue instance.
So belows example, I am creating `doTruncate` method in Vue instance then the components are calling them by `this.$parent.doTruncate`
```js
// register
Vue.component('cart-component', {
template: 'Cart Truncate!',
methods: {
doTruncate: function() {
this.$parent.doTruncate("Hello from cart");
}
}
})
// register
Vue.component('customer-component', {
template: 'Customer Truncate!',
methods: {
doTruncate: function() {
this.$parent.doTruncate("Hello from customer");
}
}
})
var app3 = new Vue({
el: '#app',
methods: {
doTruncate: function(params) {
alert(params);
}
}
})
```
```html
Parent!
```
Upvotes: 1 |
2018/03/15 | 944 | 3,528 | <issue_start>username_0: I have a table View in a View Controller, and within the cells, my text gets cut off when it's too long. How do I get the cell to automatically change based on the content in the cell or get the text to wrap so the text doesn't get cut off? Here's an [image](https://i.stack.imgur.com/hN7kB.png) of what I'm talking about.
```
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func allowMultipleLines(tableViewCell: UITableViewCell) {
tableViewCell.textLabel?.numberOfLines = 0
tableViewCell.textLabel?.lineBreakMode = .byWordWrapping
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return courses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let course:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "course")!
course.textLabel?.text = courses[indexPath.row]
return course
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "Courses", sender: nil)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailView: DetailCoursesViewController = segue.destination as! DetailCoursesViewController
selectedRow = (table.indexPathForSelectedRow?.row)!
detailView.setCourseTitle (t: courses[selectedRow])
detailView.setCourseDescription (d: courseDescription[selectedRow])
detailView.setCredits (c: credits[selectedRow])
detailView.setPrerequisites (p: prereq[selectedRow])
}
```
Here is the [image](https://i.stack.imgur.com/Yu5JJ.png) of the code<issue_comment>username_1: 1) Set `UILabel property numberOfLines = 0` inside `cellForRowAt` of `UITableView`
2) Inside `ViewDidLoad` write below code
```
self.tabelView.estimatedRowHeight = 44
self.tabelView.rowHeight = UITableViewAutomaticDimension
```
[Demo Example](https://github.com/paresh1994/TableViewDynamicCellSize)
Upvotes: 1 <issue_comment>username_2: 1- Give a bottom constraint between the label and cell bottom like 10
2- In the function `tableView(_:cellForRowAt:)` do the following:
```
cell.textLabel.numberOfLines = 0
cell.textLabel.lineBreakMode = .byWordWrapping
```
Upvotes: 0 <issue_comment>username_3: First you need to set **leading, trailing, bottom and top constraints** of label to contentView in the TableViewcell.
```
override func viewDidLoad() {
super.viewDidLoad()
self.tabelView.estimatedRowHeight = 50
self.tabelView.rowHeight = UITableViewAutomaticDimension
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return courses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let course:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "course")!
cell.textLabel.numberOfLines = 0
course.textLabel?.text = courses[indexPath.row]
return course
}
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 1,400 | 4,609 | <issue_start>username_0: This is my **api**:
```
exports.getService = function(req, res) {
var limit = 10; // number of records per page
var offset = 0;
Service.findAndCountAll({
raw: true,
where: {
shop: req.user.shop
}
}).then((data) => {
var page = req.params.page; // page number
var pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
Service.findAll({
// raw: true,
limit: limit,
offset: offset,
$sort: {
id: 1
},
where: {
shop: req.user.shop
},
include: [{
model: Categoryservice,
attributes: ['id'],
include: [{
model: Category,
attributes: ['id', 'name'],
}]
}],
}).then(function (services) {
var services=JSON.parse(JSON. stringify(services));
console.log('=====stringify==========>>',services);
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
}).catch(function(error) {
res.status(500).send('Internal Server Error');
});
};
```
I am using **map** in last then fuction ,
It contains a error map undefined in the server..
I want want a out like below given json using the map fuction.
Actually i need this out put:
```
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [
1,
2
]
}
```
my JSON. stringify(services) out put is:
```
=====stringify==========>> [ { id: 2,
username: null,
name: null,
image: null,
service: 'mobile',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '20',
per: '10',
tax: '1',
activity: null,
createdAt: '2018-03-14T07:30:57.000Z',
updatedAt: '2018-03-14T07:30:57.000Z',
categoryservices: [ [Object], [Object] ] },
{ id: 1,
username: 'sam',
name: 'New Service',
image: '/images/uploads/22-Feb-2018/f96334384cd78754454c5e4e05e20fc0-dragon_pattern_red_black_9666_1920x1080.jpg',
service: 'battery',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '5',
per: '1',
tax: '1',
activity: '2018-03-14T06:01:36.000Z',
createdAt: '2018-03-14T06:01:36.000Z',
updatedAt: '2018-03-14T06:01:36.000Z',
categoryservices: [] } ]
```
I was beginner of using map function,
so,I am confused in map ,
so please give any solution to this problem.<issue_comment>username_1: You are stringifying your array that comes back. You can't do that if you plan to use .map on it. Remove that code and try again.
```
.then(function (services) {
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
```
I think we are missing something because the output you pasted doesn't have the category.id attribute that you are returning from the item passed in to map. Is that what you are trying to target? That's off topic, but this code may not work for what you are trying to achieve but will run the map though.
Upvotes: 0 <issue_comment>username_2: Looks like `services` is an array, based on the console.log. If you want the id's of all categories, you can do
```
let categoryIds = [];
categoryIds = services.reduce((categoryIds, service) => {
let ids = service.categoryservices.map(category => category.id);
for(let id of ids) {
if(categoryIds.indexOf(id) === -1) {
categoryIds.push(id)
}
}
return categoryIds;
}, categoryIds);
```
If you want to have category ids as `cats` in each service, you can do,
```
var services=JSON.parse(JSON. stringify(services));
services.forEach(service) => {
service.cats = service.categoryservices.map(category => category.id);
delete service.categoryservices;
});
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
```
Hope this helps!
Upvotes: -1 |
2018/03/15 | 1,578 | 4,342 | <issue_start>username_0: I'm trying this mapgroups function on the below dataset
and not sure why I'm getting 0 for the "Total Value" column.
Am I missing something here??? Please advice
Spark Version - 2.0
Scala Version - 2.11
```
case class Record(Hour: Int, Category: String,TotalComm: Double, TotalValue: Int)
val ss = (SparkSession)
import ss.implicits._
val df: DataFrame = ss.sparkContext.parallelize(Seq(
(0, "cat26", 30.9, 200), (0, "cat26", 22.1, 100), (0, "cat95", 19.6, 300), (1, "cat4", 1.3, 100),
(1, "cat23", 28.5, 100), (1, "cat4", 26.8, 400), (1, "cat13", 12.6, 250), (1, "cat23", 5.3, 300),
(0, "cat26", 39.6, 30), (2, "cat40", 29.7, 500), (1, "cat4", 27.9, 600), (2, "cat68", 9.8, 100),
(1, "cat23", 35.6, 500))).toDF("Hour", "Category","TotalComm", "TotalValue")
val resultSum = df.as[Record].map(row => ((row.Hour,row.Category),(row.TotalComm,row.TotalValue)))
.groupByKey(_._1).mapGroups{case(k,iter) => (k._1,k._2,iter.map(x => x._2._1).sum,iter.map(y => y._2._2).sum)}
.toDF("KeyHour","KeyCategory","TotalComm","TotalValue").orderBy(asc("KeyHour"))
resultSum.show()
+-------+-----------+---------+----------+
|KeyHour|KeyCategory|TotalComm|TotalValue|
+-------+-----------+---------+----------+
| 0| cat26| 92.6| 0|
| 0| cat95| 19.6| 0|
| 1| cat13| 12.6| 0|
| 1| cat23| 69.4| 0|
| 1| cat4| 56.0| 0|
| 2| cat40| 29.7| 0|
| 2| cat68| 9.8| 0|
+-------+-----------+---------+----------+
```<issue_comment>username_1: `iter` inside `mapGroups` is a *buffer* and **computation can be perfomed only once**. So when you sum as `iter.map(x => x._2._1).sum` then **there is nothing left in *iter* buffer** and thus `iter.map(y => y._2._2).sum` operation yields *0* . So you will have to find a mechanism to calculate sum of both in the same iteration
**for loop with ListBuffers**
for simplicity I have used `for` loop and `ListBuffer` to sum both at once
```
val resultSum = df.as[Record].map(row => ((row.Hour,row.Category),(row.TotalComm,row.TotalValue)))
.groupByKey(_._1).mapGroups{case(k,iter) => {
val listBuffer1 = new ListBuffer[Double]
val listBuffer2 = new ListBuffer[Int]
for(a <- iter){
listBuffer1 += a._2._1
listBuffer2 += a._2._2
}
(k._1, k._2, listBuffer1.sum, listBuffer2.sum)
}}
.toDF("KeyHour","KeyCategory","TotalComm","TotalValue").orderBy($"KeyHour".asc)
```
this should give you correct result
```
+-------+-----------+---------+----------+
|KeyHour|KeyCategory|TotalComm|TotalValue|
+-------+-----------+---------+----------+
| 0| cat26| 92.6| 330|
| 0| cat95| 19.6| 300|
| 1| cat23| 69.4| 900|
| 1| cat13| 12.6| 250|
| 1| cat4| 56.0| 1100|
| 2| cat68| 9.8| 100|
| 2| cat40| 29.7| 500|
+-------+-----------+---------+----------+
```
I hope the answer is helpful
Upvotes: 4 [selected_answer]<issue_comment>username_2: As username_1 has pointed out, the issue lie in using the iterators twice, which will result in the `TotalValue` column being 0. However, there is no need to even use `groupByKey` and `mapGroups` from the beginning. The same can be acomplished using `groupBy` and `agg` which will result in much cleaner and easier to read code. And as a plus, it avoids using the slow `groupByKey` as well.
The following will work just as well:
```
val resultSum = df.groupBy($"Hour", $"Category")
.agg(sum($"TotalComm").as("TotalComm"), sum($"TotalValue").as("TotalValue"))
.orderBy(asc("Hour"))
```
Result:
```
+----+--------+---------+----------+
|Hour|Category|TotalComm|TotalValue|
+----+--------+---------+----------+
| 0| cat95| 19.6| 300|
| 0| cat26| 92.6| 330|
| 1| cat23| 69.4| 900|
| 1| cat13| 12.6| 250|
| 1| cat4| 56.0| 1100|
| 2| cat68| 9.8| 100|
| 2| cat40| 29.7| 500|
+----+--------+---------+----------+
```
If you still want to change the names of the Hour and Category columns that is easily done by changing the `groupBy` to
```
groupBy($"Hour".as("KeyHour"), $"Category".as("KeyCategory"))
```
Upvotes: 2 |
2018/03/15 | 779 | 2,893 | <issue_start>username_0: In [React v16.2.0](https://reactjs.org/docs/react-api.html#reactchildren), there is a new API call `React.Children`.
I am curious what's the different between `React.Children` and use `children` directly.
For example, if I want to manipulate the children content, I can do the trick in both methods. [example](https://codesandbox.io/s/4lxx4ynz70)
```
const Child = () => (
child
)
class App extends React.Component {
render() {
const template1 = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child);
});
const template2 = this.props.children.map((child) => {
return React.cloneElement(child);
});
return [template1, template2];
}
}
```
And the result is the same.
Does anyone know what is the different?
Or what is the purpose for React team to release this API?<issue_comment>username_1: To the best of my knowledge, for your operations there is no real difference. However, `React.Children` provides utilities for dealing with `this.props.children`. For the use of `map` there was one comment in [the documentation](https://reactjs.org/docs/react-api.html#reactchildren) that I thought might be interesting:
>
> If children is a keyed fragment or array it will be traversed
>
>
>
So their implementation seems to be doing a little more than if your just used `Array.prototype.map`.
You can read on what other [functionality `React.Children` provides](https://reactjs.org/docs/react-api.html#reactchildren), but it largely seems like they are providing convenience functions so you don't have to worry about traversing children who may have children and so on.
Upvotes: 4 [selected_answer]<issue_comment>username_2: The children of React component is a node which might be undefined or null. React.Children.map is a utility function to help you handle different cases.
[React.Children.map](https://reactjs.org/docs/react-api.html#reactchildrenmap)
>
> Invokes a function on every immediate child contained within children with this set to thisArg. If children is an array it will be traversed and the function will be called for each child in the array. If children is null or undefined, this method will return null or undefined rather than an array.
>
>
>
You should always use React.Children.map to traverse children in your app. Use children.map throws an error when children is not an array.
Upvotes: 4 <issue_comment>username_3: Please take a look at this example to see the different
Paste this to console browser:
```
var children = null
chidren.map(i => {return i}) // => VM370:1 Uncaught TypeError: Cannot read property 'map' of null
React.Children.map(children, i => {return i;}) // return null
```
Here is the result:

So React.Children.map will handle the case when children is null or undefined
Upvotes: 3 |
2018/03/15 | 746 | 2,894 | <issue_start>username_0: I want to interact with a smart contract using web3js. Every example will start with following
```js
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// or
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
```
I don't understand the use of Web3.providers.HttpProvider('Address').
My Guess: So when establishing a private network every node should give a different rpcport which identifies it and so it connects to the network. Am I wrong?
For example, the above code is used in Frontend for a website in order to connect frontend and deploy a contract in Ethereum Private Network. So the frontend code must be generic which means it should not add specific Ethereum node address in its code. Then what is the use of Web3.providers.HttpProvider('Address')?<issue_comment>username_1: It has nothing to do with using a private vs public blockchain.
You need to give your client a way to connect to the blockchain. Specifically, the web3js library requires `Provider` object that includes the connection protocol and the address/port of the node you're going to connect to.
Web3js support [3 different providers](http://web3js.readthedocs.io/en/1.0/web3.html#providers): `HttpProvider`, `WebsocketProvider`, and `IpcProvider`. Both HTTP and WS require the address of the node (IPC uses a file). The address itself will be localhost if you're running a peer node on your client (ie, using Parity or Geth). If you're using a centralized provider like Infura, you would use `https://mainnet.infura.io/API_KEY`.
Upvotes: 4 <issue_comment>username_2: It is not linked to the private or public blockchain. On the Ethereum network, all nodes are connected to each other. When one performs a transaction, providers are used to inform other nodes about this transaction.
Upvotes: 1 <issue_comment>username_3: **Provider:**
You need a Provider to read from the blockchain. In simple terms its a server running a node(local or a service like "infura") that which can query the blockchain directly.
**HttpProvider:**
A node either local or on cloud can give a HTTP, IPC or WSS for clients to interact with the node. "Web3.providers.HttpProvider()" takes the http url of the node.
**Docs Reference:**
<https://docs.ethers.io/v5/api/providers/>
***Code Example:***
```js
const Web3 = require("web3");
const HttpProvider =
"https://eth-mainnet.g.alchemy.com/v2/YOUR_API";
async function main() {
try {
// Creating an instance of the Provider
const web3 = new Web3(new Web3.providers.HttpProvider(HttpProvider));
console.log("Connection Successful");
console.log("Latest Block Number: ");
// Querying the Blockchain using the Provider and Web3.js
console.log(await web3.eth.getBlockNumber());
}
catch (error) {
console.log("Connection Error! ", error);
}
}
main();
```
Upvotes: 1 |
2018/03/15 | 1,043 | 3,794 | <issue_start>username_0: I am learning to code C++ right now and I've been struggling to finish this task for a few days as I couldn't find good examples online: basically, I have to create an entity called Students and all its attributes such as name, code and cardnumber must be created, accessed and removed dinamically. So, here's what I've tried, just to test some features:
```
#include
#include
#include
using namespace std;
class Students{
public:
Students (int codigo\_, string nome\_, string cpf\_){
codigo = codigo\_;
nome = nome\_;
cpf = cpf\_;
}
void print(){
cout << codigo << " " << nome << " " << cpf;
}
private:
int codigo;
string nome;
string cpf;
};
int main () {
vector < Students\* > students;
students.push\_back(new Students(123, "asdf", "012.123-12"));
for (int i =0; i<1; i++) students[0].print();
return 0;
}
```
But it gives an error:
**request for member ‘print’ in ‘\* alunos.std::vector<\_Tp, \_Alloc>::operator[] >(0ul)’, which is of pointer type ‘Alunos\*’ (maybe you meant to use ‘->’ ?)
alunos[0]->print();**
**How should I access, let's say, for an example, a third student element in the vector, then?**
Also, at first I wanted to use an iterator, but it gave a huge error and I couldn't seem to work with it, I had replaced the for loop line with the following line:
```
for (vector::iterator it = students.begin() ; it != students.end() ; it++)
cout << " " << it.print();
```
**Why I can't use iterators like this?**
I would really appreciate if you could also point some concise materials and textbooks online with more examples on c++ classes and object oriented codes, I keep finding recommendations on books with thousands of pages, which are not very practical.<issue_comment>username_1: It has nothing to do with using a private vs public blockchain.
You need to give your client a way to connect to the blockchain. Specifically, the web3js library requires `Provider` object that includes the connection protocol and the address/port of the node you're going to connect to.
Web3js support [3 different providers](http://web3js.readthedocs.io/en/1.0/web3.html#providers): `HttpProvider`, `WebsocketProvider`, and `IpcProvider`. Both HTTP and WS require the address of the node (IPC uses a file). The address itself will be localhost if you're running a peer node on your client (ie, using Parity or Geth). If you're using a centralized provider like Infura, you would use `https://mainnet.infura.io/API_KEY`.
Upvotes: 4 <issue_comment>username_2: It is not linked to the private or public blockchain. On the Ethereum network, all nodes are connected to each other. When one performs a transaction, providers are used to inform other nodes about this transaction.
Upvotes: 1 <issue_comment>username_3: **Provider:**
You need a Provider to read from the blockchain. In simple terms its a server running a node(local or a service like "infura") that which can query the blockchain directly.
**HttpProvider:**
A node either local or on cloud can give a HTTP, IPC or WSS for clients to interact with the node. "Web3.providers.HttpProvider()" takes the http url of the node.
**Docs Reference:**
<https://docs.ethers.io/v5/api/providers/>
***Code Example:***
```js
const Web3 = require("web3");
const HttpProvider =
"https://eth-mainnet.g.alchemy.com/v2/YOUR_API";
async function main() {
try {
// Creating an instance of the Provider
const web3 = new Web3(new Web3.providers.HttpProvider(HttpProvider));
console.log("Connection Successful");
console.log("Latest Block Number: ");
// Querying the Blockchain using the Provider and Web3.js
console.log(await web3.eth.getBlockNumber());
}
catch (error) {
console.log("Connection Error! ", error);
}
}
main();
```
Upvotes: 1 |
2018/03/15 | 642 | 2,212 | <issue_start>username_0: here is my code below
```
folder_results = Dir.foreach(Dir.pwd) {|x| File.extname(x) }
```
ive also tryed:
```
folder_results = Dir.foreach("nice/") {|x| File.extname(x) }
```
Here is my Ruby cmd errors, Ive attempt this many times , in many different ways
you can see the ruby path used in the Ruby cmd
[](https://i.stack.imgur.com/mVd03.png)
Edit:
This is what the file dir looks like of nice :
[](https://i.stack.imgur.com/BREWA.png)<issue_comment>username_1: The error message comes from `Dir.foreach` and says that the supplied argument is not a directory.
In the case where you simply put 'nice' as argument, I would conclude that this directory does not exist, but since the error message also appears for `Dir.pwd` as argument, it means that Ruby's idea of what the working directory is, must be messed up. Actually, the error message says that the result of `Dir.pwd` would be the string `pwd`, which is nonsense: `Dir.pwd` always returns an absolute path. To verify that this is really the case, I would do a `puts(Dir.pwd)` before the offending line, but I guess that this will also show `pwd`.
This means that you will have to find out, at which point in your program the working directory gets messed up. It must be OK at the program start (but please check!), and narrow down the search until you find the culprit.
BTW, aside from this problem, your program is logically flawed. You calculate all the file extensions, but then throw the result away, and folder\_results will always be `nil`.
Upvotes: 0 <issue_comment>username_2: You should save the `File.extname` result to an array instead of directly assigning result from `Dir.foreach` which always returns nil.
```
folder_results = []
Dir.foreach(Dir.pwd) { |x| folder_results << File.extname(x) }
```
Now you can get the file name extensions from `folder_results` array.
Else, you can use `map`. Thanks [engineersmnky](https://stackoverflow.com/users/1978251/engineersmnky) for pointing out this.
```
folder_results = Dir.foreach(Dir.pwd).map { |x| File.extname(x) } –
```
Upvotes: 1 |
2018/03/15 | 1,880 | 5,772 | <issue_start>username_0: Anyone having this problem on native partitioned tables?
Partitioned table has 7202 partitions. No partition contains more than 50 records. Partitioning is done on a foreign key.
Any delete operation i.e.
```
delete from contacts where id = ?
delete from contacts where id = ? and account_id = ?
delete from contacts where account_id = ?
```
results in out of memory condition.
Default Postgres Configuration with exception
max\_locks\_per\_transaction = 1024
Postgres Logs:
```none
2018-03-15 14:26:40.340 AEDT [7120] LOG: server process (PID 8177) was terminated by signal 9: Killed
2018-03-15 14:26:40.340 AEDT [7120] DETAIL: Failed process was running: delete from contacts where id = 82398 and account_id = 9000
2018-03-15 14:26:40.354 AEDT [7120] LOG: terminating any other active server processes
2018-03-15 14:26:40.367 AEDT [3821] WARNING: terminating connection because of crash of another server process
2018-03-15 14:26:40.367 AEDT [3821] DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
2018-03-15 14:26:40.367 AEDT [3821] HINT: In a moment you should be able to reconnect to the database and repeat your command.
2018-03-15 14:26:40.369 AEDT [7726] mark@postgres WARNING: terminating connection because of crash of another server process
2018-03-15 14:26:40.369 AEDT [7726] mark@postgres DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
2018-03-15 14:26:40.369 AEDT [7726] mark@postgres HINT: In a moment you should be able to reconnect to the database and repeat your command.
2018-03-15 14:26:40.392 AEDT [7749] <EMAIL> WARNING: terminating connection because of crash of another server process
2018-03-15 14:26:40.392 AEDT [7749] <EMAIL> DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
2018-03-15 14:26:40.392 AEDT [7749] <EMAIL>@<EMAIL> HINT: In a moment you should be able to reconnect to the database and repeat your command.
2018-03-15 14:26:40.569 AEDT [7120] LOG: all server processes terminated; reinitializing
2018-03-15 14:26:40.639 AEDT [9244] LOG: database system was interrupted; last known up at 2018-03-15 13:08:47 AEDT
2018-03-15 14:26:41.745 AEDT [9251] mark@postgres FATAL: the database system is in recovery mode
2018-03-15 14:26:41.746 AEDT [9252] mark@postgres FATAL: the database system is in recovery mode
2018-03-15 14:26:44.778 AEDT [9244] LOG: database system was not properly shut down; automatic recovery in progress
2018-03-15 14:26:44.798 AEDT [9244] LOG: redo starts at 0/56782CE0
2018-03-15 14:26:44.798 AEDT [9244] LOG: invalid record length at 0/56782D18: wanted 24, got 0
2018-03-15 14:26:44.798 AEDT [9244] LOG: redo done at 0/56782CE0
2018-03-15 14:26:44.870 AEDT [7120] LOG: database system is ready to accept connections
```<issue_comment>username_1: From <NAME>, pgsql-bugs
>
> I can reproduce OOM being triggered on my modest
> development machine, so perhaps that's what's happening in your case too.
>
>
> This is unfortunately expected, given that the underlying planning
> mechanism cannot cope beyond a few hundred partitions. :-( See a relevant
> note in the documentation; last line of the page at this link:
> <https://www.postgresql.org/docs/devel/static/ddl-partitioning.html>.
>
>
> Until things improve in that area, one workaround might be to perform the
> delete operation directly on the partition, as it's possible to do that.
> Or redesign your schema to use less number of partitions.
>
>
>
I know this is not actually a solution but rather a cautionary tale.
It would seem that native partitioning in postgresql 10, does not fit our use case. Part of my brief was to evaluate it's suitability. I suspected there would be a cost to aggressive partitioning but didn't expect memory problems.
Still feel free to post your own experiences and solutions.
Upvotes: 2 <issue_comment>username_2: We have exactly the same problem on PostgreSQL 11, on table with multilevel native partitioning. Main table is partitioned by shops and each shop by period (year-month) over last several years. I.e. several thousands of partitions together.
When we need to do deletes or updates over all shops PostgreSQL crashes. PostgreSQL is able to handle deletion/updates over one level of partitioning - i.e. from one specific shop and its monthly partitions. Because here we have only like several dozens of partitions for each shop.
But database crashes when we try to delete or update over main top parent table - i.e. several thousands of partitions are being addressed here.
Crashes are still the same - monitoring shows that PostgreSQL starts to use huge amount of memory and eventually is killed by OOM killer. Tuning of work\_mem or other settings seems to have only very small influence - PostgreSQL just crashes later.
So we have to do all deletes/updates on this table using cycle over shops and do deletes or updates over these partitions separately. But at least this works.
For explanation - these fine grained partitions are incredibly useful for our client portal. Because we store aggregated data there and construct queries using directly specific shop-monthly partition so clients see data very quickly. And native partitioning takes care of distributing data over whole structure during inserts which is amazing...
Upvotes: 0 |
2018/03/15 | 502 | 1,989 | <issue_start>username_0: I am using ember simple auth and when I log out and the session invalidates I am redirected back to the root of the site. How do I redirect it to the login route on invalidate session?<issue_comment>username_1: You can use this for read session
```
this.get('session.data.currentUser')
```
handle that whatever you want.
app/router.js
```
Router.map(function() {
this.route('posts');
this.route('post', { path: '/post/:post_id' });
```
});
app/routes/index.js
```
import Ember from 'ember';
export default Ember.Route.extend({
afterModel(model, transition) {
if (model.get('length') === 1) {
this.transitionTo('post', model.get('firstObject'));
}
}
});
```
Use this
Upvotes: 0 <issue_comment>username_2: Use authenticated route mixin in your route, which should be accessible after authentication:
```
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
AuthenticatedRoute = Ember.Route.extend(AuthenticatedRouteMixin, {
// route you would like to redirect to after logout
authenticationRoute: "routes.login",
// ... your stuff ...
})
```
In root application route use also corresponding mixin:
```
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
ApplicationRoute = Ember.Route.extend(ApplicationRouteMixin, {
// route you would like to redirect to after login
routeAfterAuthentication: "routes.authenticated-route",
// ... your stuff
})
```
It depends on your needs, how you will use it. You can put it in every authenticated route, or for example you can put it in one route (eg. called "/auth") and put another authenticated routes into this route. Each of these routes will be also authenticated, your routing structure could look like this:
```
/
login
auth
alsoAuthenticatedRoute
someAuthenticatedDetailRoute
anotherAuthenticatedRoute
anotherAuthenticatedDetailRoute
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 1,431 | 6,192 | <issue_start>username_0: I am trying out dagger2 and want to inject a presenter into the activity, i searched the internet as to why the presenter is null but then i get different implementations of injecting an activity with several modules. Can someone please help me understand where i am going wrong when trying to create the dagger dependencies?
I have the following classes defined:
**ActivityComponent.class**
```
@PerActivity
@Component(modules = {ActivityModule.class}, dependencies = {AppComponent.class, GitHubComponent.class})
public interface ActivityComponent {
void inject(AppCompatActivity activity);
}
```
**ActivityModule.class**
```
@Module
public class ActivityModule {
private AppCompatActivity activity;
public ActivityModule(AppCompatActivity activity) {
this.activity = activity;
}
@Provides
AppCompatActivity provideActivity() {
return activity;
}
@Provides
@PerActivity public MainView provideMainView() {
return new MainViewImpl(activity);
}
@Provides
@ActivityScope
Context providesContext() {
return activity;
}
}
```
**AppModule.class**
```
@Singleton
@Module
public class AppModule {
private final GitHubApp application;
public AppModule(final GitHubApp application) {
this.application = application;
}
@Provides
Application provideApplication() {
return application;
}
@Provides
public GitHubLog provideGithubLog() {
return new GitHubLog();
}
}
```
**GitHubModule.class**
```
@Module
public class GitHubModule {
@Provides
public MainInteractor provideMainInteractor() {
return new MainInteractorImpl();
}
@Provides
@PerActivity
public MainPresenter provideMainPresenter(){
return new MainPresenterImpl();
}
}
```
**AppComponent.class**
```
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(GitHubApp gitHubApp);
void inject(GitHubLog gitHubLog);
Application application();
GitHubLog getGitHubLog();
}
```
**GithubComponent.class**
```
@Component(modules = {GitHubModule.class, AppModule.class})
public interface GitHubComponent {
void inject(MainPresenterImpl presenter);
}
```
Inside the application class, i am created an `appcomponent` instance and also `githubcomponent` instance, that i use in the BaseActivity to create the `activitycomponent`.
And i inject the presenter inside `MainAcitivity that extends BaseActivity` and i get a null-pointer exception saying presenter is null.
Is my implementation incorrect? What could i be missing?
**EDIT:**
**GithubApp.class**
```
public class GitHubApp extends Application {
public static GitHubApp INSTANCE;
private AppComponent appComponent;
private GitHubComponent gitHubComponent;
@Override
public void onCreate() {
super.onCreate();
INSTANCE = this;
getAppComponent().inject(this);
}
public AppComponent getAppComponent() {
if (appComponent == null) {
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.gitHubModule(new GitHubModule())
.build();
}
return appComponent;
}
public GitHubComponent getGitHubComponent() {
if (gitHubComponent == null) {
gitHubComponent = DaggerGitHubComponent.builder()
.gitHubModule(new GitHubModule())
.build();
}
return gitHubComponent;
}
}
```
How i inject the presenter into the activity is as under:
BaseActivity.class has a method that returns the activity component
```
return DaggerActivityComponent.builder()
.appComponent(((GitHubApp)getApplication()).getAppComponent())
.gitHubComponent(((GitHubApp)getApplication()).getGitHubComponent())
.activityModule(new ActivityModule(this))
.build();
```
In the MainActivity.class i use it like this:
before `super.onCreate()` is called, call `getActivityComponent().inject(this);`
@Inject
MainPresenter mainPresenter is the variable declaration
**EDIT2:**
Changes suggested by Chisko and <NAME> work together, **as it is also required to change** the `inject(AppCompatActivity activity)` to `inject(MainActivity activity)`<issue_comment>username_1: You can use this for read session
```
this.get('session.data.currentUser')
```
handle that whatever you want.
app/router.js
```
Router.map(function() {
this.route('posts');
this.route('post', { path: '/post/:post_id' });
```
});
app/routes/index.js
```
import Ember from 'ember';
export default Ember.Route.extend({
afterModel(model, transition) {
if (model.get('length') === 1) {
this.transitionTo('post', model.get('firstObject'));
}
}
});
```
Use this
Upvotes: 0 <issue_comment>username_2: Use authenticated route mixin in your route, which should be accessible after authentication:
```
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
AuthenticatedRoute = Ember.Route.extend(AuthenticatedRouteMixin, {
// route you would like to redirect to after logout
authenticationRoute: "routes.login",
// ... your stuff ...
})
```
In root application route use also corresponding mixin:
```
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
ApplicationRoute = Ember.Route.extend(ApplicationRouteMixin, {
// route you would like to redirect to after login
routeAfterAuthentication: "routes.authenticated-route",
// ... your stuff
})
```
It depends on your needs, how you will use it. You can put it in every authenticated route, or for example you can put it in one route (eg. called "/auth") and put another authenticated routes into this route. Each of these routes will be also authenticated, your routing structure could look like this:
```
/
login
auth
alsoAuthenticatedRoute
someAuthenticatedDetailRoute
anotherAuthenticatedRoute
anotherAuthenticatedDetailRoute
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 922 | 2,512 | <issue_start>username_0: ```
#!bin/bash
file=txt.cfg
v4=45frsgf
n=24
ng=23jhjghg
for i in {1..3}
do
if ( $i == 3 );then
sed -i 's/host=.*/host = (\n(0x'$v4',0,'$n',0x'$ng',1,))/' $file
else
sed -i 's/host=.*/host = (\n(0x'$v4',0,'$n',0x'$ng',1,)),/' $file
done
```
On appending i get something like this in my file ..actual output
```
45frsgf,0,24,23jhjghg
45frsgf,0,24,23jhjghg,
45frsgf,0,24,23jhjghg,
```
Expecteed output:
```
45frsgf,0,24,23jhjghg,
45frsgf,0,24,23jhjghg,
45frsgf,0,24,23jhjghgif
```
i run a loop then on adding the last line it shouldnt add , and that line should come as last and not as first.
how to do it?<issue_comment>username_1: Use "\n" to denote newlines:
```
sed -r -i 's/vtemp =.*/vtemp = (\n\n\n (0'$v',0,'$n',0x'$g',1,))/' $file
```
And if you use double quotes for the outer quotes, you don't need the inner ones:
```
sed -r -i "s/vtemp =.*/vtemp = (\n\n\n (0$v,0,$n,0x$g,1,))/" $file
```
Upvotes: 0 <issue_comment>username_2: A `sed` script consists of editing commands of the following form:
```
[address[,address]]function
```
where `function` represents a single-character command verb from the list in [Editing Commands in sed](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html#tag_20_116_13_03), followed by any applicable arguments.
The command can be preceded by characters and/or characters. The function can be preceded by characters. These optional characters shall have no effect.
So essentially, `sed` scripts can be written in a single-line as
```
[address[,address]]function;[address[,address]]function;...
```
Or in a multi-line form
```
[address[,address]]function
[address[,address]]function
...
```
The function you implemented is the substitute function of the form `s/BRE/replacement/flags` where your replacement consists of multiple lines. And `sed` is unable to interpret this as a single command. You wrote:
```
s/vtemp =.*/vtemp = (
(0'$v',0,'$n',0x'$g',1,))/
```
but `sed` sees this as two separate commands
```
s/vtemp =.*/vtemp = (
(0'$v',0,'$n',0x'$g',1,))/
```
The first command has invalid syntax (hence the error). The second command also has invalid systax (btw. notice that I removed the leading spaces as `sed` does not interpret those!)
If you want to do a replacement with newline characters, you should use `\n` to indicate a new-line. Thus
```
s/vtemp =.*/vtemp = (\n\n (0'$v',0,'$n',0x'$g',1,))/
```
Upvotes: 2 |
2018/03/15 | 499 | 2,035 | <issue_start>username_0: Is it necessary to compulsory use autolayout to just use of stackview
suppose i have made whole project without autolayout,
now for particular screen i have to use the Stackview to equally divide the number of label inside the view.
is there is any solution for that..
**PROBLEM**
actually i have to customize one of my old project done without autolayout, Now i have to just modify one screen which does not require any constraint but just stackview like uitablecell with 8 label in each cell equally divided.
>
> I know we can do it by just calculating frame run time but is there is
> any other way to do it.
>
>
><issue_comment>username_1: The stack view uses Auto Layout to position and size its arranged views.
Although a stack view allows you to layout its contents without using Auto Layout directly, you still need to use Auto Layout to position the stack view, itself. In general, this means pinning at least two, adjacent edges of the stack view to define its position. Without additional constraints, the system calculates the size of the stack view based on its contents.
<https://developer.apple.com/documentation/uikit/uistackview>
Upvotes: 0 <issue_comment>username_2: Yes, it is necessary to position the stack view itself using Auto Layout
From the [Apple Documentation](https://developer.apple.com/documentation/uikit/uistackview):
>
> Although a stack view allows you to layout its contents without using
> Auto Layout directly, you still need to use Auto Layout to position
> the stack view, itself
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you set the stack view's `translatesAutoresizingMaskIntoConstraints` property to `true`, then you can set the stack view's `frame` and `autoresizingMask` to control the size and position of the stack view. Auto layout will automatically turn your settings into constraints for you.
The arranged subviews of the stack view must **not** have `translatesAutoresizingMaskIntoConstraints` set to `true`.
Upvotes: 2 |
2018/03/15 | 443 | 1,330 | <issue_start>username_0: Consider following code:
```
#include
#include
#include
class Foo;
class Foo {
public:
Foo(int i): id(i) {}
typename std::list>::iterator i2;
int id;
};
int main() {
std::list> l;
auto f1 = std::make\_shared(1);
f1->i2 = l.end();
l.insert(f1->i2, f1);
std::cout << f1->id << std::endl;
std::cout << l.size() << std::endl;
for (auto i: l) {
std::cout << i->id << std::endl;
}
auto t = f1->i2;
l.erase(t);
std::cout << l.size() << std::endl;
}
```
Executing these code will get an SIGSEGV at `l.erase(t)`,seems ListNode were destroyed before shared\_ptr decrease its ref\_count. Why?How to fix it?<issue_comment>username_1: After insert your `f1->i2` left `l.end()`. You try to erase `l.end()`, that is not allowed.
Fix is simple. Change the line where `insert` called:
```
f1->i2 = l.insert(f1->i2, f1);
```
Upvotes: 1 <issue_comment>username_2: Iterator,initialized before insert/remove operation, may be in an indeterminate state after the operation and should be updated again. Also you are trying to delete a node in the list through an iterator which itself is pointing to list.end(). For deleting the last element of a list, you can rather use `std::list.pop_back();`
```
auto t = f1->i2;
l.erase(--t); // Change this in your code - decrease the iterator
```
Upvotes: 0 |
2018/03/15 | 1,920 | 6,452 | <issue_start>username_0: I have a tableView and a UITextView inside it. I am trying to add data from JSON to the table view but it is not shrinking/expanding according to size. I have tried a lot of forums and methods.
The main problem is - if it starts expanding/shrinking with height, it stops shrinking/expanding and vice versa. Bot height and width are not working.
**This is because, when I set the trailing and leading constraints of the UITextView to the cell, it starts working with height but stops working with width. When I remove the leading/trailing constraints, the content of the UITextView goes beyond the screen and does not come as multiline i.e. does not expand with height.** I have tried -
[How do I size a UITextView to its content?](https://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content)
[How to resize table cell based on textview?](https://stackoverflow.com/questions/40034506/how-to-resize-table-cell-based-on-textview)
and a lot many like these.
A little of my code-
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Message") as! TextViewCell
cell.customTextView.textColor = UIColor.white
// Give a source to table view cell's label
cell.customTextView.text = requestResponseArr[indexPath.row]
cell.translatesAutoresizingMaskIntoConstraints = true
cell.sizeToFit()
if (indexPath.row % 2 == 0) {
cell.customTextView.backgroundColor = ConstantsChatBot.Colors.iMessageGreen
cell.customTextView.textAlignment = .right
} else {
cell.customTextView.backgroundColor = ConstantsChatBot.Colors.ButtonBlueColor
cell.customTextView.textAlignment = .left
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
```
And in viewDidLoad()-
```
override func viewDidLoad() {
// RandomEstimatedRowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
}
```
I do not want the textview to be editable. Please reply with swift as I am not familiar with Objective C. Thanks
EDIT: Custom cell code
```
class TextViewCell: UITableViewCell {
@IBOutlet weak var customTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
customTextView.isScrollEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
```
}<issue_comment>username_1: You need to disable `UItextView` Scrolling for that.
```
textView.isScrollingEnabled = false
```
and in the cell add top, bottom, right and left constraints of textview.
And add height constraint >= 10
[](https://i.stack.imgur.com/M9Dmh.png)
Upvotes: 0 <issue_comment>username_2: Disable UITextView `isScrollEnabled` is `false` inside `cellForRowAt`
[Demo Example](https://github.com/paresh1994/TextViewInsideTableView)
Upvotes: 1 <issue_comment>username_3: You need to set all four constraints for textview i.e. leading, trailing, top and bottom lets say all are set to 8 from margin.
It will look something like below:
[](https://i.stack.imgur.com/bUfLY.png)
check demo on GitHub [here](https://github.com/vanitaladkat/DemoTextViewInCell/tree/master)
Upvotes: 0 <issue_comment>username_4: I have tried with `UITextView` inside `UITableViewCell`.
**Constraints**
`UITextView`, top, bottom and right as 2, 2 and 5, Width as 50. `Font Size` as 13, `Alignment` as Center. Give `Outlet connection` for `Width constraints` as `txtVwWidthConst`
**UIViewController**
```
@IBOutlet weak var tblView: UITableView!
var textWidthHeightDict = [Int : CGSize]()
override func viewDidAppear(_ animated: Bool) {
stringValue = [0 : "qwer\nasdasfasdf", 1 : "qwe", 2 : "123123\nasdas\nwqe", 3 : "q\n3\n4", 4 : "klsdfjlsdhfjkhdjkshfjadhskfjhdjksfhkdjsahfjksdhfkhsdfhjksdfjkasklsdfjlsdhfjkhdjkshfjadhskfjhdjksfhkdjsahfjksdhfkhsdfhjksdfjkasklsdfjlsdhfjkhdjkshfjadhskfjhdjksfhkdjsahfjksdhfkhsdfhjksdfjkas"]
for i in 0.. self.tblView.frame.width
{
// IF STRING WIDTH GREATER THAN TABLEVIEW WIDTH
let multipleValue = textSize.width / self.tblView.frame.width
textSize.height = (textSize.height \* (multipleValue + 1.0))
textSize.width = self.tblView.frame.width
textWidthHeightDict[loopValue] = textSize
}
else
{
textSize.height = textSize.height + 10 //ADDING EXTRA SPACE
textSize.width = textSize.width + 10 //ADDING EXTRA SPACE
textWidthHeightDict[loopValue] = textSize
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(\_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stringValue.count
}
func tableView(\_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "table", for: indexPath) as! TblTableViewCell
cell.backgroundColor = cellBGColr[indexPath.row]
cell.txtVw.inputAccessoryView = toolBar
cell.txtVw.text = stringValue[indexPath.row]
cell.txtVw.tag = indexPath.row
cell.txtVwWidthConst.constant = (textWidthHeightDict[indexPath.row]?.width)!
cell.selectionStyle = .none
return cell
}
func tableView(\_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var heightVal = (textWidthHeightDict[indexPath.row])
return heightVal!.height + 8 //ADDING EXTRA SPACE
}
```
**UITableViewCell**
```
class TblTableViewCell: UITableViewCell {
@IBOutlet weak var txtVw: UITextView!
@IBOutlet weak var txtVwWidthConst: NSLayoutConstraint!
// TEXTVIEW WIDTH CONSTRAINTS
override func awakeFromNib() {
super.awakeFromNib()
}
}
```
**Output**
[](https://i.stack.imgur.com/uDm7T.png)
**Note**
`UITextView` only, we have to calculate String size. But, in `UILabel`, this concept is very simple. Let me know, if you have any queries.
Upvotes: 3 [selected_answer] |
2018/03/15 | 227 | 856 | <issue_start>username_0: Can I prevent the colour of the status bar becoming `colorPrimary`? I mean, I do not want to change the status bar colour, and leave it as it is (system default). I have searched Google for this, and the answer was hiding the status bar. But I do not want to hide it.
I also do not want to change the primary colour to that of the default colour of the status bar. I need the primary colour as it is for other things. I just do not want it to be applied to the status bar.
I know that was the default behaviour before Lollipop. Is this still possible after Lollipop?<issue_comment>username_1: This should work
```
<item name="android:statusBarColor">#000000</item>
```
Upvotes: 2 <issue_comment>username_2: In your application theme, set status bar color as below:
```
"YOUR\_COLOUR\_CODE"
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 420 | 1,491 | <issue_start>username_0: I am trying to hide and remove the space of the `MainUIView`.I tried to make the `MainUIView` `heightConstarint` to `0` . But it is not hiding the views inside them.
I want to hide all the view and labels inside the `MainUIView`.
hope you understand my problem.Thank you in advance
Here is my code
```
@IBOutlet weak var heightConstarint:NSLayoutConstraint!
//@IBOutlet weak var viewhide: UIView!
override func viewDidLoad() {
super.viewDidLoad()
heightConstarint.constant = 0
//self.viewhide.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
}
```
[](https://i.stack.imgur.com/VBjU7.png)<issue_comment>username_1: Updating Constraints will Never work in
**override func viewDidLoad(){}**
If you want to change constraints programmatically then you must put your code in
**override fun viewWillLayoutSubviews(){}**
So your code will look like
```
override func viewWillLayoutSubviews() {
clipToBounds = true
heightConstarint.constant = 0
//self.viewhide.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
}
```
Upvotes: 1 <issue_comment>username_2: I don't know updating constraints will work or not in `viewDidLoad`. But there are another constraints for `MainUIView`.
[](https://i.stack.imgur.com/0eqlI.png)
I think you should remove top or bottom space.
Upvotes: 0 |
2018/03/15 | 5,285 | 15,164 | <issue_start>username_0: I generate following structure for menu dynamically using recursive function.
```
* [Home](/en/)
* [Menu 1](/en/)
* [Menu 2](/en/menu2/)
+ Menu 2.1
+ Menu 2.2
* [Menu 3](/en/menu3/)
* [Menu 4](/en/menu4/)
* [Menu 5](/en/menu5)
+ Menu 5.1
+ Menu 5.2
* [Menu 6](/en/menu6/)
```
I want to generate same with saperate class for parent menu & sub menu as
```
* [Home](/en/)
* [Menu 1](/en/)
* [Menu 2](/en/menu2/)
+ Menu 2.1
+ Menu 2.2
* [Menu 3](/en/menu3/)
* [Menu 4](/en/menu4/)
* [Menu 5](/en/menu5)
+ Menu 5.1
+ Menu 5.2
* [Menu 6](/en/menu6/)
```
I need to add three different classes `nav parent-menu` `class="dropdown"` `class="sub-menu"`
**C# Code**
Not sure where i should should change the code to make it work.
```
private string GenerateMenu(DataRow[] menu, DataTable table, StringBuilder sb)
{
sb.AppendLine("");
if (menu.Length > 0)
{
foreach (DataRow dr in menu)
{
string menuName = dr["MenuName"].ToString();
string menuURL = dr["MenuURL"].ToString();
string line = string.Empty;
line = String.Format(@"* [" + menuName + "]( + menuURL + )", handler, menuName);
sb.Append(line);
string pid = dr["MenuId"].ToString();
string parentId = dr["MenuInheritance"].ToString();
DataRow[] subMenu = table.Select(String.Format("MenuInheritance = {0}", pid));
if (subMenu.Length > 0 && !pid.Equals(parentId))
{
var subMenuBuilder = new StringBuilder();
sb.Append(GenerateMenu(subMenu, table, subMenuBuilder));
}
sb.Append("
");
}
}
sb.Append("
");
return sb.ToString();
}
//Call Function
GenerateMobileUL(parentMenus, table, sbMobile);
```
**Table Structure**
```
MenuID
MenuName
MenuURL
MenuInheritance
MenuNewPage
```<issue_comment>username_1: **Copy And Paste and name it as Menu.css**
```css
#cssmenu {
position: relative;
background:#DCDCDC;
width:100%;
}
#cssmenu ul {
list-style: none;
padding: 0;
margin: 0;
line-height: 1;
}
#cssmenu > ul {
position: relative;
display: block;
background:Skyblue;
width: 100%;
}
#cssmenu:after,
#cssmenu > ul:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#cssmenu.align-right > ul > li {
float: right;
}
#cssmenu.align-center ul {
text-align: center;
}
#cssmenu.align-center ul ul {
text-align: left;
}
#cssmenu > ul > li {
display: inline-block;
position: relative;
margin: 0;
padding: 0;
}
#cssmenu > ul > #menu-button {
display: none;
}
#cssmenu ul li a {
display: block;
font-family:Times New Roman;
text-decoration: none;
}
#cssmenu > ul > li > a {
font-size: 16px;
font-weight: bold;
padding: 15px 10px;
color: Black;
text-transform: uppercase;
-webkit-transition: color 0.25s ease-out;
-moz-transition: color 0.25s ease-out;
-ms-transition: color 0.25s ease-out;
-o-transition: color 0.25s ease-out;
transition: color 0.25s ease-out;
}
#cssmenu > ul > li.has-sub > a {
padding-right: 32px;
}
#cssmenu > ul > li:hover > a {
color: #ffffff;
}
#cssmenu li.has-sub::after {
display: block;
content: "";
position: absolute;
width: 0;
height: 0;
}
#cssmenu > ul > li.has-sub::after {
right: 10px;
top: 20px;
border: 5px solid transparent;
border-top-color: #7a8189;
}
#cssmenu > ul > li:hover::after {
border-top-color: #ffffff;
}
#indicatorContainer {
position: absolute;
height: 12px;
width: 100%;
bottom: 0px;
overflow: hidden;
z-index: -1;
}
#pIndicator {
position: absolute;
height: 0;
width: 100%;
border: 12px solid transparent;
border-top-color: #2b2f3a;
z-index: -2;
-webkit-transition: left .25s ease;
-moz-transition: left .25s ease;
-ms-transition: left .25s ease;
-o-transition: left .25s ease;
transition: left .25s ease;
}
#cIndicator {
position: absolute;
height: 0;
width: 100%;
border: 12px solid transparent;
border-top-color: #2b2f3a;
top: -12px;
right: 100%;
z-index: -2;
}
#cssmenu ul ul {
position: absolute;
left: -9999px;
top: 70px;
opacity: 0;
-webkit-transition: opacity .3s ease, top .25s ease;
-moz-transition: opacity .3s ease, top .25s ease;
-ms-transition: opacity .3s ease, top .25s ease;
-o-transition: opacity .3s ease, top .25s ease;
transition: opacity .3s ease, top .25s ease;
z-index: 1000;
}
#cssmenu ul ul ul {
top: 37px;
padding-left: 5px;
}
#cssmenu ul ul li {
position: relative;
}
#cssmenu > ul > li:hover > ul {
left: auto;
top: 44px;
opacity: 1;
}
#cssmenu.align-right > ul > li:hover > ul {
left: auto;
right: 0;
opacity: 1;
}
#cssmenu ul ul li:hover > ul {
left: 170px;
top: 0;
opacity: 1;
}
#cssmenu.align-right ul ul li:hover > ul {
left: auto;
right: 170px;
top: 0;
opacity: 1;
padding-right: 5px;
}
#cssmenu ul ul li a {
width: 130px;
border-bottom: 0.5px solid #eeeeee;
padding: 10px 20px;
font-size: 14px;
color: Black;
background:#DCDCDC;
-webkit-transition: all .35s ease;
-moz-transition: all .35s ease;
-ms-transition: all .35s ease;
-o-transition: all .35s ease;
transition: all .35s ease;
}
#cssmenu.align-right ul ul li a {
text-align: right;
}
#cssmenu ul ul li:hover > a {
background: #f2f2f2;
color: #8c9195;
}
#cssmenu ul ul li:last-child > a,
#cssmenu ul ul li.last > a {
border-bottom: 0;
}
#cssmenu > ul > li > ul::after {
content: '';
border: 6px solid transparent;
width: 0;
height: 0;
border-bottom-color: #ffffff;
position: absolute;
top: -12px;
left: 30px;
}
#cssmenu.align-right > ul > li > ul::after {
left: auto;
right: 30px;
}
#cssmenu ul ul li.has-sub::after {
border: 4px solid transparent;
border-left-color: #9ea2a5;
right: 10px;
top: 12px;
-moz-transition: all .2s ease;
-ms-transition: all .2s ease;
-o-transition: all .2s ease;
transition: all .2s ease;
-webkit-transition: -webkit-transform 0.2s ease, right 0.2s ease;
}
#cssmenu.align-right ul ul li.has-sub::after {
border-left-color: transparent;
border-right-color: #9ea2a5;
right: auto;
left: 10px;
}
#cssmenu ul ul li.has-sub:hover::after {
border-left-color: #ffffff;
right: -5px;
-webkit-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
transform: rotateY(180deg);
}
#cssmenu.align-right ul ul li.has-sub:hover::after {
border-right-color: #ffffff;
border-left-color: transparent;
left: -5px;
-webkit-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
transform: rotateY(180deg);
}
@media all and (max-width: 800px), only screen and (-webkit-min-device-pixel-ratio: 2) and (max-width: 1024px), only screen and (min--moz-device-pixel-ratio: 2) and (max-width: 1024px), only screen and (-o-min-device-pixel-ratio: 2/1) and (max-width: 1024px), only screen and (min-device-pixel-ratio: 2) and (max-width: 1024px), only screen and (min-resolution: 192dpi) and (max-width: 1024px), only screen and (min-resolution: 2dppx) and (max-width: 1024px) {
#cssmenu {
width: auto;
}
#cssmenu.align-center ul {
text-align: left;
}
#cssmenu.align-right > ul > li {
float: none;
}
#cssmenu ul {
width: auto;
}
#cssmenu .submenuArrow,
#cssmenu #indicatorContainer {
display: none;
}
#cssmenu > ul {
height: auto;
display: block;
}
#cssmenu > ul > li {
float: none;
}
#cssmenu li,
#cssmenu > ul > li {
display: none;
}
#cssmenu ul ul,
#cssmenu ul ul ul,
#cssmenu ul > li:hover > ul,
#cssmenu ul ul > li:hover > ul,
#cssmenu.align-right ul ul,
#cssmenu.align-right ul ul ul,
#cssmenu.align-right ul > li:hover > ul,
#cssmenu.align-right ul ul > li:hover > ul {
position: relative;
left: auto;
top: auto;
opacity: 1;
padding-left: 0;
padding-right: 0;
right: auto;
}
#cssmenu ul .has-sub::after {
display: none;
}
#cssmenu ul li a {
padding: 12px 20px;
}
#cssmenu ul ul li a {
border: 0;
background: none;
width: auto;
padding: 8px 35px;
}
#cssmenu.align-right ul ul li a {
text-align: left;
}
#cssmenu ul ul li:hover > a {
background: none;
color: #8c9195;
}
#cssmenu ul ul ul a {
padding: 8px 50px;
}
#cssmenu ul ul ul ul a {
padding: 8px 65px;
}
#cssmenu ul ul ul ul ul a {
padding: 8px 80px;
}
#cssmenu ul ul ul ul ul ul a {
padding: 8px 95px;
}
#cssmenu > ul > #menu-button {
display: block;
cursor: pointer;
}
#cssmenu #menu-button > a {
padding: 12px 20px;
}
#cssmenu ul.open li,
#cssmenu > ul.open > li {
display: block;
}
#cssmenu > ul.open > li#menu-button > a {
color: #fff;
border-bottom: 0.5px solid rgba(150, 150, 150, 0.1);
}
#cssmenu ul ul::after {
display: none;
}
#cssmenu #menu-button::after {
display: block;
content: '';
position: absolute;
height: 3px;
width: 22px;
border-top: 0px solid #7a8189;
border-bottom: 0px solid #7a8189;
right: 20px;
top: 15px;
}
#cssmenu #menu-button::before {
display: block;
content: '';
position: absolute;
height: 3px;
width: 22px;
border-top: 0px solid #7a8189;
right: 20px;
top: 25px;
}
#cssmenu ul.open #menu-button::after,
#cssmenu ul.open #menu-button::before {
border-color: #fff;
}
}
```
**In form**
```
* [Admin](#)
+ Test1
* [Master](#)
+ test2
* [test](#)
+ Test2
- Test2-test
|
```
**Use For Has Sub else Avoid**
```
(function($) {
$(document).ready(function() {
$('#cssmenu').prepend('<div id="indicatorContainer"><div id="pIndicator"><div id="cIndicator"></div></div></div>');
var activeElement = $('#cssmenu>ul>li:first');
$('#cssmenu>ul>li').each(function() {
if ($(this).hasClass('active')) {
activeElement = $(this);
}
});
var posLeft = activeElement.position().left;
var elementWidth = activeElement.width();
posLeft = posLeft + elementWidth / 2 - 6;
if (activeElement.hasClass('has-sub')) {
posLeft -= 6;
}
$('#cssmenu #pIndicator').css('left', posLeft);
var element, leftPos, indicator = $('#cssmenu pIndicator');
$("#cssmenu>ul>li").hover(function() {
element = $(this);
var w = element.width();
if ($(this).hasClass('has-sub')) {
leftPos = element.position().left + w / 2 - 12;
}
else {
leftPos = element.position().left + w / 2 - 6;
}
$('#cssmenu #pIndicator').css('left', leftPos);
}
, function() {
$('#cssmenu #pIndicator').css('left', posLeft);
});
$('#cssmenu>ul').prepend('<li id="menu-button"><a>Menu</a></li>');
$("#menu-button").click(function() {
if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open');
}
else {
$(this).parent().addClass('open');
}
});
});
})(jQuery);
```
Upvotes: 1 <issue_comment>username_2: ```
Page Permission Comfig Form
User Type
Select user type
//page load function
$(document).ready(function () {
getusertype();
GetPagNameAll();
})
//get all page name in db menu and sub menu type display
function GetPagNameAll() {
$.ajax({
type: "POST",
url: "/PagePermission/PagePermission.aspx/getDisplayALLPageName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var jsdata = JSON.parse(msg.d);
// var SubMenu = jsdata.SubMenuList;
$.each(jsdata, function (key, value) {
$("#MailMenuList").val(value.mainmenulist);
$("#getlist").append('* ' + value.pagename)//onclick="checkSubMenufun(' + value.id + ');" onclick="check\_fun(\'' + value.id + ',' + value.SubMenuList +'\');"
//'
"' + value.pagename+'"'
var sub\_length=value.SubMenuList.length;
for (i = 0; i < sub\_length; i++) {
//'+ "' + value.pagename+'"
'
$("#getlist").append('
- ' + value.SubMenuList[i].pagename + '
')//onclick="checkUncheckMainMenufun(' + value.id + ',' + value.SubMenuList[i].id + ');"
}
'*';
});
},
failure: function (msg) {
alert("failure");
},
error: function (msg) {
alert("error");
}
});
}
//get drop down values in db
function getusertype() {
$.ajax({
type: "POST",
url: "/PagePermission/PagePermission.aspx/GetUserType",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#txtusertype').empty().append('Select user type');
var jsdata = JSON.parse(msg.d);
$.each(jsdata, function (key, value) {
$('#txtusertype').append('' + value.pagename + '');
});
//$(".side-menu").empty();
},
failure: function (msg) {
alert("failure");
},
error: function (msg) {
alert("error");
}
});
}
```
#region Select Drobdowm List
```
[WebMethod]
public static string GetUserType()
{
try
{
registerEntities1 db = new registerEntities1();
var usertype = db.user_type_table.Select(x => new { x.user_id, x.user_name }).ToList();
List obj = new List();
foreach (var append in usertype)
{
details objd = new details();
objd.pagename = append.user\_name;
objd.Sno = append.user\_id.ToString();
obj.Add(objd);
}
JavaScriptSerializer objsr = new JavaScriptSerializer();
return objsr.Serialize(obj);
//return "";
}
catch (Exception ex)
{
return "";
}
}
#endregion
#region display all page name in page load
[WebMethod]
public static string getDisplayALLPageName()
{
registerEntities1 db = new registerEntities1();
var main\_menu\_list = db.page\_name\_table.Select(x => new { x.page\_id, x.page\_name }).ToList();
var sub\_menu\_list = db.page\_name\_submenu.Select(x => new { x.page\_id, x.page\_name, x.main\_menu\_id }).ToList();
List MainMenuList = new List();
foreach (var main\_menu in main\_menu\_list)
{
List SubMenuList = new List();
mainMenu mainMenuDetails = new mainMenu();
foreach (var sub\_menu in sub\_menu\_list)
{
subMenu sunMenuDetails = new subMenu();
if (main\_menu.page\_id == sub\_menu.main\_menu\_id)
{
sunMenuDetails.id = sub\_menu.page\_id.ToString();
sunMenuDetails.pagename = sub\_menu.page\_name;
sunMenuDetails.menutype = "Sub menu";
//sunMenuDetails.submenulist = sub\_menu\_list.Count.ToString();
SubMenuList.Add(sunMenuDetails);
}
}
mainMenuDetails.id = main\_menu.page\_id.ToString();
mainMenuDetails.pagename = main\_menu.page\_name;
mainMenuDetails.menutype = "main Menu";
mainMenuDetails.SubMenuList = SubMenuList;
mainMenuDetails.mainmenulist = main\_menu\_list.Count.ToString();
MainMenuList.Add(mainMenuDetails);
}
JavaScriptSerializer objsr = new JavaScriptSerializer();
return objsr.Serialize(MainMenuList);
}
```
endregion
=========
Upvotes: -1 |
2018/03/15 | 247 | 919 | <issue_start>username_0: Following is the code which I'm using to upload file:
```
java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
```<issue_comment>username_1: You need to set correct permission for file created path. Simply you can set 777 file permission to the folder, But it is not the correct way to do. First you have to check the program running user & according that user you have to set the correct permission for that dir.
Upvotes: 0 <issue_comment>username_2: change permission of directory using command
```
chmod -R 777
```
if you want to change permission of subdirectories also
otherwise
```
chmod 777
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Your file does not have the permission to be opened.
You can change it by doing.
```
chmod +rwx filename
```
Upvotes: 0 |
2018/03/15 | 1,329 | 4,423 | <issue_start>username_0: I have an untidy DataFrame of Tweet objects. There are two columns that contain lists: `hashtags` and `expanded_urls`. I'm trying to follow tidy data principles by keeping only 1 value at a row/column index.
EDIT: This question was marked as a duplicate of [this answer](https://stackoverflow.com/questions/35491274/pandas-split-column-of-lists-into-multiple-columns), which simply splits the list into more columns. That doesn't work for me because there could be a variable number of hashtags in 1 tweet.
Here's a sample of my `tweet` DataFrame:
```
-----------------------------------------------------------
tweet_id | hashtags | expanded_urls
-----------------------------------------------------------
123 | ['lol','bff'] | ['fakeurl.com']
124 | [] | ['url1.io', 'url2.expanded.co']
```
There's two possible ways I could go about tidying this data.
**1: Simply add new rows to the DataFrame with almost all row contents copied over**:
```
---------------------------------------------
tweet_id | hashtag | expanded_url
---------------------------------------------
123 | 'lol' | 'fakeurl.com'
123 | 'bff' | 'fakeurl.com'
124 | '' | 'url1.io'
124 | '' | 'url2.expanded.io'
```
I don't think this would be very efficient, especially because there would be many insert/append operations. However, having a single DataFrame to pass into a single scikit-learn model would make things very simple.
**2: Create 2 new DataFrames:**
The first would be hashtags with their corresponding `tweet_id`s:
```
------------------
tweet_id | hashtag
------------------
123 | `lol`
123 | `bff`
```
The other would be urls with their corresponding `tweet_id`s:
```
------------------
tweet_id | url
------------------
123 | `fakeurl.com`
124 | `url1.io`
124 | `url2.expanded.co`
```
This seems cleaner, but I'm not entirely sure how I would modify the original DataFrame; would I just drop the corresponding columns and keep 3 separate tables? Is there a good way of merging these 3 DataFrames into 1, or would I have to do a separate lookup every time I wanted to know which hashtags are associated with a tweet?<issue_comment>username_1: I reassign over `df` to turn empty lists into lists of a single empty string
Both columns together
=====================
```
from itertools import product
df = df.applymap(lambda x: x if x else [''])
pd.DataFrame([
[t, h, e]
for t, h_, e_ in df.values
for h, e in product(h_, e_)
], columns=df.columns)
tweet_id hashtags expanded_urls
0 123 lol fakeurl.com
1 123 bff fakeurl.com
2 124 url1.io
3 124 url2.expanded.co
```
---
Or without itertools
```
df = df.applymap(lambda x: x if x else [''])
pd.DataFrame([
[t, h, e]
for t, h_, e_ in df.values
for h in h_ for e in e_
], columns=df.columns)
tweet_id hashtags expanded_urls
0 123 lol fakeurl.com
1 123 bff fakeurl.com
2 124 url1.io
3 124 url2.expanded.co
```
Separately
==========
```
pd.DataFrame(dict(
tweet_id=df.tweet_id.values.repeat(df.hashtags.str.len()),
hashtags=np.concatenate(df.hashtags.values)
), columns=['tweet_id', 'hashtags'])
tweet_id hashtags
0 123 lol
1 123 bff
```
---
```
pd.DataFrame(dict(
tweet_id=df.tweet_id.values.repeat(df.expanded_urls.str.len()),
expanded_urls=np.concatenate(df.expanded_urls.values)
), columns=['tweet_id', 'expanded_urls'])
tweet_id expanded_urls
0 123 fakeurl.com
1 124 url1.io
2 124 url2.expanded.co
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Assuming the index is on `tweet_id` (*if not you can with `.set_index()` method*), for approach 2, you can try:
```
df['hashtags'].apply(pd.Series).stack().reset_index(level=1, drop=True).to_frame('hashtag')
Result:
hashtag
tweet_id
123 lol
123 bff
```
Similarly for `expanded_urls`:
```
df['expanded_urls'].apply(pd.Series).stack().reset_index(level=1, drop=True).to_frame('url')
```
Result:
```
url
tweet_id
123 fakeurl.com
124 url1.io
124 url2.expanded.co
```
Upvotes: 1 |
2018/03/15 | 830 | 2,470 | <issue_start>username_0: hi i have this test data i want to get result something like this
```
na ===> not available
error ===> error
ok ===> ok
arr1 = ['na','na','ok','ok','na'] => na
arr2 = ['ok','ok','ok','ok','error'] => error
arr2 = ['ok','ok','ok','ok','ok'] => ok
```<issue_comment>username_1: I reassign over `df` to turn empty lists into lists of a single empty string
Both columns together
=====================
```
from itertools import product
df = df.applymap(lambda x: x if x else [''])
pd.DataFrame([
[t, h, e]
for t, h_, e_ in df.values
for h, e in product(h_, e_)
], columns=df.columns)
tweet_id hashtags expanded_urls
0 123 lol fakeurl.com
1 123 bff fakeurl.com
2 124 url1.io
3 124 url2.expanded.co
```
---
Or without itertools
```
df = df.applymap(lambda x: x if x else [''])
pd.DataFrame([
[t, h, e]
for t, h_, e_ in df.values
for h in h_ for e in e_
], columns=df.columns)
tweet_id hashtags expanded_urls
0 123 lol fakeurl.com
1 123 bff fakeurl.com
2 124 url1.io
3 124 url2.expanded.co
```
Separately
==========
```
pd.DataFrame(dict(
tweet_id=df.tweet_id.values.repeat(df.hashtags.str.len()),
hashtags=np.concatenate(df.hashtags.values)
), columns=['tweet_id', 'hashtags'])
tweet_id hashtags
0 123 lol
1 123 bff
```
---
```
pd.DataFrame(dict(
tweet_id=df.tweet_id.values.repeat(df.expanded_urls.str.len()),
expanded_urls=np.concatenate(df.expanded_urls.values)
), columns=['tweet_id', 'expanded_urls'])
tweet_id expanded_urls
0 123 fakeurl.com
1 124 url1.io
2 124 url2.expanded.co
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Assuming the index is on `tweet_id` (*if not you can with `.set_index()` method*), for approach 2, you can try:
```
df['hashtags'].apply(pd.Series).stack().reset_index(level=1, drop=True).to_frame('hashtag')
Result:
hashtag
tweet_id
123 lol
123 bff
```
Similarly for `expanded_urls`:
```
df['expanded_urls'].apply(pd.Series).stack().reset_index(level=1, drop=True).to_frame('url')
```
Result:
```
url
tweet_id
123 fakeurl.com
124 url1.io
124 url2.expanded.co
```
Upvotes: 1 |
2018/03/15 | 795 | 3,225 | <issue_start>username_0: I'm trying to pass a formatted string into my function, but when the email is sent the text does not appear line by line, which is what I want.
```
var bodySummary = nominatorName + "\n" + nominatorRegion
// Run email Cloud code
Parse.Cloud.run("sendEmail", {
toEmail: "<EMAIL>",
subject: "Email Test",
body: bodySummary
}).then(function(result) {
// make sure to set the email sent flag on the object
console.log("result :" + JSON.stringify(result));
}, function(error) {
// error
});
```
I'm using SendGrid and Parse Cloud Code to generate emails in my web app:
```
Parse.Cloud.define("sendEmail", function(request, response) {
// Import SendGrid module and call with your SendGrid API Key
var sg = require('sendgrid')('API_KEY');
// Create the SendGrid Request
var reqSG = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
personalizations: [
{
to: [
{
// This field is the "to" in the email
email: request.params.toEmail,
},
],
// This field is the "subject" in the email
subject: request.params.subject,
},
],
// This field contains the "from" information
from: {
email: '<EMAIL>',
name: 'Test',
},
// This contains info about the "reply-to"
// Note that the "reply-to" may be different than the "from"
reply_to: {
email: '<EMAIL>',
name: 'Test',
},
content: [
{
// You may want to leave this in text/plain,
// Although some email providers may accept text/html
type: 'text/plain',
// This field is the body of the email
value: request.params.body,
},
],
},
});
// Make a SendGrid API Call
sg.API(reqSG, function(SGerror, SGresponse) {
// Testing if some error occurred
if (SGerror) {
// Ops, something went wrong
console.error('Error response received');
console.error('StatusCode=' + SGresponse.statusCode);
console.error(JSON.stringify(SGresponse.body));
response.error('Error = ' + JSON.stringify(SGresponse.body));
}
else {
// Everything went fine
console.log('Email sent!');
response.success('Email sent!');
}
});
});
```
The end result email should look like this:
```
nominatorName
nominationRegion
```
Currently, it looks like this:
```
nominatorName nominatorRegion
```<issue_comment>username_1: There could be two ways to accomplish.
Using HTML Body
```
var bodySummary = nominatorName + "
" + nominatorRegion
```
Using newline escape characters
```
var bodySummary = nominatorName + "\r\n" + nominatorRegion
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You need to replace the line break character `\n` with the HTML line break .
For example:
```
var bodySummary = nominatorName + '
' + nominatorRegion;
```
Upvotes: 0 |
2018/03/15 | 1,034 | 2,988 | <issue_start>username_0: I have sql query like this where the input is `@year = 2017`
while the column format is `'2017-01-01 05:02:45.000'`. And I would like to tune this query because It has very long execution time.
```
DECLARE @Device_List VARCHAR(500) = 'MKV005, MKV007, NWTN01, NWTN03, QUEEN02, MKV009';
DECLARE @YEAR VARCHAR(20) = '2017'
SELECT MONTH(deduction_timestamp) as [Month],
ISNULL(sum(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog]
WHERE bus_id in (select * from fnSplit(@Device_List, ','))
and YEAR(deduction_timestamp) = ISNULL(@Year, YEAR(deduction_timestamp))
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]
```
and would like to do like this
```
SELECT MONTH(deduction_timestamp) as [Month],
ISNULL(sum(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog]
WHERE bus_id in (select * from fnSplit(@Device_List, ','))
and (deduction_timestamp) >= '@year-01-01 00:00:00' and
(deduction_timestamp) < '@year(plus one year)-01-01 00:00:00'
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]
```
But currently It doesn't work because of error
>
> Conversion failed when converting date and/or time from character
> string.
>
>
>
Can you guys help me? Really appreciate it. Thanks<issue_comment>username_1: I would re-write your first query as
```
DECLARE @Device_List VARCHAR(500) = 'MKV005, MKV007, NWTN01, NWTN03, QUEEN02, MKV009';
DECLARE @YEAR VARCHAR(20) = '2017'
SELECT MONTH(deduction_timestamp) as [Month],
COALESCE(SUM(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog] c
CROSS APPLY (
select * from fnSplit(@Device_List, ',')
where bus_id = c.bus_id
)
WHERE (@Year IS NOT NULL AND YEAR(c.deduction_timestamp) = @Year) OR
(@Year IS NULL)
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]
```
Use ANSI SQL Standard `COALESCE()` function instead of `ISNULL()`
Upvotes: 2 <issue_comment>username_2: You need to concatenate the year variable with the rest of your string, you can't embed it into the string.
```
deduction_timestamp < CONVERT(DATETIME, @year + '-01-01 00:00:00')
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```
May be you want the see the output for year 2017 or later then I do not understand why are you using (deduction_timestamp) < '@year-01-01 00:00:00'
Please check this query:
DECLARE @Device_List VARCHAR(500) = 'MKV005, MKV007, NWTN01, NWTN03, QUEEN02, MKV009';
DECLARE @YEAR VARCHAR(20) = '2017'
SELECT MONTH(deduction_timestamp) as [Month],
ISNULL(sum(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog]
WHERE bus_id in (select * from fnSplit(@Device_List, ','))
and year(deduction_timestamp) >= @year
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]
```
Upvotes: 0 |
2018/03/15 | 1,133 | 4,339 | <issue_start>username_0: When attempting to run a script, I am getting an error message.
Here is my script:
```
$saveto = "C:\scripts\Distribution Groups.txt"
filter get_member_recurse {
if($_.RecipientType -eq "MailUniversalDistributionGroup") {
Get-DistributionGroupMember -ResultSize "Unlimited" $_.Name | get_member_recurse
} else {
$output = $_.Name + " (" + $_.PrimarySMTPAddress + ")"
Write-Output $output
}
}
$DistributionGroup = Get-DistributionGroup | Sort-Object Name | ForEach-Object {
"`r`n$($_.DisplayName) ($($_.PrimarySMTPAddress))`r`n=============" | Add-Content $saveto
$distout = Get-DistributionGroupMember -ResultSize "Unlimited" $_.Name | get_member_recurse
Write-Output $distout | Sort-Object | Get-Unique | Add-Content $saveto
}
```
Error message:
```
Pipeline not executed because a pipeline is already executing. Pipelines cannot be executed concurrently.
+ CategoryInfo : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [], PSInvalidOperationException
+ FullyQualifiedErrorId : RemotePipelineExecutionFailed
Pipeline not executed because a pipeline is already executing. Pipelines cannot be executed concurrently.
+ CategoryInfo : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [], PSInvalidOperationException
+ FullyQualifiedErrorId : RemotePipelineExecutionFailed
Pipeline not executed because a pipeline is already executing. Pipelines cannot be executed concurrently.
+ CategoryInfo : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [], PSInvalidOperationException
+ FullyQualifiedErrorId : RemotePipelineExecutionFailed
```<issue_comment>username_1: Perhaps this is what you are looking for?
```
$saveto = 'C:\temp\Distribution Groups.txt'
function get_member_recurse {
Param([array]$Members)
foreach ($Member in $Members) {
if($Member.RecipientType -eq "MailUniversalDistributionGroup") {
get_member_recurse (Get-DistributionGroupMember -ResultSize "Unlimited" $Member.Name)
} else {
[array]$output += $($Member.DisplayName + " (" + $Member.PrimarySMTPAddress + ")")
}
}
return $output
}
$DistributionGroups = Get-DistributionGroup | Sort-Object Name
foreach ($dg in $DistributionGroups) {
"`n$($dg.DisplayName) ($($dg.PrimarySMTPAddress))`n=============" | Out-File -FilePath $saveto -Append
[array]$distout += get_member_recurse (Get-DistributionGroupMember -ResultSize "Unlimited" $dg.Name)
$distout = $distout | Sort -Unique
$distout | Out-File -FilePath $saveto -Append
}
```
Upvotes: 0 <issue_comment>username_1: Here's the same thing but with progress bars!! ;-)
```
$saveto = 'C:\temp\Distribution Groups.txt'
function get_member_recurse {
Param([array]$Members)
foreach ($Member in $Members) {
if($Member.RecipientType -eq "MailUniversalDistributionGroup") {
get_member_recurse (Get-DistributionGroupMember -ResultSize "Unlimited" $Member.Name)
} else {
[array]$output += $($Member.DisplayName + " (" + $Member.PrimarySMTPAddress + ")")
}
}
return $output
}
$DistributionGroups = Get-DistributionGroup | Sort-Object Name
foreach ($dg in $DistributionGroups) {
write-Progress -Activity "Parsing Distribution Groups Recursively - $($DistributionGroups.IndexOf($dg)) of $($DistributionGroups.Count)" -status "$($dg.DisplayName) ($($dg.PrimarySMTPAddress))" -PercentComplete ($DistributionGroups.IndexOf($dg) / $DistributionGroups.count*100)
"`n$($dg.DisplayName) ($($dg.PrimarySMTPAddress))`n=============" | Out-File -FilePath $saveto -Append
[array]$distout += get_member_recurse (Get-DistributionGroupMember -ResultSize "Unlimited" $dg.Name)
$distout = $distout | Sort -Unique
$distout | Out-File -FilePath $saveto -Append
}
```
Upvotes: 0 <issue_comment>username_2: Ran into this error recently, eventually discovered it comes from a bug in the `FOREACH` (or `|%{}` ) command
Easiest workaround is to wrap the objects just before they go into foreach
change this:
```
one-command|two-command|%{stuff}
```
to this:
```
@(one-command|two-command)|%{stuff}
```
the `@()` collects them into an array
Upvotes: 2 |
2018/03/15 | 514 | 1,698 | <issue_start>username_0: How can I loop values in controller send it to view in CodeIgniter
I have tried with below code
**Controller**
```
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
}
}
```
**View**
```
php
echo $d-invoice\_id;
?>
```
But data is not printing in the view.How can I print the values??<issue_comment>username_1: You Can't `foreach` and pass the data to view.
```
public function getdata()
{
$result = $this->Mdi_download_invoices->download_pdf_files(12);
$data['d'] = $result;
$this->load->view('download_all_invoices/pdf',$data);
}
```
>
> **Note:** Since you're using `echo $d->invoice_id;` check whether your [**result object**](https://www.codeigniter.com/userguide3/database/results.html) (`row`, `result`)
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: I think you are looking for this :
```
php
public function getdata()
{
$data = $this-Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
$this->load->view('download_all_invoices/pdf',$d);
}
}
?>
```
Upvotes: 1 |
2018/03/15 | 421 | 1,819 | <issue_start>username_0: I was wondering if there's a difference between, for example, using:
LENGTH var\_1 $12.;
INPUT var\_1 $;
vs
INPUT var\_1 : $12.;
when reading in standard input from datalines or an external file;<issue_comment>username_1: Both do the same job. @tom has detailed and nice answer
Upvotes: 0 <issue_comment>username_2: They are the same as long as the LENGTH or the INPUT statement is the first place that the SAS compiler sees VAR\_1 referenced and needs to decide what type and length to assign to it. Both will cause VAR\_1 to be defined as a character variable of length 12. The LENGTH statement will do it explicitly and the INPUT statement will do it as a side effect. SAS assumes that you wanted the type to be character since you used a character informat. It also assumes that you want the length to be same as the width on the informat. (Note that that you could reference the variable in a RETAIN statement before hand and SAS will not make the decision as to the type and length at that time.)
Both INPUT statements will read VAR\_1 in list mode because the second one includes the `:` modifier before the informat specification. So SAS will read the next word it sees (which depend on settings of DSD and TRUNCOVER options and whether the `&` modifier is used) into the VAR\_1, even if the next word is longer than 12 characters. When you read data using list mode instead of formatted mode then SAS will actually ignore the width of the informat and read the number of characters in the next word. So if the next word is longer than 12 characters the extra characters will be ignored.
Note that if you have already defined VAR\_1 as being a character variable then you do not need to add the `$` after it in the INPUT statement in your first case.
Upvotes: 3 [selected_answer] |
2018/03/15 | 627 | 2,410 | <issue_start>username_0: I have two sheets .
**sheet-1** contains names in column A like
1) Max
2) Sam
3) Ram
**sheet-2** also contains the name in column A but with some specific indicators in column B LIKE
COL"A" - 1) Max , 2) Sam, 3) Ram
COL"B" - 1 , 2, 1
so as you can see in **sheet-2** i have " 1" in COL"B" in front of Max and Ram in COL"A"
using this i want to mark values in front of names in **sheet-1**
eg-
in sheet-2 if i have " 1" in COL"B" in front of Max and Ram in COL"A" then mark Max and Ram in **sheet-1** COL"B" as "topper" and if it is 2 in case of Sam in **sheet-2** mark it as average in **sheet-1** COL "B" in front of Sam
is there any specific formula to do that ? i have searched but was unable to find it. it will be really helpful as i am new to this excel formulas and vba<issue_comment>username_1: Both do the same job. @tom has detailed and nice answer
Upvotes: 0 <issue_comment>username_2: They are the same as long as the LENGTH or the INPUT statement is the first place that the SAS compiler sees VAR\_1 referenced and needs to decide what type and length to assign to it. Both will cause VAR\_1 to be defined as a character variable of length 12. The LENGTH statement will do it explicitly and the INPUT statement will do it as a side effect. SAS assumes that you wanted the type to be character since you used a character informat. It also assumes that you want the length to be same as the width on the informat. (Note that that you could reference the variable in a RETAIN statement before hand and SAS will not make the decision as to the type and length at that time.)
Both INPUT statements will read VAR\_1 in list mode because the second one includes the `:` modifier before the informat specification. So SAS will read the next word it sees (which depend on settings of DSD and TRUNCOVER options and whether the `&` modifier is used) into the VAR\_1, even if the next word is longer than 12 characters. When you read data using list mode instead of formatted mode then SAS will actually ignore the width of the informat and read the number of characters in the next word. So if the next word is longer than 12 characters the extra characters will be ignored.
Note that if you have already defined VAR\_1 as being a character variable then you do not need to add the `$` after it in the INPUT statement in your first case.
Upvotes: 3 [selected_answer] |
2018/03/15 | 287 | 917 | <issue_start>username_0: **Ionic gallery album**
I can able to view all the images in grid format,if i select one among them,i need to start the ionic slide image from that..
**SAMPLE CODE**
```
![]()
```
**NOTE:**
images.imageUrl - array which contain all images<issue_comment>username_1: I would say that there are 2 options
1. simply you need make another array when user selects one.
and just use the array in template.
2. when user selects one, save the index number. and add condition in ngFor like below :
I hope this would be helpfule
```
```
or
```
...
```
Upvotes: 0 <issue_comment>username_2: >
> Need to start loop \*ngFor from given array index
>
>
>
```
![]()
```
Upvotes: 0 <issue_comment>username_3: You can call goToSlide() on your click event-
```
class MyPage {
@ViewChild(Slides) slides: Slides;
goToSlide() {
this.slides.slideTo(2, 500);
}
}
```
Upvotes: 1 |
2018/03/15 | 363 | 1,141 | <issue_start>username_0: I want to format RIGHT cells based on specific cells' value in a row
For example, in the picture, in row 1 I set: A1 = A, D1 = B and G1 = C then right cells of them will be formatted in different format.
In this same row, when we change position of A, B, C to another cell the format will be change accordingly.
I could not do on my own, sadly...:)!
Sample formating:
[](https://i.stack.imgur.com/vW49Y.png)<issue_comment>username_1: I would say that there are 2 options
1. simply you need make another array when user selects one.
and just use the array in template.
2. when user selects one, save the index number. and add condition in ngFor like below :
I hope this would be helpfule
```
```
or
```
...
```
Upvotes: 0 <issue_comment>username_2: >
> Need to start loop \*ngFor from given array index
>
>
>
```
![]()
```
Upvotes: 0 <issue_comment>username_3: You can call goToSlide() on your click event-
```
class MyPage {
@ViewChild(Slides) slides: Slides;
goToSlide() {
this.slides.slideTo(2, 500);
}
}
```
Upvotes: 1 |
2018/03/15 | 524 | 1,661 | <issue_start>username_0: I have a issue. I have a string that contains a pattern and if string contains that pattern then it should be stored inside an variable.
```
var pattern = new RegExp(/@([0-9]+)/i);
if(pattern.test('@2 ajshfd @32 asd')
// here i need to store the matched string inside a variable and replace it with another string.
```
for eg:- input:- @2 ajs @32 hfdasd output:- Hi ajs hello hfdasd
Need help. Thanks in advance.<issue_comment>username_1: Not clear what you are trying to do. But have you read about String.prototype.replace() ? Maybe you can find your answers while studying it.
Upvotes: -1 <issue_comment>username_2: Edit: updated based on question changes
You can try in 2 steps, first [`exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) and then [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
```js
let pattern = new RegExp(/@(\d+)/i)
let str = '@2 ajshfd @32 asd'
let arrOld = []
let arrNew = ['Hi', 'hello']
let m
do {
m = pattern.exec(str)
if (m) {
arrOld.push(m[1])
str = str.replace(pattern, arrNew.shift())
}
} while (m)
console.log(arrOld)
console.log(str)
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: If the string matches your pattern, you can split it with ***'] '***. This will create an array. You can pick up second value in that array and append ***'Hi '*** to it.
```js
var pattern = new RegExp(/@\[([0-9]+)\]/i);
var str = '@[2] ajshfdasd';
if(pattern.test(str)){
var name = 'Hi ' + str.split(/\] /)[1];
console.log(name)
}
```
Upvotes: 0 |
2018/03/15 | 896 | 3,112 | <issue_start>username_0: I have the following DF,
```
+-----+--------------+----------+
|level|var1 |var2 |
+-----+--------------+----------+
|1 |[id, id1] |[name] |
|2 |[add1] |[city1] |
|3 |[add2] |[city2] |
+-----+--------------+----------+
```
and I would like to store it as below,
```
val first = List(List("id","id1"), List("add1"), List("add2"))
val second = List(List("name"), List("city1"), List("city2"))
```
The logic is all the columns values should come as list of items,Please suggest me how can i achieve this.<issue_comment>username_1: You can simply use `collect_list` *inbuilt function* on each columns to collect as `Array[Array[String]]` and then do *type castings* to change them to `List[List[String]]` as below
**collect\_list**
```
import org.apache.spark.sql.functions._
val tempdf = df.select(collect_list("var1").as("var1"), collect_list("var2").as("var2"))
```
should give you
```
+---------------------------------------------------------------+--------------------------------------------------------------+
|var1 |var2 |
+---------------------------------------------------------------+--------------------------------------------------------------+
|[WrappedArray(id, id1), WrappedArray(add1), WrappedArray(add2)]|[WrappedArray(name), WrappedArray(city1), WrappedArray(city2)]|
+---------------------------------------------------------------+--------------------------------------------------------------+
```
**type casting and saving to variables**
```
val rdd = tempdf.collect().map(row => (row(0).asInstanceOf[Seq[Seq[String]]], row(1).asInstanceOf[Seq[Seq[String]]]))
val first = rdd(0)._1.map(x => x.toList).toList
//first: List[List[String]] = List(List(id, id1), List(add1), List(add2))
val second = rdd(0)._2.map(x => x.toList).toList
//second: List[List[String]] = List(List(name), List(city1), List(city2))
```
Upvotes: 1 <issue_comment>username_2: If you have the data frame look like bellow.
```
df.show()
// +-----+---------+-------+
// |level| var1| var2|
// +-----+---------+-------+
// | 1|[id, id1]| [name]|
// | 2| [add1]|[city1]|
// | 3| [add2]|[city2]|
// +-----+---------+-------+
```
and the data frame structure.
```
df.printSchema()
// root
// |-- level: integer (nullable = true)
// |-- var1: array (nullable = true)
// | |-- element: string (containsNull = true)
// |-- var2: array (nullable = true)
// | |-- element: string (containsNull = true)
```
You can collect and convert like this.
```
val first: List[List[String]] =
df.select("var1")
.collect()
.map(row =>
row(0).asInstanceOf[Seq[String]].toList).toList
// List(List(id, id1), List(add1), List(add2))
val second: List[List[String]] =
df.select("var2")
.collect()
.map(row =>
row(0).asInstanceOf[Seq[String]].toList).toList
// List(List(name), List(city1), List(city2))
```
Upvotes: 3 [selected_answer] |
2018/03/15 | 338 | 1,062 | <issue_start>username_0: [](https://i.stack.imgur.com/51zQ4.png)
I'm new to python pandas. Need some help with deleting a few rows where there are null values. In the screenshot, I need to delete rows where `charge_per_line == "-"` using python pandas.<issue_comment>username_1: If the relevant entries in Charge\_Per\_Line are empty (`NaN`) when you read into pandas, you can use `df.dropna`:
```
df = df.dropna(axis=0, subset=['Charge_Per_Line'])
```
If the values are genuinely `-`, then you can replace them with `np.nan` and then use `df.dropna`:
```
import numpy as np
df['Charge_Per_Line'] = df['Charge_Per_Line'].replace('-', np.nan)
df = df.dropna(axis=0, subset=['Charge_Per_Line'])
```
Upvotes: 7 [selected_answer]<issue_comment>username_2: Multiple ways
1. Use str.contains to find rows containing '-'
```
df[~df['Charge_Per_Line'].str.contains('-')]
```
2. Replace '-' by nan and use dropna()
```
df.replace('-', np.nan, inplace = True)
df = df.dropna()
```
Upvotes: 3 |
2018/03/15 | 793 | 2,255 | <issue_start>username_0: I'm trying to fetch below string from a content, which is part of a table row extracted from pdf.
```
$import re
$re.findall(r'\s\d+\s[Trillion$]+', '2 4334 Rigid Tall 54 Trillion somr text')
$[' 54 Trillion']
```
This is valid, but if string contains some invalid characters it returns empty list, instead I want it should throw an error.
```
$re.findall(r'\s\d+\s[Trillion$]+', '2 4334 Rigid Tall 5&_4 T×rillion somr text')
$[]
```
But it shouldn't throw an error if the text doesn't exist at all<issue_comment>username_1: I have created two reg-ex patterns
1. For matching exact result as we want
2. For matching results that have may or may not have special characters
We get results from both reg-x and dependent on the count of results we raise error.
Please check below code and demo [here](http://pythonfiddle.com/demo-for-strict-regex-python)
```
import re
def process(text):
result_a = re.findall(r'\d+\sTrillion',text)
result_b = re.findall(r'[@#$%^&+=]*\d+[@#$%^&+=]*\d*\s[@#$%^&+=]*T[@#$%^&+=]*r[@#$%^&+=]*i[@#$%^&+=]*l[@#$%^&+=]*l[@#$%^&+=]*i[@#$%^&+=]*o[@#$%^&+=]*n[@#$%^&+=]*',text)
if len(result_a)==0 and len(result_b)>0:
print('raise error here beacause ',result_b)
else:
print(result_a)
tests = ["2 4334 Rigid Tall 54 Trillion somr text","2 4334 Rigid Tall +54 Tri+llio@n somr text"]
for test in tests:
process(test)
```
Upvotes: 1 <issue_comment>username_2: Your regex `\s\d+\s[Trillion$]+` has one problem that it is using a character class `[...]` where each character is matched individually. So `[Trillion$]+` will also match `TTTT` or `$$$$$` also.
You need to remove character class and also use `.search` instead of `.findall` as in following examples:
```
import re
input = ['2 4334 Rigid Tall 54 Txrillion somr text', '4334 Rigid Tall 54 Trillion somr text']
reg = re.compile(r'\b\d+\s+Trillion\b')
for s in input:
res = reg.search(s)
if res:
print "Matched:", res.group(0), "::", s
else:
print "Didn't Match:", s
```
**Output:**
```
Didn't Match: 2 4334 Rigid Tall 54 Txrillion somr text
Matched: 54 Trillion :: 4334 Rigid Tall 54 Trillion somr text
```
[Code Demo](https://eval.in/982844)
Upvotes: 3 [selected_answer] |
2018/03/15 | 727 | 2,212 | <issue_start>username_0: I have an IOT project and want to use Druid as Time Series DBMS. Sometimes the IOT device may lose the network and will re-transfer the historical data and real-time data when reconnecting to the server. I know the Druid can ingest real-time data over http push/pull and historical data over http pull or KIS, but i can't find the document about ingesting historical data over http push.
Is there a way that i can send historical data into druid over http push?<issue_comment>username_1: I have created two reg-ex patterns
1. For matching exact result as we want
2. For matching results that have may or may not have special characters
We get results from both reg-x and dependent on the count of results we raise error.
Please check below code and demo [here](http://pythonfiddle.com/demo-for-strict-regex-python)
```
import re
def process(text):
result_a = re.findall(r'\d+\sTrillion',text)
result_b = re.findall(r'[@#$%^&+=]*\d+[@#$%^&+=]*\d*\s[@#$%^&+=]*T[@#$%^&+=]*r[@#$%^&+=]*i[@#$%^&+=]*l[@#$%^&+=]*l[@#$%^&+=]*i[@#$%^&+=]*o[@#$%^&+=]*n[@#$%^&+=]*',text)
if len(result_a)==0 and len(result_b)>0:
print('raise error here beacause ',result_b)
else:
print(result_a)
tests = ["2 4334 Rigid Tall 54 Trillion somr text","2 4334 Rigid Tall +54 Tri+llio@n somr text"]
for test in tests:
process(test)
```
Upvotes: 1 <issue_comment>username_2: Your regex `\s\d+\s[Trillion$]+` has one problem that it is using a character class `[...]` where each character is matched individually. So `[Trillion$]+` will also match `TTTT` or `$$$$$` also.
You need to remove character class and also use `.search` instead of `.findall` as in following examples:
```
import re
input = ['2 4334 Rigid Tall 54 Txrillion somr text', '4334 Rigid Tall 54 Trillion somr text']
reg = re.compile(r'\b\d+\s+Trillion\b')
for s in input:
res = reg.search(s)
if res:
print "Matched:", res.group(0), "::", s
else:
print "Didn't Match:", s
```
**Output:**
```
Didn't Match: 2 4334 Rigid Tall 54 Txrillion somr text
Matched: 54 Trillion :: 4334 Rigid Tall 54 Trillion somr text
```
[Code Demo](https://eval.in/982844)
Upvotes: 3 [selected_answer] |
2018/03/15 | 2,136 | 5,729 | <issue_start>username_0: I am trying to query two different tables (`CALL_HISTORY` and `HUB_DIRECTORY`) to find all the call records that are made between a 'hub store' and a 'spoke store'. Each call has a `CallID` field and an entry is made with the id of the store that initiated the call and then a separate entry is made for each store that receives the call, and these all have the id of the store that receives them. So they all have the same `CallID` but the stores id (`DID`) is different for each.
The problem is that not every call is between a hub and its spoke, so I need to filter it out to find only these records.
[Sample Call Data](https://i.stack.imgur.com/3hvWK.png)
```
RecordID | CallID | DID | CallDirection | StartTime
--------------------------------------------------------
1563486 | 255429 | 492 | Initiated | 1520870539
1563487 | 255429 | 849 | Received | 1520870539
1563484 | 255430 | 1098 | Initiated | 1520870562
1563485 | 255430 | 1098 | Received | 1520870562
1563482 | 255431 | 307 | Initiated | 1520870567
1563483 | 255431 | 1013 | Received | 1520870567
1563506 | 255432 | 1108 | Initiated | 1520870580
1563509 | 255432 | 1108 | Received | 1520870580
```
Here you see a sample of the calls, the `CallID` group highlighted is between a hub and its spoke and the rest are not. The hubs and spokes are linked together in the `HUB_DIRECTORY` like so:
[HUB\_DIRECTORY SAMPLE](https://i.stack.imgur.com/JrW6Z.png)
```
HubStore | HubDID | SpokeStore | SpokeDID
-----------------------------------------
4 | 37 | Store0004 | 37
4 | 37 | Store0522 | 470
7 | 1083 | Store0007 | 1083
7 | 1083 | Store1000 | 714
7 | 1083 | Store1055 | 759
12 | 38 | Store0012 | 38
12 | 38 | Store1063 | 758
13 | 45 | Store0013 | 45
13 | 45 | Store0337 | 296
13 | 45 | Store1012 | 724
```
The `HubDID` and `SpokeDID` fields are the same as the `DID` in `CALL_HISTORY`. So I'm looking to query for calls where the initiated call `DID` exists in the `HUB_DIRECTORY` table, as either a `HubDID` or a `SpokeDID`, and its `CallID` also has a record with a `DID` that matches with the appropriate hub/spoke.
My end goal would look like this:
```
HUB | Spoke | Initiated | Received
-----------------------------------------------
Store.0004 | Store.0522 | 304 | 723
```
I believe I will need to use a `UNION` to get the row with the hub or spoke but I am just unable to wrap my head around how this would be done.<issue_comment>username_1: As of now What I understand is like, You want to get data like how many call Received By Hub and How many call Initiated by Hub.
```
select
a.hubDID, a.CallDirection, count(a.CallDirection) ,
hb.SpokeDID, ch.CallDirection, count(ch.CallDirection)
from CALL_HISTORY ch inner join
(
select RecordID, CallID, DID, CallDirection, StartTime, h.HubStore , h.hubDID
from CALL_HISTORY c inner join HUB_DIRECTORY h on (c.DID = h.HubDID)
)
as a
on ch.CallID = a.CallID
and a.RecordID <> ch.RecordID
inner join HUB_DIRECTORY hb on hb.SpokeDID = ch.DID
```
Try here [Demo](http://rextester.com/YVOCS57423)
Grouped Data Query :
```
select
a.hubDID, a.CallDirection, count(a.CallDirection) ,
count(hb.SpokeDID),
ch.CallDirection, count(ch.CallDirection)
from CALL_HISTORY ch inner join
(
select distinct c.RecordID, c.CallID, c.DID, c.CallDirection, c.StartTime, c.DID as hubDID
from CALL_HISTORY c inner join HUB_DIRECTORY h on (c.DID = h.HubDID)
)
as a
on ch.CallID = a.CallID
and a.RecordID <> ch.RecordID
inner join HUB_DIRECTORY hb on hb.SpokeDID = ch.DID
group by a.hubDID, a.CallDirection,
ch.CallDirection
;
```
Without Group Data Query:
```
select
a.hubDID, a.CallDirection, count(a.CallDirection) ,
hb.SpokeDID,hb.SpokeDID,
ch.CallDirection, count(ch.CallDirection)
from CALL_HISTORY ch inner join
(
select distinct c.RecordID, c.CallID, c.DID, c.CallDirection, c.StartTime, c.DID as hubDID
from CALL_HISTORY c inner join HUB_DIRECTORY h on (c.DID = h.HubDID)
)
as a
on ch.CallID = a.CallID
and a.RecordID <> ch.RecordID
inner join HUB_DIRECTORY hb on hb.SpokeDID = ch.DID
group by a.hubDID, a.CallDirection,
hb.SpokeDID,
ch.CallDirection
;
```
Upvotes: 0 <issue_comment>username_2: I think this query will give you the results you want. It works on the limited sample data you provided.
```
select h1.hubstore, h1.hubdid,
h1.spokestore, h1.spokedid,
count(distinct if(c2.recordid is null or c1.did!=h1.hubdid, null, c1.recordid)) as initiated,
count(distinct if(c2.did!=h1.hubdid, null, c2.recordid)) as received
from hub_directory h1
left join (select * from call_history where calldirection='Initiated') c1
on c1.did=h1.hubdid or c1.did=h1.spokedid
left join (select * from call_history where calldirection='Received') c2
on c2.callid = c1.callid and c2.did=if(c1.did=h1.hubdid, h1.spokedid, h1.hubdid)
group by h1.hubstore, h1.spokestore
```
Based on the new sample data at your [fiddle](http://rextester.com/CATQPG68403), this query gives
```
hubstore spokestore initiated received
355 Store0355 0 0
355 Store0362 0 0
355 Store0655 0 0
357 Store0233 1 2
357 Store0357 0 0
360 Store0360 0 0
360 Store0868 0 0
360 Store1091 0 0
363 Store0363 0 0
363 Store1462 1 0
363 Store1507 1 0
363 Store2507 0 0
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 595 | 1,988 | <issue_start>username_0: I wanna append string to a text file at beginning and end of proc sql statment, I tried like below
```
libname DXZ 'libpath';
%macro processlogger(msg);
filename logfile '../Processlog/processlog.txt';
data _null_;
file logfile;
put "%superq(message)";
run;
%mend;
%processlogger ('Begin');
proc sql;
select * from DZ.NoofDaysin_Reje /* Mispelled name */
run;
%processlogger('End');
```
I seems to messing up in macro variable, is there any other way I can do this, Thanks<issue_comment>username_1: If you want to use a data step to append to a text file then you need to add the `MOD` keyword to the `FILE` statement.
If you want to print the value of a macro variable that might have quotes and other strange characters in a data step then it is probably best to use `symget()` to retrieve the value into a datastep variable and print that.
Make sure to reference the macro variable that you created `msg` and not some other macro variable `message`.
If you don't want quotes to be included in the value of a macro variable then do not add them.
```
%macro processlogger(msg);
data _null_;
file '../Processlog/processlog.txt' mod;
length message $32767 ;
message=symget('msg');
put message ;
run;
%mend;
%processlogger(Starting at %sysfunc(datetime(),datetime24.3));
%processlogger(Ending at %sysfunc(datetime(),datetime24.3));
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can also use [PRINTTO](http://support.sas.com/documentation/cdl/en/proc/61895/HTML/default/viewer.htm#a000146809.htm) to redirect your log to a text file. And you have the option to either append to the original file or replace. Example [here](http://documentation.sas.com/?docsetId=proc&docsetTarget=n1oardywxmmut7n1pol0zkj5u1ok.htm&docsetVersion=9.4&locale=en).
```
/*Redirect your log file*/
proc printto log='../Processlog/processlog.txt';
run;
/* Your Code Here */
/* Reset log path to default */
proc printto;
run;
```
Upvotes: 1 |
2018/03/15 | 2,688 | 7,461 | <issue_start>username_0: I am trying to make a switch button by using HTML elements. But I can't do animation for this. Here I have tried to use `transition` CSS3 property. The transition will work for some elements only and its doesn't work as expected for `switch-group:before` element. Is there any way to improve more animation to get an attractive one?. I have tried many links but this doesn't help with my code. I have attached code below,
```css
input[type=checkbox] {
display: none;
}
.switch-wrapper {
position: relative;
width: 70px;
border: 1px solid;
cursor: pointer;
height: 22px;
overflow: hidden;
}
.switch-on,
.switch-off {
display: block;
width: 50%;
float: left;
height: 100%;
transition: 0.5s;
}
.switch-on {
background-color: red;
margin-left: -100%;
text-indent: -18px;
line-height: 21px;
text-align: center;
}
.switch-off {
text-indent: 18px;
line-height: 21px;
text-align: center;
background-color: aliceblue;
}
.switch-group:before {
display: block;
content: "";
position: absolute;
height: 18px;
width: 18px;
margin: 2px;
background-color: #1b191e;
top: 0px;
}
.switch-group {
display: block;
position: relative;
height: 23px;
width: 200%;
user-select: none;
}
input[type=checkbox]:checked+.switch-group .switch-on {
margin-left: 0;
}
input[type=checkbox]:checked+.switch-group:before {
right: 50%;
}
```
```html
ON
OFF
```<issue_comment>username_1: Try this toggler
```css
.onoffswitch {
position: relative; width: 48px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
height: 24px; padding: 0; line-height: 24px;
border: 2px solid #F1F1F5; border-radius: 24px;
background-color: #F1F1F5;
transition: background-color 0.3s ease-in;
}
.onoffswitch-label:before {
content: "";
display: block; width: 24px; margin: 0px;
background: #FFFFFF;
position: absolute; top: 0; bottom: 0;
right: 22px;
border: 2px solid #F1F1F5; border-radius: 24px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label {
background-color: #2DC76D;
}
.onoffswitch-checkbox:checked + .onoffswitch-label, .onoffswitch-checkbox:checked + .onoffswitch-label:before {
border-color: #2DC76D;
}
.onoffswitch-checkbox:checked + .onoffswitch-label:before {
right: 0px;
}
.onoffswitch-checkbox:checked + .onoffswitch-label span.switch-off {
opacity: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label span.switch-on{
opacity: 1;
}
span.switch-off {
opacity: 1;
float: right;
font-size: 12px;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
}
span.switch-on {
position: absolute;
font-size: 12px;
top: 50%;
transform: translateY(-50%);
opacity: 0;
}
```
```html
ON
OFF
```
Upvotes: 2 <issue_comment>username_2: The transition will not work in your `:before` pseudo element because you are changing the `:before` `right` value from `auto`(by default) to `0`...transition does not works on `auto` values...
So try to use `left:0` at start and then change it value on click(when input checked) using `calc()` and also use `transtion:0.5s` in `:before` to make it animate
```css
input[type=checkbox] {
display: none;
}
.switch-wrapper {
position: relative;
width: 70px;
border: 1px solid;
cursor: pointer;
height: 22px;
overflow: hidden;
}
.switch-on,
.switch-off {
display: block;
width: 50%;
float: left;
height: 100%;
transition: 0.5s;
}
.switch-on {
background-color: red;
margin-left: -50%;
text-indent: -18px;
line-height: 21px;
text-align: center;
}
.switch-off {
text-indent: 18px;
line-height: 21px;
text-align: center;
background-color: aliceblue;
}
.switch-group:before {
display: block;
content: "";
position: absolute;
height: 18px;
width: 18px;
margin: 2px;
background-color: #1b191e;
top: 0px;
left: 0;
transition: 0.5s;
}
.switch-group {
display: block;
position: relative;
height: 23px;
width: 200%;
user-select: none;
}
input[type=checkbox]:checked+.switch-group .switch-on {
margin-left: 0;
}
input[type=checkbox]:checked+.switch-group:before {
left: calc(50% - 22px);
}
```
```html
ON
OFF
```
---
Or if you want your code to work in more intuitive way, try to use `opacity` instead of `margin`.
I have changed some of your css a little bit
```css
input[type=checkbox] {
display: none;
}
.switch-wrapper {
position: relative;
width: 70px;
border: 1px solid;
cursor: pointer;
height: 22px;
overflow: hidden;
}
.switch-on,
.switch-off {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
transition: 0.5s;
padding: 2px 6px;
}
.switch-on {
background-color: red;
line-height: 21px;
opacity: 0;
}
.switch-off {
line-height: 21px;
background-color: aliceblue;
opacity: 1;
text-align: right;
}
.switch-group:before {
display: block;
content: "";
position: absolute;
height: 18px;
width: 18px;
margin: 2px;
background-color: #1b191e;
top: 0px;
left: 0;
transition: 0.5s;
z-index: 99;
}
.switch-group {
display: block;
position: relative;
height: 23px;
user-select: none;
}
input[type=checkbox]:checked+.switch-group .switch-on {
opacity: 1;
}
input[type=checkbox]:checked+.switch-group .switch-off {
opacity: 0;
}
input[type=checkbox]:checked+.switch-group:before {
left: calc(100% - 22px);
}
```
```html
ON
OFF
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: **You Can Try This.. Or [visit This link For Details](https://proto.io/freebies/onoff/)**
```css
.onoffswitch {
position: relative; width: 90px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
display: block; width: 200%; margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
box-sizing: border-box;
}
.onoffswitch-inner:before {
content: "ON";
padding-left: 10px;
background-color: #34A7C1; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}
.onoffswitch-switch {
display: block; width: 18px; margin: 6px;
background: #FFFFFF;
position: absolute; top: 0; bottom: 0;
right: 56px;
border: 2px solid #999999; border-radius: 20px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
}
```
```html
```
Upvotes: 2 |
2018/03/15 | 697 | 2,445 | <issue_start>username_0: When I try to retrieve time from MySQL and set it to a `JLabel`, it gives me an error.
>
> java.sql.SQLException: Illegal hour value '50' for java.sql.Time type
> in value '50:51:05.
>
>
>
Can anyone suggest me how to fix this?
Code is as follows.
```
String sql = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(ot)))"
+ " FROM attendance"
+ " WHERE department = '"+department+"'"
+ " AND date BETWEEN '"+dateChooser1+"' AND '"+dateChooser2+"'";
st = con.createStatement();
rst = st.executeQuery(sql);
if(rst.next())
{
String time = rst.getString(1);
oTimeTemp.setText(time);
}
```<issue_comment>username_1: ```
// if you want to use time as label
// you can use oTimeTemp if Date type of java.util, this have both time and date
if(rst.next())
{
// this Time string need to cast in util time
String time = rst.getString(1);
String time = time ;
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
oTimeTemp.setText(date); // in this date we have the time
}
```
Upvotes: -1 <issue_comment>username_2: I solved it. Here is the code,
```
String sql = "SELECT SUM(TIME_TO_SEC(ot))"
+ " FROM attendance"
+ " WHERE department = '"+department+"'"
+ " AND date BETWEEN '"+dateChooser1+"' AND '"+dateChooser2+"'";
st = con.createStatement();
rst = st.executeQuery(sql);
if(rst.next())
{
String time = rst.getString(1);
Double dTime = Double.valueOf(time);
int intTime = (int) dTime.doubleValue();
String nTime = calculateTime(intTime);
oTimeTemp.setText(nTime);
}
private static String calculateTime(int totalSecs)
{
int hours = totalSecs / 3600;
int minutes = (totalSecs % 3600) / 60;
int seconds = totalSecs % 60;
String timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return timeString;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: There is a mysql bug , use it as follows it would work fine:
```
String sql = "SELECT concate(SEC_TO_TIME(SUM(TIME_TO_SEC(ot))),'')"
+ " FROM attendance"
+ " WHERE department = '"+department+"'"
+ " AND date BETWEEN '"+dateChooser1+"' AND '"+dateChooser2+"'";
```
Upvotes: 1 |
2018/03/15 | 741 | 2,878 | <issue_start>username_0: I have returned some raw JSON from an angular HTTPClient GET request and I am unsure how to now bind the properties of my JSON object to my html dynamically.
I would usually think to just store the returned JSON object into a variable and then reference it where I need it using dot notation, but Angular doesn't seem to work that way as I cannot set my http get request to a variable in ngOnInit and reference it.
I am using ngOnInit to initialize it when my Component loads and it is successfully logging to the console, but how do I get it binded INTO my html?
app.component.ts:
```
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Contacts';
constructor (private httpClient: HttpClient) {}
ngOnInit(): void {
this.httpClient.get('**URL PATH RETURNING JSON OBJECT**')
.subscribe((data) => {
console.log(data));
}
}
```
app.module.ts:
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
HTML:
```
{{ title }}
============
Favorite Contacts
* 
### {{ contact.name }}
{{ contact.companyName }}
---
```<issue_comment>username_1: Try like this :
```
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Contacts';
constructor (private httpClient: HttpClient) {}
ngOnInit(): void {
this.httpClient.get('**URL PATH RETURNING JSON OBJECT**')
.subscribe((data)=>{
this.contacts = data;//I have assigned data here inside subscription
console.log(data);
});
}
}
```
and reference `this.contacts` in same way you are doing in HTML
Upvotes: 1 [selected_answer]<issue_comment>username_2: You don't seem to have a `contacts` variable in your `app.component.ts`.
This is what it should look like:
```
export class AppComponent {
title = 'Contacts';
contacts: any[]; // Add variable
constructor (private httpClient: HttpClient) {}
ngOnInit(): void {
this.httpClient.get('**URL PATH RETURNING JSON OBJECT**')
.subscribe((data)=>{
console.log(data);
this.contacts = data; // Once you get the data, assign the data returned to contacts
});
}
}
```
Upvotes: 2 |
2018/03/15 | 592 | 1,974 | <issue_start>username_0: I am new to `Angular JS`, when I tried to get and print out some `JSON` data using `$scope` variable, but double curly braces just don't work as i thought it would do.
HTML:
```
YYQAngularJS
haha {{ p.name }}
```
JS:
```
$(window).on("load",function () {
var $myApp = angular.module('myApp',[]);
$myApp.controller('myController',function ($scope) {
$scope.p =
{
"name":"a",
"id":"1"
}
});
});
```
result:
haha {{ p.name }}
Update:
HTML file:
```
YYQAngularJS
haha {{ p.name }}
```
JS file:
```
var $myApp = angular.module('myApp',[]);
$myApp.controller('myController',function ($scope) {
$scope.p =
{
"name":"a",
"id":"1"
}
});
```
And now i got this error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.<issue_comment>username_1: * Remove `$(window).on("load",function () {`
* Change `type="javascript"` to `type="text/javascript"` in all tags
Angularjs will load it before DOM is loaded
Here is the working code
```html
YYQAngularJS
haha {{ p.name }}
var $myApp = angular.module('myApp', []);
$myApp.controller('myController', function($scope) {
$scope.p = {
"name": "a",
"id": "1"
}
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: `$(window).on('load', () => {})` is causing conflict with your angular app.
```js
var $myApp = angular.module('myApp', []);
$myApp.controller('myController', function($scope){
$scope.p = {
"id": 1,
"name": "<NAME>"
};
});
```
```html
YYQAngularJS
haha {{ p.name }}
```
Upvotes: 0 |
2018/03/15 | 567 | 1,543 | <issue_start>username_0: I have a fol df:
```
Zip | Name | id |
abc | xyz | 1 |
def | wxz | 2 |
abc | wex | 3 |
bcl | rea | 4 |
abc | txc | 5 |
def | rfx | 6 |
abc | abc | 7 |
```
I need to group all the names that contain 'x' based on same Zip using scala
Desired Output:
```
Zip | Count |
abc | 3 |
def | 2 |
```
Any help is highly appreciated<issue_comment>username_1: You want to groupBy bellow data frame.
```
+---+----+---+
|zip|name| id|
+---+----+---+
|abc| xyz| 1|
|def| wxz| 2|
|abc| wex| 3|
|bcl| rea| 4|
|abc| txc| 5|
|def| rfx| 6|
|abc| abc| 7|
+---+----+---+
```
then you can simply use `groupBy` function with passing column parameter and followed by `count` will give you the result.
```
val groupedDf: DataFrame = df.groupBy("zip").count()
groupedDf.show()
// +---+-----+
// |zip|count|
// +---+-----+
// |bcl| 1|
// |abc| 4|
// |def| 2|
// +---+-----+
```
Upvotes: 0 <issue_comment>username_2: As @Shaido mentioned in the comment above, all you need is `filter`, `groupBy` and *aggregation* as
```
import org.apache.spark.sql.functions._
fol.filter(col("Name").contains("x")) //filtering the rows that has x in the Name column
.groupBy("Zip") //grouping by Zip column
.agg(count("Zip").as("Count")) //counting the rows in each groups
.show(false)
```
and you should have the desired output
```
+---+-----+
|Zip|Count|
+---+-----+
|abc|3 |
|def|2 |
+---+-----+
```
Upvotes: 2 [selected_answer] |
2018/03/15 | 259 | 755 | <issue_start>username_0: ```
$a=ls | grep test | wc -l
```
I want to store wc -l count in a variable, I don't shell scripting<issue_comment>username_1: Just use backtick (`)
```
$ a=`ls | grep test | wc -l`
$ echo $a
1
```
Upvotes: 1 <issue_comment>username_2: On bash like shells (zsh etc.), you can do
```
a=$(ls | grep test | wc -l)
```
You can get the value back using `$a`. (e.g. `echo $a`).
The older syntax was to use backticks like so
```
a=`ls | grep test | wc -l`
```
but this is best avoided. It doesn't nest and has a few other problems as well.
Upvotes: 3 [selected_answer]<issue_comment>username_3: You can use something like the below example.
```
a=$(ls | grep test | wc -l)
echo $a
```
Lemme know if it works.
Upvotes: 0 |
2018/03/15 | 323 | 1,242 | <issue_start>username_0: I currently have 3 fields in a table:
id, client\_id, username
The client\_id and username combination should never be duplicates. The original thought was to use a composite primary key for client\_id and username. This however did not allow my "ID" field to auto increment as it was not primary.
If I were to add my ID to my composite, there would never be a duplicate as the ID is always changing.
The latest I have is a basic:
```
"INSERT IGNORE INTO users (client_id, username) VALUES(cid,username)"
```
Is there a way to check that client\_id and username are a match for any previous records, and if they are, then don't add them? The above does not work.<issue_comment>username_1: you can add a unique key by combination of client\_id ,username in your table .
Upvotes: 1 <issue_comment>username_2: ```
ALTER TABLE yourTable
ADD CONSTRAINT constraint_name UNIQUE ( client_id ,username);
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You can create the table like this so that client\_id and username will'nt get matched for any previous records...
```
CREATE TABLE table1 (
id int,
client_id int,
username varchar(255),
PRIMARY KEY('id','client_id')
);
```
Upvotes: 0 |
2018/03/15 | 531 | 1,855 | <issue_start>username_0: As the title says I am trying to create a function that achieves it.
Here is my JavaScript:
```
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
clickCount++;
clickCount = clickCount % bgColors.length;
}
```
When the function `changeBg()` is called from my html it does nothing and I'm scratching my head trying to understand why.<issue_comment>username_1: There are some typos in your code.
```js
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changeBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
//---^------ missing e
clickCount++;
clickCount = clickCount % colors.length;
// array variable name ---^^^^^^---
// you can combine the above 2 lines if needed
// clickCount = ++clickCount % colors.length;
// or all 3 lines
// changeBgColor(colors[ clickCount++ % colors.length]);
}
```
```html
click
```
Upvotes: 2 <issue_comment>username_2: You have a spelling mistake while declaring funtion 'changBgColor'. You are missing an 'e'.
Also you are doing ***clickCount % bgColors.length;***, bgColors is not defined here. use ***colors.length*** instead
```js
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changeBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
clickCount++;
clickCount = clickCount % colors.length;
}
```
```html
change color
```
Upvotes: 0 |
2018/03/15 | 898 | 3,477 | <issue_start>username_0: I am taking a business applications course in Swift and am having trouble running my code. I think I have all the correct code in place to run this. I have a JSON file that I have to import into the app and push the data from the json file into the tableView. Something is breaking in the "func tableView", but I cant figure it out. Any help is appreciated :)
[I added a screenshot of my code, as well as the main.storyboard](https://i.stack.imgur.com/1Oms9.png)
```
import UIKit
struct Movie : Decodable {
let MOVIENAME : String
let DIRECTORNAME : String
}
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
//indicates this is an array of the structure 'Movie'
var movies = [Movie]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let myCell = movieTableView.dequeueReusableCell(withIdentifier:
"movieTable")
myCell?.textLabel?.text = movies[indexPath.row].MOVIENAME
myCell?.detailTextLabel?.text = movies[indexPath.row].DIRECTORNAME
return myCell!
}
@IBOutlet weak var movieTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// construct path to the file, this tells the system the name of the file and the file type JSON
let path = Bundle.main.path(forResource: "movies", ofType: "json")
let url = URL(fileURLWithPath: path!) //creating url of the file, add "!" to unwrap the path
do {
//'try" is a security measure that basically says, if we dont get successfully create data through the url
let data = try Data(contentsOf: url)
self.movies = try JSONDecoder().decode([Movie].self, from: data)
for eachMovie in self.movies {
print(eachMovie.MOVIENAME)
}
} catch {
print("JSON Error.")
}
movieTableView.delegate = self
movieTableView.dataSource = self
}
}
```<issue_comment>username_1: There are some typos in your code.
```js
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changeBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
//---^------ missing e
clickCount++;
clickCount = clickCount % colors.length;
// array variable name ---^^^^^^---
// you can combine the above 2 lines if needed
// clickCount = ++clickCount % colors.length;
// or all 3 lines
// changeBgColor(colors[ clickCount++ % colors.length]);
}
```
```html
click
```
Upvotes: 2 <issue_comment>username_2: You have a spelling mistake while declaring funtion 'changBgColor'. You are missing an 'e'.
Also you are doing ***clickCount % bgColors.length;***, bgColors is not defined here. use ***colors.length*** instead
```js
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changeBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
clickCount++;
clickCount = clickCount % colors.length;
}
```
```html
change color
```
Upvotes: 0 |
2018/03/15 | 523 | 1,910 | <issue_start>username_0: Facing error of undefined offset. If I remove `$ship = $ship->toArray();` then the data of a particular table becomes N/A. I Need to show the name under that particular table.
Controller
```
->addColumn('captain', function ($ship) {
$ship = $ship->toArray();
$user = User::pluck('name', 'id')->toArray();
if (!empty($ship['company_employee'])) {
$captain = $user[($ship['company_employee']['user_id'])];
} else {
$captain = 'N/A';
}
return $captain;
})
```<issue_comment>username_1: There are some typos in your code.
```js
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changeBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
//---^------ missing e
clickCount++;
clickCount = clickCount % colors.length;
// array variable name ---^^^^^^---
// you can combine the above 2 lines if needed
// clickCount = ++clickCount % colors.length;
// or all 3 lines
// changeBgColor(colors[ clickCount++ % colors.length]);
}
```
```html
click
```
Upvotes: 2 <issue_comment>username_2: You have a spelling mistake while declaring funtion 'changBgColor'. You are missing an 'e'.
Also you are doing ***clickCount % bgColors.length;***, bgColors is not defined here. use ***colors.length*** instead
```js
var clickCount = 0;
var colors = ["red", "blue", "green"];
function changeBgColor(color) {
var bodyTag = document.getElementsByTagName("body");
bodyTag[0].style.backgroundColor = color;
}
function changeBg() {
changeBgColor(colors[clickCount]);
clickCount++;
clickCount = clickCount % colors.length;
}
```
```html
change color
```
Upvotes: 0 |
2018/03/15 | 2,157 | 8,397 | <issue_start>username_0: In my project I wanted to read data from a file and update the DataGridView to a simple List. I wanted this so that the list can be updated at run time and then upon save wanted the final content of the list to be updated to a file.
In most of the solutions seen on google search I came up with examples of how to use a DatagridView with Database connection used to update the DatagridView. for Insert, Update and Delete operations. Lot of suggestions for my answer included adding INotifyProperty and IBindingList based impelementations which are probably an overkill.
I only aim to post my solution which involves using Datagridview to update a list. The code snippet used here is part of a huge project where updating the data from Datagridview to the List and back was a very big challenge due to initial impelementation with Database, whose dependency needed to be removed.
At the point of posting this question, I have a solution to my problem. To arrive at this problem I have taken bits and pieces of suggestions from various previous questions. I am not looking for suggestions in comments. If anyone wants to show me better way to solve this problem, please post an answer with working code.<issue_comment>username_1: Here is an example where I have used the DatagridView to perform Insert Update and Delete on a List (List of Class objects `PersonState`).
The DatagridView’s Datasource needs to contain a DataTable, to bridge this gap, I have used a function named `ConvertToDatatable()`.
As my starting point I began with a project suggested on another [link](https://www.c-sharpcorner.com/UploadFile/1e050f/insert-update-and-delete-record-in-datagridview-C-Sharp/) by <NAME>.
[](https://i.stack.imgur.com/fRQJ5.png)
Using the following code:
```
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
namespace InsertUpdateDelete {
public partial class Form1 : Form {
public class PersonState {
public string Name { get; set; }
public string State { get; set; }
}
public List listOfPersonState;
public Form1() {
InitializeComponent();
listOfPersonState = new List();
}
//Display Data in DataGridView
private void DisplayData() {
DataTable dt = new DataTable();
dt = ConvertToDatatable();
dataGridView1.DataSource = dt;
}
//Clear Data
private void ClearData() {
txt\_Name.Text = "";
txt\_State.Text = "";
}
public DataTable ConvertToDatatable() {
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("State");
foreach (var item in listOfPersonState) {
var row = dt.NewRow();
row["Name"] = item.Name;
row["State"] = item.State;
dt.Rows.Add(row);
}
return dt;
}
private void AddToList(string text1, string text2) {
listOfPersonState.Add(new PersonState { Name = text1, State = text2 });
}
private void UpdateToList(string text1, string text2) {
int index = dataGridView1.SelectedRows[0].Index;
listOfPersonState[index] = new PersonState { Name = text1, State = text2 };
}
private void DeleteToList() {
int index = dataGridView1.SelectedRows[0].Index;
listOfPersonState.RemoveAt(index);
}
private void btn\_Insert\_Click(object sender, EventArgs e) {
if (txt\_Name.Text != "" && txt\_State.Text != "") {
AddToList(txt\_Name.Text, txt\_State.Text);
//MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
} else {
MessageBox.Show("Please Provide Details!");
}
}
private void btn\_Update\_Click(object sender, EventArgs e) {
if (txt\_Name.Text != "" && txt\_State.Text != "") {
if (dataGridView1.SelectedRows != null && dataGridView1.SelectedRows.Count > 0) {
UpdateToList(txt\_Name.Text, txt\_State.Text);
//MessageBox.Show("Record Updated Successfully");
DisplayData();
ClearData();
}
} else {
MessageBox.Show("Please Select Record to Update");
}
}
private void btn\_Delete\_Click(object sender, EventArgs e) {
if (dataGridView1.SelectedRows != null && dataGridView1.SelectedRows.Count > 0) {
DeleteToList();
//MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
} else {
MessageBox.Show("Please Select Record to Delete");
}
}
private void dataGridView1\_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
FillInputControls(e.RowIndex);
}
private void dataGridView1\_CellClick(object sender, DataGridViewCellEventArgs e) {
FillInputControls(e.RowIndex);
}
private void FillInputControls(int Index) {
if (Index > -1) {
txt\_Name.Text = dataGridView1.Rows[Index].Cells[0].Value.ToString();
txt\_State.Text = dataGridView1.Rows[Index].Cells[1].Value.ToString();
}
}
}
}
```
**Learnings:**
1. Observe that I have used propertis in the class.
Instead of using:
```
public class PersonState {
public string Name;
public string State;
}
```
I have used:
```
public class PersonState {
public string Name { get; set; }
public string State { get; set; }
}
```
For some reason, the former does not work when trying to assing values.
2. I have made the list of objects a class variable so that all
functions can access that list directly instead of it being passed
around as a parameter.
`public List listOfPersonState;`
3. I replaced the logic to Insert, Update and Delete to a DB, to Insert
Update and Delete to a List.
```
private void AddToList(string text1, string text2) {
listOfPersonState.Add(new PersonState { Name = text1, State = text2 });
}
private void UpdateToList(string text1, string text2) {
int index = dataGridView1.SelectedRows[0].Index;
listOfPersonState[index] = new PersonState { Name = text1, State = text2 };
}
private void DeleteToList() {
int index = dataGridView1.SelectedRows[0].Index;
listOfPersonState.RemoveAt(index);
}
```
Note: I am assigning the Grid directly from the List, so my Grid and my List always have the same index because I am using the Display function to ensure this on Insert, update and delete Button operations.
```
private void DisplayData() {
DataTable dt = new DataTable();
dt = ConvertToDatatable();
dataGridView1.DataSource = dt;
}
public DataTable ConvertToDatatable() {
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("State");
foreach (var item in listOfPersonState) {
var row = dt.NewRow();
row["Name"] = item.Name;
row["State"] = item.State;
dt.Rows.Add(row);
}
return dt;
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: So after reading, you have a sequence of MyData objects. You want to display all MyData objects (or a subsection) in a DataGridView.
Operators may change the displayed values, add some new rows, or delete rows. Some columns may be readonly and can't be changed
After pressing the OK-button, you want to read all MyData objects from the DataGridView and Save them in a file.
Most of your work can be done using the forms designer.
* Open your form class in the designer
* Drag a DataGridView on this form
* Drag a BindingSource on this form
* Right click BindingSource and select properties
* Click in the properties window in DataSource on the arrow on the right
* If MyData is not visible there, select Add Project Data Source
* In the new window **select object**
* Select the added data source as DataSource of your BindingSource
* In the properties of DataGridView, assign your bindingSource to the DataSource
And suddenly: your DataGridView has the columns of the public properties of MyData. And magically, the columns have the correct type. They are able to display the values. Readonly properties have readonly Columns, read-write properties are editable.
To display your data:
```
void FillDataGridView(IEnumerable dataToDisplay)
{
this.bindingSource1.DataSource = new BindingList(dataToDisplay.ToList();
}
```
To read all data after editing
```
IEnumerable ReadDataGridView()
{
return this.bindingSource1.List.Cast();
}
```
This enables the operator to add and delete rows and to edit the values.
If you don't want the operator to do this, adjust the DataGridView properties
If the displayed values of the columns are not to your liking, edit the column properties (different header text, different display format, different backgroundcolor etc)
Upvotes: 2 |
2018/03/15 | 418 | 1,546 | <issue_start>username_0: Does the Azure CLI SDK use the Azure Rest API internally? And if so any further details on how these relate to each other internally would be great.<issue_comment>username_1: Yes, you are right. Azure CLI uses Azure Rest APi.
If you use `--debug`, you will find the API the command use. For example:
```
az vm list --debug
```
Yes, as Johan said, Azure Power Shell/CLI, SDK all call Azure Rest API. If you use debug mode, you could see the API. More information about Azure Rest API, you could check this [link](https://learn.microsoft.com/en-us/rest/api/).
Upvotes: 3 <issue_comment>username_2: Each service in Azure exposes a set of APIs. For managing/creating/updating your resources (e.g. [creating a Virtual Machine](https://learn.microsoft.com/en-us/rest/api/compute/virtualmachines/createorupdate)), these are REST calls. Note: Other services may use non-HTTP/REST APIs (e.g. AMQP for [Azure Service Bus](https://azure.microsoft.com/en-us/services/service-bus/)).
While you can use your favorite HTTP networking stack or utility (e.g. curl, postman etc.) to make HTTP/REST calls, Microsoft publishes a set of SDKs to make things easier to develop applicationsin various languages.
The [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest) happens to be implemented in [python](https://python.org), and thus makes use of the [Azure Python SDKs](http://azure-sdk-for-python.readthedocs.io/en/latest/) to get its work done.
There is no separate Azure **CLI** SDK, however.
Upvotes: 2 |
2018/03/15 | 450 | 1,629 | <issue_start>username_0: I was wondering if there was a way to select all text on a web page, and copy it to clipboard on button click.
I have a PHP script that `echo`s the output of `dmesg` on my server, and I want a way to copy all text on button click.<issue_comment>username_1: Yes, you are right. Azure CLI uses Azure Rest APi.
If you use `--debug`, you will find the API the command use. For example:
```
az vm list --debug
```
Yes, as Johan said, Azure Power Shell/CLI, SDK all call Azure Rest API. If you use debug mode, you could see the API. More information about Azure Rest API, you could check this [link](https://learn.microsoft.com/en-us/rest/api/).
Upvotes: 3 <issue_comment>username_2: Each service in Azure exposes a set of APIs. For managing/creating/updating your resources (e.g. [creating a Virtual Machine](https://learn.microsoft.com/en-us/rest/api/compute/virtualmachines/createorupdate)), these are REST calls. Note: Other services may use non-HTTP/REST APIs (e.g. AMQP for [Azure Service Bus](https://azure.microsoft.com/en-us/services/service-bus/)).
While you can use your favorite HTTP networking stack or utility (e.g. curl, postman etc.) to make HTTP/REST calls, Microsoft publishes a set of SDKs to make things easier to develop applicationsin various languages.
The [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest) happens to be implemented in [python](https://python.org), and thus makes use of the [Azure Python SDKs](http://azure-sdk-for-python.readthedocs.io/en/latest/) to get its work done.
There is no separate Azure **CLI** SDK, however.
Upvotes: 2 |
2018/03/15 | 2,762 | 9,332 | <issue_start>username_0: I want to make a realistic typing effect with sound. I'm using Typed.js, I have already create a simple example.
Here is my code :
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
function playSound () {
keystrokeSound.pause();
keystrokeSound.currentTime = 0;
keystrokeSound.play();
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 50,
preStringTyped : function(array, self){
playSound();
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
The typing effect works as excepted. But no with the sound, the sound only play when the first char of sentence only. I have read the [docs](https://github.com/mattboldt/typed.js/#customization), but I can't found callback for each char typed. How to play sound on each typed char?
Here's the [fiddle](https://jsfiddle.net/rz6appro/3/)<issue_comment>username_1: Try This code :
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
var interval ;
function playSound () {
clearInterval(interval);
interval = setInterval(function(){
keystrokeSound.pause();
keystrokeSound.currentTime = 0;
keystrokeSound.play();
},220);
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 100,
preStringTyped : function(array, self){
playSound();
},
onStringTyped : function(array, self){
clearInterval(interval);
},
onComplete: function(array, self){
clearInterval(interval);
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 50;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: You could also try to loop the sound, and call the onStringTyped method from typed.js:
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
function playSound () {
if (typeof keystrokeSound.loop == 'boolean')
{
keystrokeSound.loop = true;
}
else
{
keystrokeSound.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
}
keystrokeSound.play();
}
function stopSound () {
keystrokeSound.pause();
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 50,
preStringTyped : function(array, self){
playSound();
},
onStringTyped : function(array, self){
stopSound();
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
Upvotes: 1 <issue_comment>username_3: I guess the best would be to tweak the source code directly in order to make such an event available.
Here is the result of my best try from what we have now, using the Web Audio API in order to trigger the sound with the best timing precision possible, and ... It's not that fantastic...
For whatever reasons, the typing code doesn't seem to be very regular, I suspect perfs issues, but can't be sure, and didn't want to dissect the sources of the plugin yet.
Anyway, here is my attempt, if it can help you for the time being.
```js
/* A simple player using the Web Audio API */
class Player {
constructor(url) {
this.media_url = url;
}
init() {
this.ctx = new AudioContext();
return fetch(this.media_url)
.then(resp => resp.arrayBuffer())
.then(buf => this.ctx.decodeAudioData(buf))
.then(audioBuffer => this.audioBuffer = audioBuffer);
}
play() {
const node = this.ctx.createBufferSource();
node.buffer = this.audioBuffer;
node.connect(this.ctx.destination);
node.start(0);
}
}
// I have absolutely no rights on the given sound so neither do any reader
// If authors have concerns about it, simply leave me a comment, I'll remove right away
const keystrokePlayer = new Player('https://dl.dropboxusercontent.com/s/hjx4xlxyx39uzv7/18660_1464810669.mp3');
function playSound (string, delay) {
// It seems space is typed twice?
const l = string.length + string.match(/\s/g).length;
let current = 0;
function loop() {
// start our sound (1 time)
keystrokePlayer.play();
// if all have been played stop
if(current++ >= l) return;
// otherwise restart in 'delay' ms
setTimeout(loop, delay);
}
loop();
}
// load our sound
keystrokePlayer.init().then(()=> {
inp.disabled = false;
btn.onclick();
});
btn.onclick = e => {
var elem = makeNewElem();
var typed = new Typed(elem, {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: +inp.value || 50,
preStringTyped : function(index, self){
const opts = self.options;
playSound(opts.strings[index], opts.typeSpeed);
}
});
};
function makeNewElem(){
var cont = document.createElement('div');
var elem = document.createElement('span');
elem.classList.add('element');
cont.appendChild(elem);
document.body.appendChild(cont);
return elem;
}
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
typeSpeed (ms)do it
```
Upvotes: 0 <issue_comment>username_4: Answer my own question, the best way to do that is, edit the source code directly, and create a callback for each typed char. I'm just edit a little bit the source code (uncompressed version)
Found the `typewrite` function, and add this script before end of function
```
// fires callback function
this.options.onCharAppended(substr.charAt(0), this);
```
Also, found the `defaults` object, there is collection of default function for callback, I just add
```
onCharAppended: function onCharAppended(char, self){},
```
And then I can play sound with sync and precision time with the additional callback
```
var typed = new Typed('.element', {
strings: ["Test ^1000 with delay"],
typeSpeed: 100,
onCharAppended : function(char, self){
playSound();
}
});
```
Upvotes: 2 [selected_answer]<issue_comment>username_5: My solution was a bit different. I synced the audio to the typing speed using the audio's duration and playbackRate properties:
```
var typeSpeed = (audio.duration * 1000) / audio.playbackRate;
```
And then added the `onComplete` and the `preStringTyped` props to the `option` object:
```
var options = {
typeSpeed: typeSpeed,
preStringTyped: (arrPos) => {
// Start the playing the looped audio when the typing's about to start
audio.loop = true;
audio.play();
},
onComplete: () => {
// When the typing ends we stop the looping
audio.loop = false;
audio.stop();
}
}
```
This lead to a convincing, albeit repetitive, typing sound effect.
Alternatively, if you wanted to more random effects, you could start the sound in the `preStringTyped` function and also leave a flag there in place of the `audio.loop` (e.g. `repeat = true`). Then, you would add a event listener for the `onend` event and play the audio again if the `repeat` flag is still on. Except this time you pick a random audio file to play. And lastly, in the `onComplete` callback you stop the currently playing audio and set the `repeat` flag to `false`.
Upvotes: 0 |
2018/03/15 | 2,432 | 8,359 | <issue_start>username_0: When I declare the class in python as below **slots** work
```
class CSStudent(object):
stream = 'cse'
__slots__ = ['name', 'roll']
def __init__(self, name, roll):
self.name = name
self.roll = roll
```
When I declare the class in python as below **slots** doesn't work
```
class CSStudent:
stream = 'cse'
__slots__ = ['name', 'roll']
def __init__(self, name, roll):
self.name = name
self.roll = roll
```<issue_comment>username_1: Try This code :
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
var interval ;
function playSound () {
clearInterval(interval);
interval = setInterval(function(){
keystrokeSound.pause();
keystrokeSound.currentTime = 0;
keystrokeSound.play();
},220);
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 100,
preStringTyped : function(array, self){
playSound();
},
onStringTyped : function(array, self){
clearInterval(interval);
},
onComplete: function(array, self){
clearInterval(interval);
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 50;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: You could also try to loop the sound, and call the onStringTyped method from typed.js:
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
function playSound () {
if (typeof keystrokeSound.loop == 'boolean')
{
keystrokeSound.loop = true;
}
else
{
keystrokeSound.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
}
keystrokeSound.play();
}
function stopSound () {
keystrokeSound.pause();
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 50,
preStringTyped : function(array, self){
playSound();
},
onStringTyped : function(array, self){
stopSound();
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
Upvotes: 1 <issue_comment>username_3: I guess the best would be to tweak the source code directly in order to make such an event available.
Here is the result of my best try from what we have now, using the Web Audio API in order to trigger the sound with the best timing precision possible, and ... It's not that fantastic...
For whatever reasons, the typing code doesn't seem to be very regular, I suspect perfs issues, but can't be sure, and didn't want to dissect the sources of the plugin yet.
Anyway, here is my attempt, if it can help you for the time being.
```js
/* A simple player using the Web Audio API */
class Player {
constructor(url) {
this.media_url = url;
}
init() {
this.ctx = new AudioContext();
return fetch(this.media_url)
.then(resp => resp.arrayBuffer())
.then(buf => this.ctx.decodeAudioData(buf))
.then(audioBuffer => this.audioBuffer = audioBuffer);
}
play() {
const node = this.ctx.createBufferSource();
node.buffer = this.audioBuffer;
node.connect(this.ctx.destination);
node.start(0);
}
}
// I have absolutely no rights on the given sound so neither do any reader
// If authors have concerns about it, simply leave me a comment, I'll remove right away
const keystrokePlayer = new Player('https://dl.dropboxusercontent.com/s/hjx4xlxyx39uzv7/18660_1464810669.mp3');
function playSound (string, delay) {
// It seems space is typed twice?
const l = string.length + string.match(/\s/g).length;
let current = 0;
function loop() {
// start our sound (1 time)
keystrokePlayer.play();
// if all have been played stop
if(current++ >= l) return;
// otherwise restart in 'delay' ms
setTimeout(loop, delay);
}
loop();
}
// load our sound
keystrokePlayer.init().then(()=> {
inp.disabled = false;
btn.onclick();
});
btn.onclick = e => {
var elem = makeNewElem();
var typed = new Typed(elem, {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: +inp.value || 50,
preStringTyped : function(index, self){
const opts = self.options;
playSound(opts.strings[index], opts.typeSpeed);
}
});
};
function makeNewElem(){
var cont = document.createElement('div');
var elem = document.createElement('span');
elem.classList.add('element');
cont.appendChild(elem);
document.body.appendChild(cont);
return elem;
}
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
typeSpeed (ms)do it
```
Upvotes: 0 <issue_comment>username_4: Answer my own question, the best way to do that is, edit the source code directly, and create a callback for each typed char. I'm just edit a little bit the source code (uncompressed version)
Found the `typewrite` function, and add this script before end of function
```
// fires callback function
this.options.onCharAppended(substr.charAt(0), this);
```
Also, found the `defaults` object, there is collection of default function for callback, I just add
```
onCharAppended: function onCharAppended(char, self){},
```
And then I can play sound with sync and precision time with the additional callback
```
var typed = new Typed('.element', {
strings: ["Test ^1000 with delay"],
typeSpeed: 100,
onCharAppended : function(char, self){
playSound();
}
});
```
Upvotes: 2 [selected_answer]<issue_comment>username_5: My solution was a bit different. I synced the audio to the typing speed using the audio's duration and playbackRate properties:
```
var typeSpeed = (audio.duration * 1000) / audio.playbackRate;
```
And then added the `onComplete` and the `preStringTyped` props to the `option` object:
```
var options = {
typeSpeed: typeSpeed,
preStringTyped: (arrPos) => {
// Start the playing the looped audio when the typing's about to start
audio.loop = true;
audio.play();
},
onComplete: () => {
// When the typing ends we stop the looping
audio.loop = false;
audio.stop();
}
}
```
This lead to a convincing, albeit repetitive, typing sound effect.
Alternatively, if you wanted to more random effects, you could start the sound in the `preStringTyped` function and also leave a flag there in place of the `audio.loop` (e.g. `repeat = true`). Then, you would add a event listener for the `onend` event and play the audio again if the `repeat` flag is still on. Except this time you pick a random audio file to play. And lastly, in the `onComplete` callback you stop the currently playing audio and set the `repeat` flag to `false`.
Upvotes: 0 |
2018/03/15 | 2,910 | 9,462 | <issue_start>username_0: I've been trying to apply this preloading screen in angular 4. Here is the code of my index.html
[Here](https://codepen.io/cjnucette/pen/ZaWjLR) is the link to the code pen of this css effect .
I don't want any other preloading screens . Please be specific why this is not working not even in a dummy project. I've tried some other css screens but they are also not working. I've suspected the problem is in keyframes , they work with only transform property of css.
```
Test4preloadingscreen
@import url('https://fonts.googleapis.com/css?family=Roboto:700');
\*, \*:after, \*:before {
margin: 0;
padding: 0;
box-sizing: inherit;
}
app-root {
margin: 0;
padding: 0;
height: 100vh;
background: #262626;
display: flex;
justify-content: center;
box-sizing: border-box;
align-items: center;
}
ul {
display: flex;
}
li {
list-style: none;
color: #484848;
font-family: roboto, Arial, Sans-serif;
font-size: 5em;
letter-spacing: 15px;
animation: loading 1.4s linear infinite;
}
@keyframes loading {
0% {
color: #484848;
text-shadow: none;
}
90% {
color: #484848;
text-shadow: none;
}
100% {
color: #fff900;
text-shadow: 0 0 7px #fff900, 0 0 50px #ff6c00;
}
}
li:nth-child(1) {
animation-delay: .2s;
}
li:nth-child(2) {
animation-delay: .4s;
}
li:nth-child(3) {
animation-delay: .6s;
}
li:nth-child(4) {
animation-delay: .8s;
}
li:nth-child(5) {
animation-delay: 1s;
}
li:nth-child(6) {
animation-delay: 1.2s;
}
li:nth-child(7) {
animation-delay: 1.4s;
}
* L
* O
* A
* D
* I
* N
* G
```<issue_comment>username_1: Try This code :
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
var interval ;
function playSound () {
clearInterval(interval);
interval = setInterval(function(){
keystrokeSound.pause();
keystrokeSound.currentTime = 0;
keystrokeSound.play();
},220);
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 100,
preStringTyped : function(array, self){
playSound();
},
onStringTyped : function(array, self){
clearInterval(interval);
},
onComplete: function(array, self){
clearInterval(interval);
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 50;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: You could also try to loop the sound, and call the onStringTyped method from typed.js:
```js
var keystrokeSound = new Audio('http://www.freesfx.co.uk/rx2/mp3s/6/18660_1464810669.mp3');
function playSound () {
if (typeof keystrokeSound.loop == 'boolean')
{
keystrokeSound.loop = true;
}
else
{
keystrokeSound.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
}
keystrokeSound.play();
}
function stopSound () {
keystrokeSound.pause();
}
var typed = new Typed('.element', {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: 50,
preStringTyped : function(array, self){
playSound();
},
onStringTyped : function(array, self){
stopSound();
}
});
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
```
Upvotes: 1 <issue_comment>username_3: I guess the best would be to tweak the source code directly in order to make such an event available.
Here is the result of my best try from what we have now, using the Web Audio API in order to trigger the sound with the best timing precision possible, and ... It's not that fantastic...
For whatever reasons, the typing code doesn't seem to be very regular, I suspect perfs issues, but can't be sure, and didn't want to dissect the sources of the plugin yet.
Anyway, here is my attempt, if it can help you for the time being.
```js
/* A simple player using the Web Audio API */
class Player {
constructor(url) {
this.media_url = url;
}
init() {
this.ctx = new AudioContext();
return fetch(this.media_url)
.then(resp => resp.arrayBuffer())
.then(buf => this.ctx.decodeAudioData(buf))
.then(audioBuffer => this.audioBuffer = audioBuffer);
}
play() {
const node = this.ctx.createBufferSource();
node.buffer = this.audioBuffer;
node.connect(this.ctx.destination);
node.start(0);
}
}
// I have absolutely no rights on the given sound so neither do any reader
// If authors have concerns about it, simply leave me a comment, I'll remove right away
const keystrokePlayer = new Player('https://dl.dropboxusercontent.com/s/hjx4xlxyx39uzv7/18660_1464810669.mp3');
function playSound (string, delay) {
// It seems space is typed twice?
const l = string.length + string.match(/\s/g).length;
let current = 0;
function loop() {
// start our sound (1 time)
keystrokePlayer.play();
// if all have been played stop
if(current++ >= l) return;
// otherwise restart in 'delay' ms
setTimeout(loop, delay);
}
loop();
}
// load our sound
keystrokePlayer.init().then(()=> {
inp.disabled = false;
btn.onclick();
});
btn.onclick = e => {
var elem = makeNewElem();
var typed = new Typed(elem, {
strings: ["Play sound each I type character", "It's only play on start of string"],
typeSpeed: +inp.value || 50,
preStringTyped : function(index, self){
const opts = self.options;
playSound(opts.strings[index], opts.typeSpeed);
}
});
};
function makeNewElem(){
var cont = document.createElement('div');
var elem = document.createElement('span');
elem.classList.add('element');
cont.appendChild(elem);
document.body.appendChild(cont);
return elem;
}
```
```css
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
```
```html
typeSpeed (ms)do it
```
Upvotes: 0 <issue_comment>username_4: Answer my own question, the best way to do that is, edit the source code directly, and create a callback for each typed char. I'm just edit a little bit the source code (uncompressed version)
Found the `typewrite` function, and add this script before end of function
```
// fires callback function
this.options.onCharAppended(substr.charAt(0), this);
```
Also, found the `defaults` object, there is collection of default function for callback, I just add
```
onCharAppended: function onCharAppended(char, self){},
```
And then I can play sound with sync and precision time with the additional callback
```
var typed = new Typed('.element', {
strings: ["Test ^1000 with delay"],
typeSpeed: 100,
onCharAppended : function(char, self){
playSound();
}
});
```
Upvotes: 2 [selected_answer]<issue_comment>username_5: My solution was a bit different. I synced the audio to the typing speed using the audio's duration and playbackRate properties:
```
var typeSpeed = (audio.duration * 1000) / audio.playbackRate;
```
And then added the `onComplete` and the `preStringTyped` props to the `option` object:
```
var options = {
typeSpeed: typeSpeed,
preStringTyped: (arrPos) => {
// Start the playing the looped audio when the typing's about to start
audio.loop = true;
audio.play();
},
onComplete: () => {
// When the typing ends we stop the looping
audio.loop = false;
audio.stop();
}
}
```
This lead to a convincing, albeit repetitive, typing sound effect.
Alternatively, if you wanted to more random effects, you could start the sound in the `preStringTyped` function and also leave a flag there in place of the `audio.loop` (e.g. `repeat = true`). Then, you would add a event listener for the `onend` event and play the audio again if the `repeat` flag is still on. Except this time you pick a random audio file to play. And lastly, in the `onComplete` callback you stop the currently playing audio and set the `repeat` flag to `false`.
Upvotes: 0 |
2018/03/15 | 387 | 1,344 | <issue_start>username_0: I have created a ListView with a scrollBar. Like this
[](https://i.stack.imgur.com/ngICQ.png)
Here is my code,
```
ListView {
id: listView;
ScrollBar.vertical: ScrollBar {
id: bar
//x :100 doesn't work
active: true
}
}
```
In my case, i want to reset the location of the scrollbar. For example,move the scrollbar to the right by 5 pixels more. I tried to **set "x:"** , but didn't work. How can i solve my problem.<issue_comment>username_1: You have to establish that property a moment after loading the `ScrollBar` since the `ListView` sets it to the default position.
```
ScrollBar.vertical: ScrollBar {
id: sb
active: true
Component.onCompleted: x = 100
}
```
[](https://i.stack.imgur.com/0yj6Z.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can move the `ScrollBar` outside of the `ListView` and reference it inside the `ListView` with its `id`:
```
ListView {
id: listView
ScrollBar.vertical: bar
}
ScrollBar {
id: bar
active: true
anchors {
left: listView.left
top: listView.top
bottom: listView.bottom
leftMargin: 100
}
}
```
Upvotes: 3 |
2018/03/15 | 695 | 2,492 | <issue_start>username_0: Given I have the following information:
```
string Sentence = "The dog jumped over the cat and the cat jumped above the mouse."
string startword = "jumped"
string endword = "the"
```
My requirement is how to program in C# to count the number of occurrences that the Sentence contains the starting of the `startword` until matching the second `endword`.
The above example should return 2 because `The dog [jumped] ... [the] cat and ...cat [jumped] .. [the] mouse.`
One of my ideas of to do string.Split the Sentence into string of words and looping through the words and compare with `startword`. If `startword` matched, then compare the next word to the `endword` until found or end of Sentence. If the `startword` and `endword` have been found, increase the counter, and continue searching for `startword` and `endword` until end of sentence.
Any other suggestion or code sample will be appreciated.<issue_comment>username_1: I would suggest using regex for this.
The regex to use is pretty straightforward: `jumped.*?the`
You can play with it here: <https://regex101.com/r/h0MKyV/1>
Since you are expecting multiple matches, you can get them in C# using `regex.Matches` call. So your code should look like the following:
```
var regex = new Regex("jumped.*?the");
var str = "The dog jumped over the cat and the cat jumped above the mouse.";
var matches = regex.Matches(str);
```
You can iterate over the `matches` to access each match, or get their count directly.
Upvotes: 2 <issue_comment>username_2: ```
regexPattern= "jumped[\s\w]+?the"
searchText = "The dog jumped over the cat and the cat jumped above the mouse."
```
The above regex match your question.
To count the number of occurrences use
`regexCount = Regex.Matches(searchText, regexPattern).Count`
Upvotes: 1 <issue_comment>username_3: The answers here are good. However, I just thought I'd point out that you might want to respect word boundaries by using `\b`. Otherwise you might pick up partial words.
>
> `\b` Matches any word boundary. Specifically, any point between a `\w` and
> a `\W`.
>
>
>
```
var regex = new Regex(@"\bjumped\b.*?\bthe\b");
var str = "The dog jumped over theatre cat and the cat bejumped above the mouse.";
var matches = regex.Matches(str);
Console.WriteLine("Count : " + matches.Count);
foreach (var match in matches)
{
Console.WriteLine(match);
}
```
[**You can see the demo here**](https://dotnetfiddle.net/J2Hj2R)
Upvotes: 3 [selected_answer] |
2018/03/15 | 595 | 2,307 | <issue_start>username_0: As an effort to automate the (Android) build and test process, I configured an *AWS code pipeline* that will 1st get the code from *GitHub* and trigger a build (via *aws codebuild*) Build is shown as completed successfully but the artifacts (apk file) generated as a result of the build process isn't uploaded to the s3 bucket (public bucket). The logs clearly say the upload is successful as seen in the screenshots attached![![here]](https://i.stack.imgur.com/yQxCA.png) [](https://i.stack.imgur.com/LYadS.png)
The *codepipeline* as well shows everything is successful as attached [](https://i.stack.imgur.com/XrITf.png)
However, if I run **aws codebuild project directly from the aws codebuild screen**, it **does upload** the artifact successfully to the s3 bucket!
I tried changing the bucket permissions to public/non public, etc. So far no success<issue_comment>username_1: CodePipeline will override the CodeBuild's artifact bucket, I guess it's moving the artifacts to its own Bucket. you can see the CodePipeline's bucket by running the below command.
```
codepipeline get-pipeline --name PipelineName--query pipeline.[artifactStore]
[
{
"type": "S3",
"location": "codepipeline-us-east-1-xxxxxxxx"
}
]
```
If you are using CloudFormation to create the pipeline you configure the bucket using [ArtifactStore](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstore).
**Update ArtifactStore in CodePipeline:**
Currently, I don't see a way to update the ArtifactStore through Console but it can be done with `update-pipeline` command.
Get the pipleline details:
```
aws codepipeline get-pipeline --name MyFirstPipeline >pipeline.json
```
Edit the pipeline to update the S3 Bucket in `artifactStore` and then run the command.
```
aws codepipeline update-pipeline --cli-input-json file://pipeline.json
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: I had this same problem, couldn't see the `MyAppBuild` folder in S3 that was meant to hold CodeBuild artifacts. Logged out of the web console and back in again and the folder was now visible.
Upvotes: 0 |
2018/03/15 | 558 | 2,460 | <issue_start>username_0: [This question](https://stackoverflow.com/questions/14820450/best-splittable-compression-for-hadoop-input-bz2) tells that lz4 compression format is splittable and suitable for using in hdfs. Ok I have compressed 1.5 Gb data into 300 Mb lz4 file. If I try to read this file via spark - what the maximum workers count can it create to read file in parallel? Do splittable pieces count depend on lz4 compression level?<issue_comment>username_1: Compression will not impact the no of splittable pieces count
If the input file is compressed, then the bytes read in from HDFS is reduced, which means less time to read data. This time conservation is beneficial to the performance of job execution.
Upvotes: 0 <issue_comment>username_2: Compression codec that is splittable definitely matters and counts in Hadoop processing. I disagree with the previous answer. When you say splittable it essentially means you can have a mapper program that can read the logical split and process the data without worrying about the other parts of the split stored elsewhere in the datanode cluster with some compression algorithm.
For example, think about your windows zip file. If I had 10 GB file that and plan to zip with max size of split to be 100MB each then i create maybe 10 files of 100MB each (in total compressed to 1 GB). Can you write a program to process part of the file without unzipping the whole file back to its original state. This is the difference between splittable and unsplittable compression codec in hadoop context. For example, .gz is not splittable whereas bzip2 is possible. Even if you have a .gz file in Hadoop, you will have to first uncompresses the whole file across your datanode and then run program against the single file.This is not efficient and doesnt use power of Hadoop parallelism.
Lot of people confuse between splitting a compressed file into multiple parts in your windows or linux versus splitting a file in hadoop with compression codecs.
Lets come back to discussion of why compression with split matters. Hadoop essentially relies on mappers and reducers and each mapper can works upon the logical split of the file (not the physical block). If I had stored the file without splittablity then mapper will have to first uncompresses whole of the file before performing any operation on that record.
So be aware that input split is directly correlated with parallel processing in Hadoop.
Upvotes: -1 |
2018/03/15 | 1,262 | 4,804 | <issue_start>username_0: I started working on Google Script.
I wonder if there is some way to print in google script( be it text or google sheet data ) when a cell event is generated on the Google sheet.
Any suggestion would be helpful.
Thanks.<issue_comment>username_1: A Google Script cannot use system functions such as the print dialogue.
Upvotes: 2 [selected_answer]<issue_comment>username_2: **Before proceeding further make sure you have added google cloud supporting printer to google account for printing because of security reasons services like print is not supported by google script**
* Open Google Drive.
1. Right-click to make open Google Sheet.
2. Add some rows.
3. Click on **Tools** menu and select **Script editor** option.
4. Select **File** menu from script editor and then select **project properties** option.
5. Note down the **Project key** (Deprecated) and **Script\_id** from **info** tab.
6. Select Resources > Libraries.
7. Add key `<KEY>` to **add library box**. Select latest version from list and set **identifier** `OAuth2`.
* Open Google Cloud Console.
1. To open Google Cloud Console follow this link Google Cloud Console link, there in left navigation section you will find a credentials link.
2. Click on **Credentials link** > **Create Credentials**. A popup will appear. From there select `OAuth Client Id` option.
3. Under Application Type select Web Application. Set some name to Application.
In authorised script origins url box paste below link.
`https://apis.google.com`
In authorized redirected url box paste below link.
`https://script.google.com/macros/d/{SCRIPT_ID}/usercallback`
4. SCRIPT\_ID is from project properties.
5. Save the details.
6. Note down Client\_id and Client\_secret for future use.
* Script.
Paste Below code in script window.
```
function showURL() {
var cpService = getCloudPrintService();
if (!cpService.hasAccess()) {
console.log(cpService.getAuthorizationUrl());
}
}
function getCloudPrintService() {
return OAuth2.createService('print')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId('CLIENT_ID’)
.setClientSecret('CLIENT_SECRET')
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/cloudprint')
.setParam('login_hint', Session.getActiveUser().getEmail())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var isAuthorized = getCloudPrintService().handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('You can now use Google Cloud Print from Apps Script.');
} else {
return HtmlService.createHtmlOutput('Cloud Print Error: Access Denied');
}
}
```
**getPrinterList** this method will check list of linked printer to account and return printer ID, NAME and DESCRIPTION
```
function getPrinterList() {
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/search', {
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
muteHttpExceptions: true
}).getContentText();
var printers = JSON.parse(response).printers;
for (var p in printers) {
Logger.log("%s %s %s", printers[p].id, printers[p].name, printers[p].description);
}
}
```
* Last step.
1. In script window select Select Function from toolbar and select showURL function and run code.
2. Hit CMD + ENTER to open logs. Copy the url from logs and paste in browser.
3. Follow the direction and allow permissions for printer.
**Run below method with required parameters to add print job to cloud printer.**
```
function printGoogleDocument(docID, printerID, docName) {
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "NO_DUPLEX"
}
}
};
var payload = {
"printerid" : printerID,
"title" : docName,
"content" : DriveApp.getFileById(docID).getBlob(),
"contentType": "application/pdf",
"ticket" : JSON.stringify(ticket)
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
}
```
Thanks.
If you face any error , kindly leave a reply.
Upvotes: 2 |
2018/03/15 | 680 | 2,524 | <issue_start>username_0: I have this data access interface:
```
public interface UserDao {
void loadUsers(Handler>> handler);
}
```
And it's used in a service like this:
```
public class UserService {
private UserDao userDao;
public UserService(UserDao UserDao) {
this.userDao = userDao;
}
public void getUsers(Future> future) {
userDao.loadUsers( ar ->{
if (ar.succeeded()){
List users = ar.result();
// process users
future.complete(users);
}else {
// handle the error
}
});
}
}
```
Now my intention is to unit test my service and mock the data access layer. I want to return a fixed set of results every time getUsers method of UserDao class is called.
```
@Test
public void testGetUsers(TestContext context) {
Async async = context.async();
UserDao mockUserDao = Mockito.mock(UserDao.class);
UserService userService = new UserService(mockUserDao);
List mockResult = Arrays.asList(new User(), new User());
/\* (?) How to make mockUserDao return mockResult through its Handler argument? \*/
Future> future = Future.future();
userService.getUsers(future);
future.setHandler(ar -> {
assertEquals(2, ar.result().size());
async.complete();
});
async.awaitSuccess();
}
```
How can I do that? It does not fit the normal Mockito pattern *when(serviceMock.method(any(Argument.class))).thenAnswer(new Result())* as *mockResult* is not returned from the method per say but through the handler.<issue_comment>username_1: Mock `Handler` also.
```
Handler mockedHandler = mock(Handler.class);
when(mockedHandler.result()).thenReturn(mockResult);
when(userDao.loadUsers(any(Handler.class))).thenReturn(mockedHandler);
```
Upvotes: 0 <issue_comment>username_2: Stub the function.
```
public class TestUserDao implements UserDao {
void loadUsers(Handler>> handler) {
handler.apply(mockResult)
}
}
UserDao userDao = mock(UserDao.class, AdditionalAnswers.delegatesTo(new TestUserDao()));
verify(userDao).loadUsers(any());
```
Upvotes: 1 <issue_comment>username_3: You could check, if the loadUsers() has been invoked with a non-null handler, using an ArgumentCaptor. The ArgumentCaptor provides you access to the handler
to which you could pass a prepared result (either with a success or a failed result)
```
AsyncResult> yourResult = ... //success or failure
ArgumentCaptor>>> captor = ArgumentCaptor.forClass(Handler.class);
Mockito.verify(userDao).loadUsers(captor.capture());
Handler>> handler = captor.getValue();
handler.handle(yourResult);
```
Upvotes: 1 |
2018/03/15 | 296 | 1,020 | <issue_start>username_0: I have table called total\_table in which i have 3 columns requested\_amount,total and difference.
[](https://i.stack.imgur.com/p1ur4.png)
I want the query to calculate the difference value of requested\_amount and total columns (requested\_amount - total) and store it in difference column of same table.<issue_comment>username_1: What you need to do is to write a simple update query like this:
```
Update total_table Set
difference_amt = requested_amount - total
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You don't want to store the `difference_amt` field in the table...It can be fetched using query when you actually need the `difference_amt` field.So you need to change the structure of the table like this.
[](https://i.stack.imgur.com/d4BT8.jpg)
I've explained it in fiddle...You can check it...
<http://sqlfiddle.com/#!9/8984d7/1>
Upvotes: 0 |
2018/03/15 | 1,098 | 4,612 | <issue_start>username_0: I am new to android studio. I want to learn how to convert webview to app. I have written the code for the same :
`activity_main.xml` is as follow :
```
xml version="1.0" encoding="utf-8"?
```
`AndroidMenifest.xml` is as follow:
```
xml version="1.0" encoding="utf-8"?
```
`Main Activity.java` is :
```
package com.aarvansh.shoponline.shoponline;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://aarvanshinfotech.co.in/shop");
}
public class myWebClient extends WebViewClient
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
```
But when I am trying to run this apk, no splash screen is being load at the start. I want to load splash screen in which I want to rotate a jpg file when the app is loading<issue_comment>username_1: You need to create another activity for splash screen
Check the below code foe splash screen
create a new empty activity than just use below code
customize your splash screen as per your requirement
>
> **SAMPLE CODE**
>
>
>
**LAYOUT file**
```
xml version="1.0" encoding="utf-8"?
```
**ACTVITY Code**
```
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SplashActivity extends AppCompatActivity {
private int SPLASH_TIME_OUT = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getSupportActionBar().hide();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, DashboardActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
@Override
public void onBackPressed() {
}
}
```
Upvotes: 2 <issue_comment>username_2: Add this to your android project to load splash screen. U can change the logo image in splashscreeen.xml as per ur need .
SplashScreenActivity.java
```
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Window;
public class SplashScreenActivity extends Activity {
// Set Duration of the Splash Screen
long Delay = 8000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove the Title Bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Get the view from splash_screen.xml
setContentView(R.layout.splash_screen);
// Create a Timer
Timer RunSplash = new Timer();
// Task to do when the timer ends
TimerTask ShowSplash = new TimerTask() {
@Override
public void run() {
// Close SplashScreenActivity.class
finish();
// Start MainActivity.class
Intent myIntent = new Intent(SplashScreenActivity.this,
MainActivity.class);
startActivity(myIntent);
}
};
// Start the timer
RunSplash.schedule(ShowSplash, Delay);
}
}
```
splash\_screen.xml
```
```
AndroidManifest.xml
In your Manifest file Change the application part as below...
```
```
Upvotes: 0 |
2018/03/15 | 803 | 3,248 | <issue_start>username_0: I am trying to add a new column in old sqlite database tables. The tables are dynamic. I mean they are created when app users add a specific data in the app.
The tables names have a similar suffix. Prefix depends upon user input. Now, in android, how can I add a new column in those tables without losing previous data?<issue_comment>username_1: **Try This Logic**
```
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int upgradeTo = oldVersion + 1;
while (upgradeTo <= newVersion)
{
switch (upgradeTo)
{
case 2:
db.execSQL("ALTER TABLE " + TABLE_REGISTER +" ADD COLUMN user_mobile TEXT");
break;
case 3:
db.execSQL("ALTER TABLE " + TABLE_REGISTER +" ADD COLUMN user_mobile_new TEXT");
break;
}
upgradeTo++;
}
}
```
**Every time you add new column or new table just add another case and increase db version. Your last case would be your database version. In my case dbVersion = 3**
Upvotes: 0 <issue_comment>username_2: I hope you already know how the `onUpgrade` method works. The implementation of `onUpgrade` is pretty simple, which detects if the database version is changed and take the changes in effect for the newer version of database. Here's a sample implementation.
```
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// The last case will contain the break statement only. As the migration will take place one by one.
// Here's a nice explanation - http://stackoverflow.com/a/26916986/3145960
switch (oldVersion) {
case 1:
doSomeChangesInDBForVersion1();
case 2:
doSomeChangesInDBForVersion2();
break;
}
}
```
Now let us come to the specific problem that you asked. As far as I could understand, the tables in your database are dynamic which are based on user input. You want to add columns in your database table which are created based on user inputs.
In that case, you need to find out first the existing tables and then run the alter command on each of your tables. To find the existing tables in your database you might do something like the following.
```
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List tableList = new ArrayList<>();
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
tableList.add(c.getString(0));
c.moveToNext();
}
}
```
Now store the table names in an array and then run alter command on each of your table to add a new column in each of your tables.
```
for (String tableName : tableList) {
db.execSQL("alter table " + tableName +" add column new_col TEXT default null");
}
```
Run these executions in your `onUpgrade` function. I have not tested this code. Please modify as per your requirement.
Upvotes: 4 [selected_answer]<issue_comment>username_3: You got this problem for me and I benefited from this site, which will show you the best way to follow on this topic
[enter link description here](https://umeshsaravane.wordpress.com/2015/12/29/new-blog/)
Upvotes: 0 |
2018/03/15 | 268 | 1,020 | <issue_start>username_0: Originally, when I tried to do this:
```
ans = Book.new Book.last.attributes
```
It used to throw me a warning:
```
WARNING: Can't mass-assign protected attributes for Book: id
```
And the new object created without id being copied.
But now when I upgraded from rails 4.2.8 to 4.2.10, and also upgraded my other gems. I don't get any warnings, and the id is also being copied from the attributes. I want to create a new object, with id being nil.
Why would the behaviour of mass assignment security change with gem upgrades? I didn't add any new gem.<issue_comment>username_1: You could do...
```
ans = Book.new Book.last.dup.attributes
```
Which will duplicate the book but set id to nil.
Upvotes: 1 <issue_comment>username_2: I had to remove or downgrade protected-attributes gem to the previous version. We were using it to allow parameters without permitting, but with new version it was letting even id and other protected attributes to copy as well.
Upvotes: 1 [selected_answer] |
2018/03/15 | 308 | 1,024 | <issue_start>username_0: I am trying to compile this code and it is returning a syntax error in the last line:(, have any one idea why
```
let nth_index str c n =
let i = 0 in
let rec loop n i=
let j = String.index_from str i c in
if n>1 then loop (n-1) j
else
j
```<issue_comment>username_1: Your outermost `let` doesn't require a matching `in`. It makes a top-level definition.
However, the other three `let`s do require a matching `in`. And you only have two `in`s.
Upvotes: 3 [selected_answer]<issue_comment>username_2: So, according to the @Jeffrey's response, you can write:
```
let nth_index str c n =
let rec loop n i =
let j = String.index_from str i c in
if n>1 then loop (n-1) j else j
in loop n 0
```
But looking at your algorithm, probably you wanted to write `if n>1 then loop (n-1) (j+1) else j` in penultimate line. If yes, please note that this method can raise exception, so good practice is to name it `nth_index_exn`.
Upvotes: 2 |
2018/03/15 | 288 | 1,112 | <issue_start>username_0: ```
xml version="1.0" encoding="utf-8"?
```
After generating app from source code two error message displayed although it does not affect the app by any mean, but it really looks odds when someone open my app and those ugly errors shown before start the apps.
**Error :-**
>
> 1. missing permission , uses-permission android:name="android.permission.WRITE\_EXTERNAL\_STORAGE # although i
> gave the permission #
> 2. Integration Error : Vungle classes are already loaded from jar files ,remove unnecessary Dex files. # i use Appodeal SDK integration
> #
>
>
>
i just can't understand what should i have to do, please help me.<issue_comment>username_1: about case one add this
```
```
above application tag in manifest
Upvotes: 2 <issue_comment>username_2: Have you checked their [documentation?.](https://www.appodeal.com/sdk/documentation) Also, look through the samples, if you are using MultiDex or if you are not using MultiDex, as there are different sample projects for these. In the app folder, look for the proguard-rules.pro and copy the rules there.
Upvotes: 0 |
2018/03/15 | 223 | 928 | <issue_start>username_0: Is there anyway to detect if the Android operating system (not the app) crashed and rebooted the phone?
It would need to be for an app to detect when that has occurred within the app itself--so looking at logs as the developer isn't a suitable option.
Edit: I'm already using the receiver to make my app aware when boot completes--but I need to distinguish in that moment if there was an OS crash or if the phone was simply restarted or turned on/off.<issue_comment>username_1: about case one add this
```
```
above application tag in manifest
Upvotes: 2 <issue_comment>username_2: Have you checked their [documentation?.](https://www.appodeal.com/sdk/documentation) Also, look through the samples, if you are using MultiDex or if you are not using MultiDex, as there are different sample projects for these. In the app folder, look for the proguard-rules.pro and copy the rules there.
Upvotes: 0 |
2018/03/15 | 1,339 | 2,590 | <issue_start>username_0: In R, what would be the best way to separate the following data into a table with 2 columns?
March 09, 2018
0.084752
March 10, 2018
0.084622
March 11, 2018
0.084622
March 12, 2018
0.084437
March 13, 2018
0.084785
March 14, 2018
0.084901
I considered using a for loop but was advised against it. I do not know how to parse things very well, so if the best method involves this process please
be as clear as possible.
The final table should look something like this:
<https://i.stack.imgur.com/u5hII.png>
Thank you!<issue_comment>username_1: Input:
```
input <- c("March 09, 2018",
"0.084752",
"March 10, 2018",
"0.084622",
"March 11, 2018",
"0.084622",
"March 12, 2018",
"0.084437",
"March 13, 2018",
"0.084785",
"March 14, 2018",
"0.084901")
```
Method:
```
library(dplyr)
library(lubridate)
df <- matrix(input, ncol = 2, byrow = TRUE) %>%
as_tibble() %>%
mutate(V1 = mdy(V1), V2 = as.numeric(V2))
```
Output:
```
df
# A tibble: 6 x 2
V1 V2
1 2018-03-09 0.0848
2 2018-03-10 0.0846
3 2018-03-11 0.0846
4 2018-03-12 0.0844
5 2018-03-13 0.0848
6 2018-03-14 0.0849
```
Use `names()` or `rename()` to rename each columns.
```
names(df) <- c("Date", "Value")
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
result = data.frame(matrix(input, ncol = 2, byrow = T), stringsAsFactors = FALSE)
result
# X1 X2
# 1 March 09, 2018 0.084752
# 2 March 10, 2018 0.084622
# 3 March 11, 2018 0.084622
# 4 March 12, 2018 0.084437
# 5 March 13, 2018 0.084785
# 6 March 14, 2018 0.084901
```
You should next adjust the names and classes, something like this:
```
names(result) = c("date", "value")
result$value = as.numeric(result$value)
# etc.
```
---
Using Nik's nice input:
```
input = c(
"March 09, 2018",
"0.084752",
"March 10, 2018",
"0.084622",
"March 11, 2018",
"0.084622",
"March 12, 2018",
"0.084437",
"March 13, 2018",
"0.084785",
"March 14, 2018",
"0.084901"
)
```
Upvotes: 0 <issue_comment>username_3: `data.table::fread` can read "...a string (containing at least one \n)...."
'f' in `fread` stands for 'fast' so the code below should work on fairly large chunks as well.
```
require(data.table)
x = 'March 09, 2018
0.084752
March 10, 2018
0.084622
March 11, 2018
0.084622
March 12, 2018
0.084437
March 13, 2018
0.084785
March 14, 2018
0.084901'
o = fread(x, sep = '\n', header = FALSE)
o[, V1L := shift(V1, type = "lead")]
o[, keep := (1:.N)%% 2 != 0 ]
z = o[(keep)]
z[, keep := NULL]
z
```
Upvotes: 2 |
2018/03/15 | 710 | 2,974 | <issue_start>username_0: I am using SQLServer with C#.
```
foreach(var item in list)
{
TransactionOptions transOption = new TransactionOptions();
transOption.IsolationLevel =
System.Transactions.IsolationLevel.ReadUncommitted;
using (TransactionScope scope = new
TransactionScope(TransactionScopeOption.Required, transOption))
{
//Code to select
//Code to insert
scope.Complete();
}
}
```
For first time(1st item from list) transaction not getting committed. but I can see select and insert queries in SQL Profiler. There is no exception in any where.
But second time (2nd item from list) and also remaining items getting committed.
If I change into `TransactionScopeOption.Suppress`, first item itself getting committed. But I dont know what is 'Suppress'
```
TransactionScope(TransactionScopeOption.Suppress, transOption))
{
//Code to select
//Code to insert
scope.Complete();
}
```
So any idea why `TransactionScopeOption.Required` and `TransactionScopeOption.RequiredNew` not working to commit? What changes I need to do to get commit?
Advance thanks for your help.<issue_comment>username_1: Try restructuring your code, like this:
```
TransactionOptions transOption = new TransactionOptions();
transOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (TransactionScope scope = new
TransactionScope(TransactionScopeOption.Required, transOption))
{
foreach(var item in enter code here`list)
{
//your code
scope.Complete();
}
}
```
Refer to [this](https://social.msdn.microsoft.com/Forums/en-US/25f037ca-886c-4563-b169-d724b6047a99/transactionscopeoptionsuppress-questions?forum=windowstransactionsprogramming) forum question for more details on what Supress is.
Upvotes: 0 <issue_comment>username_2: It's hard to say why there is the strange behaviour with the 1st item. But you should know a couple of things here:
### Transactions committing
The actual commit happens not on `scope.Complete();`, it happens when `TransactionScope` is being disposed.
### TransactionScopeOptions
**`TransactionScopeOption.Required`** guarantees that insructions in the scope will be wrapped by transaction. It can be achieved by two ways: a) if there is an ambient outer transaction then inner scope doesn't create the own transaction. The actual commit happens if `outerScope.Complete()` was invoked and then the outer transaction scope is disposed b) if there is no outer transactions then it creates its own transaction.
**`TransactionScopeOption.RequiresNew`** always creates its own independent transaction.
**`TransactionScopeOption.Suppress`** doesn't create any transaction and ignores any outer transaction. Since there is no any transaction to save changes it doesn't require `scope.Complete();` and you can't rollback changes.
I hope this information will help you to understand what happens in your particular case.
Upvotes: 1 |
2018/03/15 | 581 | 2,418 | <issue_start>username_0: I have an angularjs application, and I am using [this directive](https://github.com/kuhnza/angular-google-places-autocomplete) to get the google-maps-api places autocomplete in the following input field .
```html
```
The issue is that the input field's style is getting set as `display: none;`, and the autocomplete is not working.
When I manually set the property to `display: block;`, everything is working fine. Am I missing something in using the `g-places-autocomplete` directive?
Any help will be greatly appreciated. Thanks in advance!<issue_comment>username_1: Try restructuring your code, like this:
```
TransactionOptions transOption = new TransactionOptions();
transOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (TransactionScope scope = new
TransactionScope(TransactionScopeOption.Required, transOption))
{
foreach(var item in enter code here`list)
{
//your code
scope.Complete();
}
}
```
Refer to [this](https://social.msdn.microsoft.com/Forums/en-US/25f037ca-886c-4563-b169-d724b6047a99/transactionscopeoptionsuppress-questions?forum=windowstransactionsprogramming) forum question for more details on what Supress is.
Upvotes: 0 <issue_comment>username_2: It's hard to say why there is the strange behaviour with the 1st item. But you should know a couple of things here:
### Transactions committing
The actual commit happens not on `scope.Complete();`, it happens when `TransactionScope` is being disposed.
### TransactionScopeOptions
**`TransactionScopeOption.Required`** guarantees that insructions in the scope will be wrapped by transaction. It can be achieved by two ways: a) if there is an ambient outer transaction then inner scope doesn't create the own transaction. The actual commit happens if `outerScope.Complete()` was invoked and then the outer transaction scope is disposed b) if there is no outer transactions then it creates its own transaction.
**`TransactionScopeOption.RequiresNew`** always creates its own independent transaction.
**`TransactionScopeOption.Suppress`** doesn't create any transaction and ignores any outer transaction. Since there is no any transaction to save changes it doesn't require `scope.Complete();` and you can't rollback changes.
I hope this information will help you to understand what happens in your particular case.
Upvotes: 1 |
2018/03/15 | 1,509 | 4,652 | <issue_start>username_0: For example)
```
var str = "ABCDEF"
let result = str.someMethod("B")
result[0] // "A"
result[1] // "B"
result[2] // "CDEF"
let result2 = str.someMethod("A")
result2[0] // "A"
result2[1] // "BCDEF"
var str2 = "BBBAAA"
let result3 = str2.someMethod("B")
result3[0] // "B"
result3[1] // "B"
result3[2] // "B"
result3[3] // "AAA"
var str3 = "BABBCDEDBB"
let result4 = str3.someMethod("B")
result4[0] // "B"
result4[1] // "A"
result4[2] // "B"
result4[3] // "B"
result4[4] // "CDED"
result4[5] // "B"
result4[6] // "B"
```
How can I that???
This method is a little different component(separatedBy: )
Maybe it should work this way<issue_comment>username_1: try with below method,
```
func someMethod(input: String, fullString: String) -> [String] {
var array: [String] = []
var string:String = ""
for (index, char) in fullString.enumerated() {
if String(char) == input {
if string != "" {
array.append(string)
string = ""
}
array.append(input)
} else {
string.append(char)
if index == fullString.count-1 {
array.append(string)
}
}
}
return array
}
```
and call it like this way,
```
let str = "BABBCDEDBB"
let result = someMethod(input: "B", fullString: str)
print(result)
```
You will get following output,
```
["B", "A", "B", "B", "CDED", "B", "B"]
```
Upvotes: 1 <issue_comment>username_2: Here's a complete answer written as a `String` extension. This solution fits all of your listed needs plus it also handles cases where you pass in multi-characters searches.
```
extension String {
func someMethod(_ input: String) -> [String] {
var result = [String]()
var str = self
repeat {
if str.hasPrefix(input) {
result.append(input)
str.removeFirst(input.count)
} else if let range = str.range(of: input) {
result.append(String(str[.. \(result)")
}
print("A in \(strs[0]) -> \(strs[0].someMethod("A"))")
print("BB in \(strs[2]) -> \(strs[2].someMethod("BB"))")
```
Output:
>
> B in ABCDEF -> ["A", "B", "CDEF"]
>
> B in BBBAAA -> ["B", "B", "B", "AAA"]
>
> B in BABBCDEDBB -> ["B", "A", "B", "B", "CDED", "B", "B"]
>
> A in ABCDEF -> ["A", "BCDEF"]
>
> BB in BABBCDEDBB -> ["BA", "BB", "CDED", "BB"]
>
>
>
Upvotes: 1 <issue_comment>username_3: try this, it will work for string and char
```
func getResult(input:String, separator:String)->[String]{
var arr = input.components(separatedBy: separator)
var newArray = [String]()
var count = 0
while count < arr.count {
if let lastObj = newArray.last{
if lastObj == separator{
newArray.append(arr[count] == "" ? separator : arr[count])
}else{
if arr[count] == ""{
newArray.append(separator)
}else{
newArray.append(separator)
newArray.append(arr[count] == "" ? separator : arr[count])
}
}
}else{
newArray.append(arr[count] == "" ? separator : arr[count])
}
count += 1
}
return newArray
}
print(getResult(input: "ABCABDEA", separator: "AB"))
print(getResult(input: "ABCABDEA", separator: "A"))
```
>
> ["AB", "C", "AB", "DEA"]
>
>
> ["A", "BC", "A", "BDE", "A"]
>
>
>
Upvotes: 1 [selected_answer]<issue_comment>username_4: I think I finally got what you need from the question: to split a string and keep the delimiters. You can achieve this via a nice `String` extension:
```
extension String {
func splitAndKeep(separator: Character) -> [String] {
let separatorIndexes = enumerated().flatMap { $0.1 == separator ? index(startIndex, offsetBy: $0.0) : nil }
let separatorRangeIndexes = separatorIndexes.flatMap { [$0, index(after: $0)] }
let splitIndexes = [startIndex] + separatorRangeIndexes + [endIndex]
let splitRangesEnds = zip(splitIndexes, splitIndexes.dropFirst()).filter { $0.0 < $0.1 }
return splitRangesEnds.map { String(self[$0.0..<$0.1]) }
}
}
```
`splitAndKeep` gradually computes the information needed to build the array of components to use.
Usage:
```
print("ABCDEF".splitAndKeep(separator: "B"))
// ["A", "B", "CDEF"]
print("ABCDEF".splitAndKeep(separator: "A"))
// ["A", "BCDEF"]
print("BBBAAA".splitAndKeep(separator: "B"))
// ["B", "B", "B", "AAA"]
print("BABBCDEDBB".splitAndKeep(separator: "B"))
// ["B", "A", "B", "B", "CDED", "B", "B"]
```
Upvotes: 0 |
2018/03/15 | 610 | 2,019 | <issue_start>username_0: I read the documentation on Procs in the Crystal Language book on the organizations’s site. What exactly is a proc? I get that you define argument and return types and use a call method to call the proc which makes me think it’s a function. But why use a proc? What is it for?<issue_comment>username_1: *You cannot pass methods into other methods (but you can pass procs into methods), and methods cannot return other methods (but they can return procs).*
Also Proc captures variables from the scope where it has been defined:
```
a = 1
b = 2
proc = ->{ a + b }
def foo(proc)
bar(proc)
end
def bar(proc)
a = 5
b = 6
1 + proc.call
end
puts bar(proc) # => 4
```
A powerful feature is to convert a block to Proc and pass it to a method, so you can [forward it](https://crystal-lang.org/docs/syntax_and_semantics/block_forwarding.html):
```
def int_to_int(█ : Int32 -> Int32)
block
end
proc = int_to_int { |x| x + 1 }
proc.call(1) #=> 2
```
Also, as @username_2 commented, Proc can be used as a [closure](https://crystal-lang.org/docs/syntax_and_semantics/closures.html):
```
def minus(num)
->(n : Int32) { num - n }
end
minus_20 = minus(20)
minus_20.call(7) # => 13
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: The language reference explains [Proc](https://crystal-lang.org/docs/syntax_and_semantics/literals/proc.html) pretty well actually:
>
> A [Proc](https://crystal-lang.org/api/Proc.html) represents a function pointer with an optional context (the closure data).
>
>
>
So yes, a proc is essentially like a function. In contrast to a plain block, it essentially holds a reference to a block so it can be stored and passed around and also provides a closure.
Upvotes: 2 <issue_comment>username_3: A Proc is simply a function/method without a name. You can pass it around as a variable, and it can refer to variables in it's enclosing scope (it's a closure). They are often used as a way of passing method blocks around as variables.
Upvotes: 2 |
2018/03/15 | 629 | 1,993 | <issue_start>username_0: Looked at *all* the articles on search for this and no answers that work -- on Ubuntu 16.04 I'm getting:
```
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/msqli.so' - /usr/lib/php/20151012/msqli.so: cannot open shared object file: No such file or directory in Unknown on line 0
```
`msqli.so` is definitely there in the folder cited above and is owned by root and is excutable. Folder and parent folders are owned by root. Hell of it is, phpmyadmin is running fine and can see and operate on the mySQL databases just fine. Do I need to chown folders/files to mysql or php entities? Just reinstalled Apache/php/mysql today and that did not fix it - all latest versions. Trying to use Eclipse IDE but this code fails on web server, too. Also tried in `php.ini` extensions pdo\_`msql.so` and `msqlnd.so` and related coding techniques, but they all resulted in messages like the above (but with appropriate .so filename) so I suspect its 'environmental' something wrong in setup. `phpinfo()`; suggests the drivers are all there and working.<issue_comment>username_1: Solved it [with help from this post](https://www.linuxquestions.org/questions/slackware-14/php-7-1-in-testing-%BB-unable-to-load-dynamic-library-mysqli-so-4175618544/).
Changed php.ini:
```
extension=/usr/lib/php/20151012/mysqli.so
extension=/usr/lib/php/20151012/mysqlnd.so
```
to
```
extension=/usr/lib/php/20151012/mysqlnd.so
extension=/usr/lib/php/20151012/mysqli.so
```
ie: reversed the order of the 2 entries to put mysqlnd.so first.
Now I am all happy and telecomputing with alacrity and enthusiasm.
Upvotes: 3 <issue_comment>username_2: It seems that uninstalling all versions of php with
```
sudo apt-get purge `dpkg -l | grep php | awk '{print $2}' | tr "\n" " "`
```
and only installing the latest version with
```
apt install php libapache2-mod-php php-mysql php-xml php-soap php-gd php-mbstring
```
solved the problem for me.
Upvotes: 3 |
2018/03/15 | 438 | 1,323 | <issue_start>username_0: I'm trying to import modified `WITs` to a existing project. But, It was showing the below error:
>
> Microsoft.TeamFoundation.WorkItemTracking.Server.ProvisioningImportEventsCallback
>
>
>
Earlier it was working fine. But, now the issue started.
What could be the possible solution for this? I just wanted to upload WITs through Command prompt(witadmin.exe) only. Any hints/information would help<issue_comment>username_1: Solved it [with help from this post](https://www.linuxquestions.org/questions/slackware-14/php-7-1-in-testing-%BB-unable-to-load-dynamic-library-mysqli-so-4175618544/).
Changed php.ini:
```
extension=/usr/lib/php/20151012/mysqli.so
extension=/usr/lib/php/20151012/mysqlnd.so
```
to
```
extension=/usr/lib/php/20151012/mysqlnd.so
extension=/usr/lib/php/20151012/mysqli.so
```
ie: reversed the order of the 2 entries to put mysqlnd.so first.
Now I am all happy and telecomputing with alacrity and enthusiasm.
Upvotes: 3 <issue_comment>username_2: It seems that uninstalling all versions of php with
```
sudo apt-get purge `dpkg -l | grep php | awk '{print $2}' | tr "\n" " "`
```
and only installing the latest version with
```
apt install php libapache2-mod-php php-mysql php-xml php-soap php-gd php-mbstring
```
solved the problem for me.
Upvotes: 3 |
2018/03/15 | 570 | 2,081 | <issue_start>username_0: I have a textbox where i can type double quoted words like: hello i am "steve" and i can successfully insert the string into my database after mysqli\_real\_escape\_string
```
```
php below:
```
$text_data = $_POST['description']; // hello my name is "steve"
$final_text = mysqli_real_escape_string($this->conn,$text_data);
// the above without removing double quotes can be inserted into the db
but if it is single quotes and I convert to double quotes then it cannot be inserted.
$text_data = $_POST['description']; // hello my name is 'steve'
$final_text = str_replace("'",'"',$text_data);
$final_text = mysqli_real_escape_string($this->conn,$text_data);
```
so my questions are:
1. how come it works with double quotes? doesn't it needs to be removed or replaced with "/ something?
2. if the first case: double quotes work fine, then how come the second case when converted from single to double quotes cannot be inserted into the db?
Thanks a lot in advance<issue_comment>username_1: `MySQL` treats single quote as a string `END`. In order to `INSERT` string with single quotes you have to `ESCAPE` it as `\'Hello World\'`
This should work seamlessly
`$text_data = "hello my name is \'steve\'";`
Upvotes: 0 <issue_comment>username_2: A couple things..
First I would do some reading on the differences between the single quote and the double quote's behaviors. Just so going forward you have a basis for the differences between the two.
Secondly lets look at the logic of your code:
If I replace the single quotes in your code like your code suggest your statement will look like this:
```
"hello my name is "steve""
```
No lets look closly at what happens between " and steve.
```
"hello my name is " steve ""
```
The reason your query is failing, I believe is because steve is not quoted anymore.
Using prepared statement is really your best solution to the problem.
Hope that helps
UPDATED:
```
$text_data = "hello my name is 'steve'";
$final_text = str_replace("'",'\"',$text_data);
```
Upvotes: -1 [selected_answer] |